Skip to content

Automate browser based workflows with AI

Rename CodeBlock redaction test constant so OSS CodeQL stops flagging it (SKY-16595) (#8624)

Andrew Neilsone93325e95e1b
diff --git a/alembic/versions/2026_09_21_1843-317a80337f2e_add_workflow_run_routing.py b/alembic/versions/2026_09_21_1843-317a80337f2e_add_workflow_run_routing.py
new file mode 100644
index 000000000..4a506f04f
--- /dev/null
+++ b/alembic/versions/2026_09_21_1843-317a80337f2e_add_workflow_run_routing.py
@@ -0,0 +1,31 @@
+"""add workflow run routing
+
+Revision ID: 317a80337f2e
+Revises: 2dace0960323
+Create Date: 2026-09-21T18:43:50.129051+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "317a80337f2e"
+down_revision: Union[str, None] = "2dace0960323"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("workflow_runs", sa.Column("task_queue", sa.String(), nullable=True))
+ op.add_column("workflow_runs", sa.Column("target_cluster", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("workflow_runs", "target_cluster")
+ op.drop_column("workflow_runs", "task_queue")
diff --git a/dev_scripts/fake_captcha_site/hcaptcha/api.js b/dev_scripts/fake_captcha_site/hcaptcha/api.js
new file mode 100644
index 000000000..47b118dd9
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/hcaptcha/api.js
@@ -0,0 +1,53 @@
+// Local stand-in for https://js.hcaptcha.com/1/api.js in invisible mode. Measured from the real script before
+// execute(): .h-captcha is 1264x0, the checkbox iframe display:none, the challenge iframe hidden at y=-9999.
+(function () {
+ var widget = document.querySelector(".h-captcha");
+ if (!widget) {
+ return;
+ }
+ var siteKey = widget.getAttribute("data-sitekey");
+ var callbackName = widget.getAttribute("data-callback");
+
+ var checkboxFrame = document.createElement("iframe");
+ checkboxFrame.setAttribute("aria-hidden", "true");
+ checkboxFrame.setAttribute("data-hcaptcha-response", "");
+ checkboxFrame.src = "hcaptcha_widget.html#frame=checkbox-invisible";
+ checkboxFrame.style.display = "none";
+ widget.appendChild(checkboxFrame);
+
+ var response = document.createElement("textarea");
+ response.name = "h-captcha-response";
+ response.id = "h-captcha-response";
+ response.style.display = "none";
+ widget.appendChild(response);
+
+ var legacyResponse = document.createElement("textarea");
+ legacyResponse.name = "g-recaptcha-response";
+ legacyResponse.style.display = "none";
+ widget.appendChild(legacyResponse);
+
+ var challengeFrame = document.createElement("iframe");
+ challengeFrame.src = "hcaptcha_widget.html#frame=challenge";
+ challengeFrame.style.cssText =
+ "position:absolute;left:9px;top:-9999px;width:300px;height:150px;border:0;visibility:hidden;";
+ document.body.appendChild(challengeFrame);
+
+ window.hcaptcha = {
+ execute: function () {
+ return new Promise(function (resolve) {
+ setTimeout(function () {
+ var token = "fixture-invisible-token." + siteKey;
+ response.value = token;
+ legacyResponse.value = token;
+ if (callbackName && typeof window[callbackName] === "function") {
+ window[callbackName](token);
+ }
+ resolve({ response: token });
+ }, 300);
+ });
+ },
+ getResponse: function () {
+ return response.value;
+ },
+ };
+})();
diff --git a/dev_scripts/fake_captcha_site/hcaptcha_widget.html b/dev_scripts/fake_captcha_site/hcaptcha_widget.html
new file mode 100644
index 000000000..e824757d9
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/hcaptcha_widget.html
@@ -0,0 +1,3 @@
+<meta charset="utf-8">
+<title>hCaptcha widget</title>
+<body style="margin:0;font-family:system-ui,sans-serif;font-size:12px">Verify you are human</body>
diff --git a/dev_scripts/fake_captcha_site/image_captcha.html b/dev_scripts/fake_captcha_site/image_captcha.html
new file mode 100644
index 000000000..fbc28f878
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/image_captcha.html
@@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Test Page - Image-Based Captcha</title>
+ <style>
+ body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; }
+ .form-group { margin-bottom: 15px; }
+ label { display: block; margin-bottom: 5px; font-weight: bold; }
+ input[type="text"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
+ .captcha-box { background: #f0f0f0; border: 1px solid #ddd; padding: 15px; margin: 15px 0; border-radius: 4px; }
+ button { background: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
+ .result { margin-top: 15px; padding: 10px; border-radius: 4px; display: none; }
+ .success { background: #dff0d8; color: #3c763d; }
+ .error { background: #f2dede; color: #a94442; }
+ .captcha-image-container { text-align: center; margin: 10px 0; }
+ </style>
+</head>
+<body>
+ <h1>Record Search</h1>
+ <p>Enter information below to search public records.</p>
+
+ <form id="searchForm" onsubmit="return validateForm()">
+ <div class="form-group">
+ <label for="firstName">First Name</label>
+ <input type="text" id="firstName" name="firstName" placeholder="Enter first name">
+ </div>
+
+ <div class="form-group">
+ <label for="lastName">Last Name</label>
+ <input type="text" id="lastName" name="lastName" placeholder="Enter last name">
+ </div>
+
+ <div class="captcha-box">
+ <p>Type the characters you see in the image below:</p>
+ <div class="captcha-image-container">
+ <svg id="captchaImage" width="200" height="60" xmlns="http://www.w3.org/2000/svg">
+ <rect width="200" height="60" fill="#e8e8e8" stroke="#999" stroke-width="1"/>
+ </svg>
+ </div>
+ <div class="form-group">
+ <label for="captchaAnswer">Enter Captcha</label>
+ <input type="text" id="captchaAnswer" name="captchaAnswer" placeholder="Type the characters shown above">
+ </div>
+ </div>
+
+ <button type="submit">Search</button>
+ </form>
+
+ <div id="result" class="result"></div>
+
+ <script>
+ function generateCaptchaText(length) {
+ const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
+ let result = '';
+ for (let i = 0; i < length; i++) {
+ result += chars[Math.floor(Math.random() * chars.length)];
+ }
+ return result;
+ }
+
+ function renderCaptchaSVG(text) {
+ const svg = document.getElementById('captchaImage');
+ // Clear existing text elements
+ while (svg.childNodes.length > 1) {
+ svg.removeChild(svg.lastChild);
+ }
+
+ // Add noise lines
+ for (let i = 0; i < 5; i++) {
+ const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
+ line.setAttribute('x1', Math.random() * 200);
+ line.setAttribute('y1', Math.random() * 60);
+ line.setAttribute('x2', Math.random() * 200);
+ line.setAttribute('y2', Math.random() * 60);
+ line.setAttribute('stroke', `hsl(${Math.random()*360}, 30%, 70%)`);
+ line.setAttribute('stroke-width', '1');
+ svg.appendChild(line);
+ }
+
+ // Add characters with distortion
+ for (let i = 0; i < text.length; i++) {
+ const t = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ const x = 20 + i * 30;
+ const y = 35 + (Math.random() * 15 - 7);
+ const rotation = Math.random() * 30 - 15;
+ t.setAttribute('x', x);
+ t.setAttribute('y', y);
+ t.setAttribute('font-size', `${22 + Math.random() * 8}`);
+ t.setAttribute('font-family', 'monospace');
+ t.setAttribute('fill', `hsl(${Math.random()*360}, 50%, 35%)`);
+ t.setAttribute('transform', `rotate(${rotation}, ${x}, ${y})`);
+ t.textContent = text[i];
+ svg.appendChild(t);
+ }
+ }
+
+ let captchaText = generateCaptchaText(6);
+ renderCaptchaSVG(captchaText);
+
+ function validateForm() {
+ const userAnswer = document.getElementById('captchaAnswer').value;
+ const resultDiv = document.getElementById('result');
+ resultDiv.style.display = 'block';
+
+ if (userAnswer.toLowerCase() === captchaText.toLowerCase()) {
+ resultDiv.className = 'result success';
+ resultDiv.textContent = 'Captcha verified successfully! Search results would appear here.';
+ } else {
+ resultDiv.className = 'result error';
+ resultDiv.textContent = `Incorrect captcha. Try again.`;
+ captchaText = generateCaptchaText(6);
+ renderCaptchaSVG(captchaText);
+ document.getElementById('captchaAnswer').value = '';
+ }
+ return false;
+ }
+ </script>
+</body>
+</html>
diff --git a/dev_scripts/fake_captcha_site/instruction_captcha.html b/dev_scripts/fake_captcha_site/instruction_captcha.html
new file mode 100644
index 000000000..b2cd20a67
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/instruction_captcha.html
@@ -0,0 +1,124 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Test Page - Instruction-Based Captcha</title>
+ <style>
+ body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; }
+ .form-group { margin-bottom: 15px; }
+ label { display: block; margin-bottom: 5px; font-weight: bold; }
+ input[type="text"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
+ .captcha-box { background: #f0f0f0; border: 1px solid #ddd; padding: 15px; margin: 15px 0; border-radius: 4px; }
+ .captcha-instruction { font-size: 16px; color: #333; }
+ button { background: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
+ button:hover { background: #45a049; }
+ .result { margin-top: 15px; padding: 10px; border-radius: 4px; display: none; }
+ .success { background: #dff0d8; color: #3c763d; }
+ .error { background: #f2dede; color: #a94442; }
+ </style>
+</head>
+<body>
+ <h1>Record Search</h1>
+ <p>Enter information below to search public records.</p>
+
+ <form id="searchForm" onsubmit="return validateForm()">
+ <div class="form-group">
+ <label for="firstName">First Name</label>
+ <input type="text" id="firstName" name="firstName" placeholder="Enter first name">
+ </div>
+
+ <div class="form-group">
+ <label for="lastName">Last Name</label>
+ <input type="text" id="lastName" name="lastName" placeholder="Enter last name">
+ </div>
+
+ <div class="captcha-box">
+ <p class="captcha-instruction" id="captchaInstruction"></p>
+ <div class="form-group">
+ <label for="captchaAnswer">Security Verification</label>
+ <input type="text" id="captchaAnswer" name="captchaAnswer" placeholder="Enter your answer">
+ </div>
+ </div>
+
+ <button type="submit">Search</button>
+ </form>
+
+ <div id="result" class="result"></div>
+
+ <script>
+ // Generate a random captcha challenge
+ function generateCaptcha() {
+ const types = [
+ generateCapitalLettersCaptcha,
+ generateLowercaseLettersCaptcha,
+ generateDigitsCaptcha,
+ ];
+ const generator = types[Math.floor(Math.random() * types.length)];
+ return generator();
+ }
+
+ function generateCapitalLettersCaptcha() {
+ const str = generateRandomString(7);
+ const answer = str.replace(/[^A-Z]/g, '');
+ return {
+ instruction: `Enter all the capital letters from '${str}'`,
+ answer: answer
+ };
+ }
+
+ function generateLowercaseLettersCaptcha() {
+ const str = generateRandomString(7);
+ const answer = str.replace(/[^a-z]/g, '');
+ return {
+ instruction: `Enter all the lowercase letters from '${str}'`,
+ answer: answer
+ };
+ }
+
+ function generateDigitsCaptcha() {
+ const str = generateRandomString(7);
+ const answer = str.replace(/[^0-9]/g, '');
+ return {
+ instruction: `Enter all the digits from '${str}'`,
+ answer: answer
+ };
+ }
+
+ function generateRandomString(length) {
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&';
+ let result = '';
+ // Ensure at least one uppercase, one lowercase, one digit
+ result += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(Math.random() * 26)];
+ result += 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)];
+ result += '0123456789'[Math.floor(Math.random() * 10)];
+ for (let i = 3; i < length; i++) {
+ result += chars[Math.floor(Math.random() * chars.length)];
+ }
+ // Shuffle
+ return result.split('').sort(() => Math.random() - 0.5).join('');
+ }
+
+ let currentCaptcha = generateCaptcha();
+ document.getElementById('captchaInstruction').textContent = currentCaptcha.instruction;
+
+ function validateForm() {
+ const userAnswer = document.getElementById('captchaAnswer').value;
+ const resultDiv = document.getElementById('result');
+ resultDiv.style.display = 'block';
+
+ if (userAnswer === currentCaptcha.answer) {
+ resultDiv.className = 'result success';
+ resultDiv.textContent = 'Captcha verified successfully! Search results would appear here.';
+ } else {
+ resultDiv.className = 'result error';
+ resultDiv.textContent = `Incorrect. Expected "${currentCaptcha.answer}" but got "${userAnswer}". Try again.`;
+ // Regenerate captcha on failure
+ currentCaptcha = generateCaptcha();
+ document.getElementById('captchaInstruction').textContent = currentCaptcha.instruction;
+ document.getElementById('captchaAnswer').value = '';
+ }
+ return false;
+ }
+ </script>
+</body>
+</html>
diff --git a/dev_scripts/fake_captcha_site/invisible_hcaptcha.html b/dev_scripts/fake_captcha_site/invisible_hcaptcha.html
new file mode 100644
index 000000000..ecd36d49e
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/invisible_hcaptcha.html
@@ -0,0 +1,36 @@
+<meta charset="utf-8">
+<title>Apply - Warehouse Associate</title>
+<style>
+ body { font-family: system-ui, sans-serif; max-width: 640px; margin: 60px auto; }
+ label { display: block; margin: 16px 0 4px; }
+ input[type="text"], input[type="email"] { padding: 8px; width: 260px; }
+ button { margin-top: 24px; padding: 8px 20px; }
+</style>
+
+<h1>Warehouse Associate</h1>
+<p>Apply for this opening.</p>
+
+<form id="application" action="invisible_hcaptcha_results.html" method="get">
+ <label for="full-name">Full name</label>
+ <input type="text" id="full-name" name="full-name" autocomplete="off">
+
+ <label for="email">Email</label>
+ <input type="email" id="email" name="email" autocomplete="off">
+
+ <div class="h-captcha"
+ data-sitekey="10000000-ffff-ffff-ffff-000000000001"
+ data-size="invisible"
+ data-callback="onCaptchaToken"></div>
+
+ <button type="button" id="apply-submit">Submit application</button>
+</form>
+
+<script>
+ function onCaptchaToken() {
+ document.getElementById('application').submit();
+ }
+ document.getElementById('apply-submit').addEventListener('click', function () {
+ window.hcaptcha.execute();
+ });
+</script>
+<script src="hcaptcha/api.js" defer></script>
diff --git a/dev_scripts/fake_captcha_site/invisible_hcaptcha_results.html b/dev_scripts/fake_captcha_site/invisible_hcaptcha_results.html
new file mode 100644
index 000000000..64575c5d4
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/invisible_hcaptcha_results.html
@@ -0,0 +1,14 @@
+<meta charset="utf-8">
+<title>Application received</title>
+<style>
+ body { font-family: system-ui, sans-serif; max-width: 640px; margin: 60px auto; }
+ #confirmation { font-size: 20px; }
+</style>
+
+<h1>Warehouse Associate</h1>
+<p id="confirmation">Application received. Thanks, <span id="applicant">-</span>.</p>
+
+<script>
+ var params = new URLSearchParams(location.search);
+ document.getElementById('applicant').textContent = params.get('full-name') || 'applicant';
+</script>
diff --git a/dev_scripts/fake_captcha_site/invisible_recaptcha.html b/dev_scripts/fake_captcha_site/invisible_recaptcha.html
new file mode 100644
index 000000000..bfa398602
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/invisible_recaptcha.html
@@ -0,0 +1,42 @@
+<meta charset="utf-8">
+<title>Member Lookup</title>
+<style>
+ body { font-family: system-ui, sans-serif; max-width: 640px; margin: 60px auto; }
+ label { display: block; margin: 16px 0 4px; }
+ input[type="text"] { padding: 8px; width: 260px; }
+ button { margin-top: 20px; padding: 8px 20px; }
+ button[disabled] { opacity: 0.5; cursor: not-allowed; }
+ .grecaptcha-badge {
+ position: fixed; right: 14px; bottom: 14px; width: 256px; height: 60px;
+ border: 1px solid #d3d3d3; border-radius: 2px; background: #f9f9f9;
+ box-shadow: 0 0 4px rgba(0,0,0,.2); overflow: hidden;
+ }
+ #results { margin-top: 28px; }
+</style>
+
+<h1>Member Lookup</h1>
+<p>Search the public member directory.</p>
+
+<form id="lookup" action="/invisible_recaptcha_results.html" method="get">
+ <label for="member-name">Member name</label>
+ <input type="text" id="member-name" name="member-name" autocomplete="off">
+ <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" value="">
+ <button type="submit" id="search" disabled>Search</button>
+</form>
+
+<div id="results"></div>
+
+<div class="grecaptcha-badge" data-style="bottomright">
+ <iframe src="/recaptcha/api2/anchor?k=6LtSkyvernFixtureKey&amp;size=invisible"
+ title="reCAPTCHA" width="256" height="60" frameborder="0" scrolling="no"></iframe>
+</div>
+
+<script src="/recaptcha/api.js?render=6LtSkyvernFixtureKey"></script>
+<script>
+ grecaptcha.ready(function () {
+ grecaptcha.execute('6LtSkyvernFixtureKey', { action: 'search' }).then(function (token) {
+ document.getElementById('g-recaptcha-response').value = token;
+ document.getElementById('search').disabled = false;
+ });
+ });
+</script>
diff --git a/dev_scripts/fake_captcha_site/invisible_recaptcha_results.html b/dev_scripts/fake_captcha_site/invisible_recaptcha_results.html
new file mode 100644
index 000000000..36674248c
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/invisible_recaptcha_results.html
@@ -0,0 +1,19 @@
+<meta charset="utf-8">
+<title>Member Lookup - Results</title>
+<style>
+ body { font-family: system-ui, sans-serif; max-width: 640px; margin: 60px auto; }
+ table { border-collapse: collapse; margin-top: 20px; }
+ th, td { border: 1px solid #ccc; padding: 6px 12px; text-align: left; }
+</style>
+
+<h1>Member Lookup</h1>
+<h2>Results</h2>
+<table>
+ <tr><th>Name</th><th>Member ID</th><th>Status</th></tr>
+ <tr><td id="match-name">-</td><td>MBR-40199</td><td>Active</td></tr>
+</table>
+
+<script>
+ var name = new URLSearchParams(location.search).get('member-name') || 'Unknown';
+ document.getElementById('match-name').textContent = name;
+</script>
diff --git a/dev_scripts/fake_captcha_site/recaptcha/anchor.html b/dev_scripts/fake_captcha_site/recaptcha/anchor.html
new file mode 100644
index 000000000..5d2e1c45d
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/recaptcha/anchor.html
@@ -0,0 +1,11 @@
+<meta charset="utf-8">
+<title>reCAPTCHA</title>
+<style>
+ body { margin: 0; font-family: system-ui, sans-serif; font-size: 11px; color: #555; }
+ .badge { display: flex; align-items: center; height: 60px; padding: 0 10px; gap: 10px; }
+ .mark { width: 32px; height: 32px; border-radius: 50%; border: 3px solid #1c3aa9; }
+</style>
+<div class="badge">
+ <div class="mark"></div>
+ <div>protected by <strong>reCAPTCHA</strong><br>Privacy - Terms</div>
+</div>
diff --git a/dev_scripts/fake_captcha_site/recaptcha/api.js b/dev_scripts/fake_captcha_site/recaptcha/api.js
new file mode 100644
index 000000000..07a689f7c
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/recaptcha/api.js
@@ -0,0 +1,17 @@
+// Local stand-in for https://www.google.com/recaptcha/api.js?render=<sitekey>. It mints a score
+// token after a short delay and never escalates to a userverify/bframe interactive challenge,
+// which is the network shape this fixture exists to reproduce.
+window.grecaptcha = {
+ ready: function (callback) {
+ setTimeout(callback, 250);
+ },
+ execute: function (siteKey, options) {
+ return new Promise(function (resolve) {
+ setTimeout(function () {
+ resolve(
+ "fixture-v3-token." + siteKey + "." + (options && options.action),
+ );
+ }, 1200);
+ });
+ },
+};
diff --git a/dev_scripts/fake_captcha_site/serve.py b/dev_scripts/fake_captcha_site/serve.py
new file mode 100644
index 000000000..ca51faeb5
--- /dev/null
+++ b/dev_scripts/fake_captcha_site/serve.py
@@ -0,0 +1,47 @@
+"""Simple HTTP server for fake captcha test pages.
+
+Usage:
+ python dev_scripts/fake_captcha_site/serve.py
+
+Pages:
+ http://localhost:8888/instruction_captcha.html — Instruction-based captcha (no image)
+ http://localhost:8888/image_captcha.html — SVG image-based captcha
+ http://localhost:8888/invisible_recaptcha.html — Invisible reCAPTCHA v3, never escalates
+ http://localhost:8888/invisible_hcaptcha.html — Invisible hCaptcha, executed only on Submit
+"""
+
+import http.server
+import os
+import sys
+from typing import Any
+
+PORT = 8888
+DIRECTORY = os.path.dirname(os.path.abspath(__file__))
+
+
+class Handler(http.server.SimpleHTTPRequestHandler):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, directory=DIRECTORY, **kwargs)
+
+ def translate_path(self, path: str) -> str:
+ # Google serves the invisible widget's iframe from an extensionless /api2/anchor path.
+ if path.split("?", 1)[0] == "/recaptcha/api2/anchor":
+ path = "/recaptcha/anchor.html"
+ return super().translate_path(path)
+
+
+if __name__ == "__main__":
+ # Threading matters: a browser holds keep-alive connections open, and the single-threaded
+ # HTTPServer stops answering entirely for the rest of a run once one is parked on it.
+ with http.server.ThreadingHTTPServer(("", PORT), Handler) as httpd:
+ print(f"Serving fake captcha site at http://localhost:{PORT}/")
+ print(f" Instruction captcha: http://localhost:{PORT}/instruction_captcha.html")
+ print(f" Image captcha: http://localhost:{PORT}/image_captcha.html")
+ print(f" Invisible reCAPTCHA: http://localhost:{PORT}/invisible_recaptcha.html")
+ print(f" Invisible hCaptcha: http://localhost:{PORT}/invisible_hcaptcha.html")
+ print("Press Ctrl+C to stop.")
+ try:
+ httpd.serve_forever()
+ except KeyboardInterrupt:
+ print("\nStopped.")
+ sys.exit(0)
diff --git a/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx b/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx
index b048abdf0..ee3c94354 100644
--- a/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx
+++ b/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { StrictMode, useState } from "react";
+import { StrictMode, useState, type ComponentProps } from "react";
import {
act,
cleanup,
@@ -16,7 +16,6 @@ import type {
LegacyOnboardingStatePatch,
OnboardingState,
OnboardingStateResponse,
- QuestionnairePatchV1,
QuestionnaireStateV1,
} from "@/store/onboarding/types";
import { OnboardingContext } from "@/store/onboarding/useOnboardingState";
@@ -24,6 +23,8 @@ import { GetStartedModal } from "./GetStartedModal";
const mocks = vi.hoisted(() => ({
userId: "user-a",
+ orgId: null as string | null,
+ realDetails: false,
confirmed: vi.fn<(patch: ConfirmedPatch) => Promise<ConfirmedWriteResult>>(),
createWorkflow: vi.fn(),
legacyUpdate: vi.fn<(patch: LegacyOnboardingStatePatch) => void>(),
@@ -43,7 +44,7 @@ vi.mock("posthog-js/react", () => ({
useFeatureFlagVariantKey: () => "template-first",
}));
vi.mock("@clerk/clerk-react", () => ({
- useAuth: () => ({ userId: mocks.userId }),
+ useAuth: () => ({ userId: mocks.userId, orgId: mocks.orgId }),
useUser: () => ({
isLoaded: true,
user: { createdAt: new Date("2026-08-28T00:00:00Z") },
@@ -64,50 +65,53 @@ vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
vi.mock("./CopilotCTAStep", () => ({
CopilotCTAStep: () => null,
}));
-vi.mock("./QuestionnaireDetailsStep", () => ({
- QuestionnaireDetailsStep: ({
- completionAction,
- expectedRevision,
- externalError,
- isPending,
- onAction,
- onBack,
- }: {
- completionAction: "complete" | "update";
- expectedRevision: number;
- externalError?: string | null;
- isPending: boolean;
- onAction: (patch: QuestionnairePatchV1) => Promise<void>;
- onBack: () => void;
- }) => {
- const answerPatch = {
- version: 1 as const,
- mutation_id: `mutation-${completionAction}-${expectedRevision}`,
- expected_revision: expectedRevision,
- action: completionAction,
- role: "developer" as const,
- company_context: "startup" as const,
- scale_intent: "exploring" as const,
- referral_source: "search" as const,
- };
- return (
- <div>
- <span>{`details-${completionAction}-${expectedRevision}`}</span>
- {externalError ? <div role="alert">{externalError}</div> : null}
- <button
- type="button"
- disabled={isPending}
- onClick={() => void onAction(answerPatch)}
- >
- details-submit
- </button>
- <button type="button" onClick={onBack}>
- details-back
- </button>
- </div>
- );
- },
-}));
+vi.mock("./QuestionnaireDetailsStep", async () => {
+ const actual = await vi.importActual<
+ typeof import("./QuestionnaireDetailsStep")
+ >("./QuestionnaireDetailsStep");
+ return {
+ QuestionnaireDetailsStep: (
+ props: ComponentProps<typeof actual.QuestionnaireDetailsStep>,
+ ) => {
+ if (mocks.realDetails)
+ return <actual.QuestionnaireDetailsStep {...props} />;
+ const {
+ completionAction,
+ expectedRevision,
+ externalError,
+ isPending,
+ onAction,
+ onBack,
+ } = props;
+ const answerPatch = {
+ version: 1 as const,
+ mutation_id: `mutation-${completionAction}-${expectedRevision}`,
+ expected_revision: expectedRevision,
+ action: completionAction,
+ role: "developer" as const,
+ company_context: "startup" as const,
+ scale_intent: "exploring" as const,
+ referral_source: "search" as const,
+ };
+ return (
+ <div>
+ <span>{`details-${completionAction}-${expectedRevision}`}</span>
+ {externalError ? <div role="alert">{externalError}</div> : null}
+ <button
+ type="button"
+ disabled={isPending}
+ onClick={() => void onAction(answerPatch)}
+ >
+ details-submit
+ </button>
+ <button type="button" onClick={onBack}>
+ details-back
+ </button>
+ </div>
+ );
+ },
+ };
+});
const baseState: OnboardingState = {
tour_completed_at: null,
@@ -151,6 +155,7 @@ function response(
): OnboardingStateResponse {
return {
onboarding_state: { ...baseState, ...overrides },
+ project_owner_supported: true,
launch_date_at_signup: "2026-01-01T00:00:00Z",
recovery_guidance_assignment: null,
};
@@ -229,6 +234,8 @@ beforeEach(() => {
mocks.confirmed.mockResolvedValue(response({ user_intent: "fill_forms" }));
mocks.telemetry.questionnaireShown.mockReturnValue(true);
mocks.userId = "user-a";
+ mocks.orgId = null;
+ mocks.realDetails = false;
});
afterEach(() => {
@@ -238,6 +245,142 @@ afterEach(() => {
});
describe("GetStartedModal", () => {
+ it.each([undefined, false])(
+ "keeps owner capture hidden without backend support: %s",
+ async (supported) => {
+ mocks.realDetails = true;
+ mocks.confirmed.mockImplementation(async (patch) =>
+ patch.questionnaire_prompt
+ ? reservedResponse()
+ : {
+ ...response({ user_intent: "fill_forms" }),
+ organization_id: "o_test",
+ project_owner_supported: supported,
+ },
+ );
+ render(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ await screen.findByRole("button", { name: "Complete and continue" });
+ expect(
+ screen.queryByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ ).toBeNull();
+ expect(screen.getAllByRole("combobox")).toHaveLength(4);
+ },
+ );
+
+ it.each(["Complete and continue", "Skip", "Close"])(
+ "only saves the draft on explicit completion: %s",
+ async (action) => {
+ mocks.realDetails = true;
+ mocks.confirmed.mockImplementation(async (patch) => {
+ if (patch.questionnaire_prompt)
+ return { ...reservedResponse(), organization_id: "o_test" };
+ if (!patch.questionnaire)
+ return {
+ ...response({ user_intent: "fill_forms" }),
+ organization_id: "o_test",
+ };
+ const q = patch.questionnaire;
+ return {
+ ...response({
+ user_intent: "fill_forms",
+ questionnaire: questionnaire({
+ last_mutation_id: q.mutation_id,
+ status: q.action === "skip" ? "skipped" : "completed",
+ }),
+ }),
+ organization_id: "o_test",
+ };
+ });
+ render(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ );
+ fireEvent.change(screen.getByLabelText("Work email"), {
+ target: { value: "[email protected]" },
+ });
+ screen.getAllByRole("combobox").forEach((control) => {
+ fireEvent.click(control);
+ fireEvent.click(screen.getAllByRole("option")[0]!);
+ });
+ fireEvent.click(screen.getByRole("button", { name: action }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ const write = mocks.confirmed.mock.calls.find(
+ ([patch]) => patch.questionnaire,
+ )?.[0].questionnaire;
+ if (action === "Complete and continue") {
+ expect(write).toHaveProperty("project_owner", {
+ action: "set",
+ expected_organization_id: "o_test",
+ professional_email: "[email protected]",
+ });
+ } else {
+ expect(write).toEqual({
+ version: 1,
+ action: "skip",
+ mutation_id: expect.any(String),
+ expected_revision: 0,
+ });
+ }
+ },
+ );
+
+ it("drops the real optional draft on an organization switch", async () => {
+ mocks.realDetails = true;
+ mocks.orgId = "org_a";
+ mocks.confirmed
+ .mockResolvedValueOnce({ ...reservedResponse(), organization_id: "o_a" })
+ .mockResolvedValueOnce({
+ ...response({ user_intent: "fill_forms" }),
+ organization_id: "o_a",
+ });
+ const view = render(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ );
+ fireEvent.change(screen.getByLabelText("Name"), {
+ target: { value: "Synthetic Owner" },
+ });
+ mocks.confirmed
+ .mockResolvedValueOnce({ ...reservedResponse(), organization_id: "o_b" })
+ .mockResolvedValueOnce({
+ ...response({ user_intent: "fill_forms" }),
+ organization_id: "o_b",
+ });
+ mocks.orgId = "org_b";
+ view.rerender(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ );
+ expect(screen.getByLabelText("Name")).toHaveProperty("value", "");
+ expect(
+ mocks.confirmed.mock.calls.some(([patch]) => patch.questionnaire),
+ ).toBe(false);
+ });
+
it("reserves once, completes, stamps dismissal, and closes", async () => {
const reservation = deferred<ConfirmedWriteResult>();
const completion = deferred<OnboardingStateResponse>();
diff --git a/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx b/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx
index 405e207cf..ca178039d 100644
--- a/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx
+++ b/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx
@@ -135,6 +135,8 @@ function GetStartedModalForUser() {
const [selectedIntent, setSelectedIntent] = useState<string | null>(null);
const [questionnaire, setQuestionnaire] =
useState<QuestionnaireStateV1 | null>(null);
+ const [questionnaireOrganizationId, setQuestionnaireOrganizationId] =
+ useState<string | null>(null);
const [intentPending, setIntentPending] = useState(false);
const [decidingPlaceholderVisible, setDecidingPlaceholderVisible] =
useState(false);
@@ -388,10 +390,19 @@ function GetStartedModalForUser() {
if ("code" in response) {
throw new Error(`Intent confirmation failed: ${response.code}`);
}
- if (!isOpenRef.current || visitId !== openVisitRef.current) {
+ if (
+ !mountedRef.current ||
+ !isOpenRef.current ||
+ visitId !== openVisitRef.current
+ ) {
return;
}
const nextState = response.onboarding_state;
+ setQuestionnaireOrganizationId(
+ response.project_owner_supported === true
+ ? (response.organization_id ?? null)
+ : null,
+ );
if (!isQuestionnaireUserIntentV1(nextState.user_intent)) {
setOwner({ kind: "closed" });
return;
@@ -457,6 +468,7 @@ function GetStartedModalForUser() {
previousQuestionnaire: QuestionnaireStateV1 | null,
nextQuestionnaire: QuestionnaireStateV1,
primaryIntent: string | null,
+ organizationId: string | null,
) {
if (nextQuestionnaire.last_mutation_id !== patch.mutation_id) return;
const eventName = `onboarding_questionnaire_${
@@ -466,7 +478,7 @@ function GetStartedModalForUser() {
? "completed"
: "updated"
}`;
- const eventKey = `${nextQuestionnaire.response_id}:${nextQuestionnaire.revision}:${eventName}`;
+ const eventKey = `${organizationId}:${nextQuestionnaire.response_id}:${nextQuestionnaire.revision}:${eventName}`;
if (confirmedEventsRef.current.has(eventKey)) return;
if (patch.action === "skip") {
if (nextQuestionnaire.status !== "skipped") return;
@@ -476,6 +488,7 @@ function GetStartedModalForUser() {
revision: nextQuestionnaire.revision,
disposition: "skip",
statusAfter: "skipped",
+ organizationId,
});
return;
}
@@ -490,6 +503,8 @@ function GetStartedModalForUser() {
revision: nextQuestionnaire.revision,
primaryIntent,
answers,
+ organizationId,
+ projectOwner: nextQuestionnaire.project_owner,
});
return;
}
@@ -501,6 +516,8 @@ function GetStartedModalForUser() {
primaryIntent,
previousStatus: previousQuestionnaire.status,
answers,
+ organizationId,
+ projectOwner: nextQuestionnaire.project_owner,
});
}
@@ -515,9 +532,15 @@ function GetStartedModalForUser() {
try {
const response = await updateStateConfirmed({ questionnaire: patch });
if ("code" in response) {
+ if (response.code === "project_owner_invalid")
+ throw new Error(response.code);
throw new Error(`Questionnaire confirmation failed: ${response.code}`);
}
- if (!isOpenRef.current || visitId !== openVisitRef.current) {
+ if (
+ !mountedRef.current ||
+ !isOpenRef.current ||
+ visitId !== openVisitRef.current
+ ) {
return;
}
const nextQuestionnaire = response.onboarding_state.questionnaire;
@@ -529,6 +552,7 @@ function GetStartedModalForUser() {
previousQuestionnaire,
nextQuestionnaire,
response.onboarding_state.user_intent,
+ response.organization_id ?? null,
);
setQuestionnaire(nextQuestionnaire);
if (patch.action === "complete") {
@@ -648,6 +672,7 @@ function GetStartedModalForUser() {
<QuestionnaireDetailsStep
completionAction={questionnaire ? "update" : "complete"}
expectedRevision={questionnaire?.revision ?? 0}
+ organizationId={questionnaireOrganizationId}
initialAnswers={answersFromQuestionnaire(questionnaire)}
externalError={intentError}
isPending={questionnairePending}
@@ -748,8 +773,12 @@ function GetStartedModalForUser() {
}
function GetStartedModal() {
- const { userId } = useAuth();
- return <GetStartedModalForUser key={userId ?? "signed-out"} />;
+ const { userId, orgId } = useAuth();
+ return (
+ <GetStartedModalForUser
+ key={JSON.stringify([userId ?? null, orgId ?? null])}
+ />
+ );
}
export { GetStartedModal };
diff --git a/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx
index b315540f4..efa6ba4f0 100644
--- a/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx
+++ b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx
@@ -51,6 +51,7 @@ function renderDetails({
<QuestionnaireDetailsStep
completionAction={action}
expectedRevision={revision}
+ organizationId="o_test"
initialAnswers={initialAnswers}
externalError={externalError}
isPending={isPending}
@@ -82,6 +83,108 @@ afterEach(() => {
});
describe("QuestionnaireDetailsStep", () => {
+ it.each([
+ ["Name", " Example Owner ", { name: "Example Owner" }],
+ [
+ "Work email",
+ { professional_email: "[email protected]" },
+ ],
+ ["Role", "Project lead", { role: "Project lead" }],
+ ] as const)(
+ "saves %s independently with confirmed organization",
+ async (label, value, fields) => {
+ const { onAction } = renderDetails({ initialAnswers: ANSWERS });
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ );
+ fireEvent.change(screen.getByLabelText(label), { target: { value } });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Complete and continue" }),
+ );
+ await waitFor(() => expect(onAction).toHaveBeenCalledOnce());
+ expect(submitted(onAction)).toEqual(
+ expect.objectContaining({
+ ...ANSWERS,
+ project_owner: {
+ action: "set",
+ expected_organization_id: "o_test",
+ ...fields,
+ },
+ }),
+ );
+ },
+ );
+
+ it.each(["Skip", "Discard owner details and continue"])(
+ "%s discards invalid drafts without extra requests or validation",
+ async (action) => {
+ const { onAction } = renderDetails({ initialAnswers: ANSWERS });
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ );
+ fireEvent.change(screen.getByLabelText("Name"), {
+ target: { value: "Example Owner" },
+ });
+ fireEvent.change(screen.getByLabelText("Work email"), {
+ target: { value: "invalid" },
+ });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Complete and continue" }),
+ );
+ expect(onAction).not.toHaveBeenCalled();
+ expect(
+ screen.getByLabelText("Work email").getAttribute("aria-invalid"),
+ ).toBe("true");
+ fireEvent.click(screen.getByRole("button", { name: action }));
+ await waitFor(() => expect(onAction).toHaveBeenCalledOnce());
+ expect(submitted(onAction)).toEqual({
+ version: 1,
+ mutation_id: expect.any(String),
+ expected_revision: 0,
+ action: action === "Skip" ? "skip" : "complete",
+ ...(action === "Skip" ? {} : ANSWERS),
+ });
+ expect(screen.getByLabelText("Name")).toHaveProperty("value", "");
+ expect(screen.getByLabelText("Work email")).toHaveProperty("value", "");
+ },
+ );
+
+ it("omits an all-blank owner and reuses a mutation only for the same report", async () => {
+ const onAction = vi.fn<Action>().mockRejectedValue(new Error("offline"));
+ renderDetails({ initialAnswers: ANSWERS, onAction });
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: /Who else owns this automation project/,
+ }),
+ );
+ const name = screen.getByLabelText("Name");
+ const submit = screen.getByRole("button", {
+ name: "Complete and continue",
+ });
+ fireEvent.change(name, { target: { value: " " } });
+ fireEvent.click(submit);
+ await screen.findByRole("alert");
+ expect(submitted(onAction)).not.toHaveProperty("project_owner");
+ fireEvent.change(name, { target: { value: "Example Owner" } });
+ fireEvent.click(submit);
+ await waitFor(() => expect(onAction).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(submit).toHaveProperty("disabled", false));
+ const patch = submitted(onAction);
+ fireEvent.click(submit);
+ await waitFor(() => expect(onAction).toHaveBeenCalledTimes(3));
+ expect(submitted(onAction)).toEqual(patch);
+ await waitFor(() => expect(submit).toHaveProperty("disabled", false));
+ fireEvent.change(name, { target: { value: "Another Owner" } });
+ fireEvent.click(submit);
+ await waitFor(() => expect(onAction).toHaveBeenCalledTimes(4));
+ expect(submitted(onAction).mutation_id).not.toBe(patch.mutation_id);
+ });
+
it("renders the optional details form as the final step", () => {
const { onBack } = renderDetails();
expect(
@@ -108,7 +211,7 @@ describe("QuestionnaireDetailsStep", () => {
name: "Complete and continue",
});
const hint = screen.getByText(
- "Answer every question to complete and continue.",
+ "Answer the four setup questions to complete and continue.",
);
expect(submit).toHaveProperty("disabled", false);
diff --git a/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx
index 122da8f3c..f8fa37a3b 100644
--- a/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx
+++ b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx
@@ -1,5 +1,6 @@
-import { ReloadIcon } from "@radix-ui/react-icons";
+import { ChevronDownIcon, ReloadIcon } from "@radix-ui/react-icons";
import { useId, useRef, useState } from "react";
+import { z } from "zod";
import { cn } from "@/util/utils";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -10,6 +11,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
@@ -25,6 +27,7 @@ import type {
QuestionnaireReferralSourceV1,
QuestionnaireRoleV1,
QuestionnaireScaleIntentV1,
+ ProjectOwnerFieldsV1,
} from "@/store/onboarding/types";
type Option<Value extends string> = {
@@ -39,6 +42,7 @@ type Selections = {
type Props = {
completionAction: "complete" | "update";
expectedRevision: number;
+ organizationId?: string | null;
initialAnswers?: QuestionnaireAnswersV1 | null;
externalError?: string | null;
isPending: boolean;
@@ -167,6 +171,7 @@ function QuestionnaireSelect<Value extends string>({
function QuestionnaireDetailsStep({
completionAction,
expectedRevision,
+ organizationId,
initialAnswers,
externalError,
isPending,
@@ -185,6 +190,13 @@ function QuestionnaireDetailsStep({
QuestionnairePatchV1["action"] | null
>(null);
const [error, setError] = useState<string | null>(null);
+ const [ownerExpanded, setOwnerExpanded] = useState(false);
+ const [ownerDraft, setOwnerDraft] = useState({
+ name: "",
+ professional_email: "",
+ role: "",
+ });
+ const [ownerError, setOwnerError] = useState<string | null>(null);
const displayedError = externalError ?? error;
const pending = isPending || pendingAction !== null;
const mutationIdentityRef = useRef<{
@@ -209,8 +221,40 @@ function QuestionnaireDetailsStep({
return mutationId;
}
- async function submit(action: QuestionnairePatchV1["action"]) {
+ function discardOwner() {
+ setOwnerDraft({ name: "", professional_email: "", role: "" });
+ setOwnerError(null);
+ }
+
+ async function submit(
+ action: QuestionnairePatchV1["action"],
+ discard = false,
+ ) {
if (pending) return;
+ const owner: ProjectOwnerFieldsV1 = {};
+ if (action === "skip" || discard) {
+ discardOwner();
+ } else {
+ for (const key of ["name", "professional_email", "role"] as const) {
+ const value = ownerDraft[key].trim();
+ if (value) owner[key] = value;
+ }
+ if (
+ owner.professional_email &&
+ !z.string().max(254).email().safeParse(owner.professional_email).success
+ ) {
+ setOwnerError("Enter a valid work email or discard the owner details.");
+ setOwnerExpanded(true);
+ return;
+ }
+ if (Object.keys(owner).length > 0 && !organizationId) {
+ setOwnerError(
+ "We couldn't confirm your organization. Discard the owner details to continue.",
+ );
+ setOwnerExpanded(true);
+ return;
+ }
+ }
try {
const payload =
@@ -221,6 +265,15 @@ function QuestionnaireDetailsStep({
expected_revision: expectedRevision,
action,
...answers,
+ ...(Object.keys(owner).length > 0 && organizationId
+ ? {
+ project_owner: {
+ action: "set" as const,
+ expected_organization_id: organizationId,
+ ...owner,
+ },
+ }
+ : {}),
};
if (!payload) return;
const patch = {
@@ -232,8 +285,13 @@ function QuestionnaireDetailsStep({
setError(null);
await onAction(patch);
mutationIdentityRef.current = null;
- } catch {
- setError("We couldn't save your details. Try again.");
+ } catch (cause) {
+ if (cause instanceof Error && cause.message === "project_owner_invalid") {
+ setOwnerError("Check the owner details or discard them to continue.");
+ setOwnerExpanded(true);
+ } else {
+ setError("We couldn't save your details. Try again.");
+ }
} finally {
setPendingAction(null);
}
@@ -287,6 +345,93 @@ function QuestionnaireDetailsStep({
disabled={pending}
onValueChange={(value) => setSelection("referral_source", value)}
/>
+ {organizationId ? (
+ <div className="ph-no-capture grid gap-3 border-t border-border pt-3">
+ <Button
+ type="button"
+ variant="ghost"
+ className="h-auto min-h-11 justify-start whitespace-normal px-0 text-left"
+ aria-expanded={ownerExpanded}
+ aria-controls={`${fieldPrefix}-owner`}
+ disabled={pending}
+ onClick={() => setOwnerExpanded(!ownerExpanded)}
+ >
+ <ChevronDownIcon
+ aria-hidden
+ className={cn(
+ "mr-2 size-4 shrink-0",
+ ownerExpanded && "rotate-180",
+ )}
+ />
+ Who else owns this automation project? (Optional)
+ </Button>
+ {ownerExpanded ? (
+ <div id={`${fieldPrefix}-owner`} className="grid gap-3">
+ <p className="text-sm text-muted-foreground">
+ Share a project owner or technical sponsor to help us
+ understand your project. This does not send an invitation or
+ message.
+ </p>
+ {(
+ [
+ ["name", "Name", 120],
+ ["professional_email", "Work email", 254],
+ ["role", "Role", 120],
+ ] as const
+ ).map(([key, label, maxLength]) => (
+ <div key={key} className="grid gap-2">
+ <Label htmlFor={`${fieldPrefix}-owner-${key}`}>
+ {label}
+ </Label>
+ <Input
+ id={`${fieldPrefix}-owner-${key}`}
+ type={key === "professional_email" ? "email" : "text"}
+ autoComplete="off"
+ maxLength={maxLength}
+ value={ownerDraft[key]}
+ disabled={pending}
+ className="min-h-11"
+ aria-invalid={
+ (key === "professional_email" && !!ownerError) ||
+ undefined
+ }
+ aria-describedby={
+ ownerError ? `${fieldPrefix}-owner-error` : undefined
+ }
+ onChange={(event) => {
+ const value = event.target.value;
+ setOwnerDraft((current) => ({
+ ...current,
+ [key]: value,
+ }));
+ setOwnerError(null);
+ }}
+ />
+ </div>
+ ))}
+ {ownerError ? (
+ <div className="grid gap-2">
+ <p
+ id={`${fieldPrefix}-owner-error`}
+ role="alert"
+ className="text-sm text-destructive"
+ >
+ {ownerError}
+ </p>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={pending}
+ onClick={() => void submit(completionAction, true)}
+ >
+ Discard owner details and continue
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
{displayedError ? (
<Alert variant="destructive">
<AlertDescription>{displayedError}</AlertDescription>
@@ -294,7 +439,7 @@ function QuestionnaireDetailsStep({
) : null}
{!answers ? (
<p id={incompleteHintId} className="text-sm text-muted-foreground">
- Answer every question to complete and continue.
+ Answer the four setup questions to complete and continue.
</p>
) : null}
</div>
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
index 664ed6015..4027ba241 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
@@ -169,6 +169,8 @@ const editingPasswordCredential: CredentialApiResponse = {
function renderEditPasswordCredentialsModal(
credential = editingPasswordCredential,
additionalTwoFactorMethods?: CredentialAdditionalTwoFactorMethod[],
+ onCredentialCreated?: (id: string, name?: string) => void,
+ defaultTotpType?: "authenticator",
) {
const queryClient = new QueryClient({
defaultOptions: {
@@ -187,7 +189,9 @@ function renderEditPasswordCredentialsModal(
onOpenChange={vi.fn()}
overrideType={CredentialModalTypes.PASSWORD}
editingCredential={credential}
+ defaultTotpType={defaultTotpType}
onStartBackgroundTest={vi.fn()}
+ onCredentialCreated={onCredentialCreated}
/>
</MemoryRouter>
</CredentialAuthenticatorSupportProvider>
@@ -723,6 +727,34 @@ describe("CredentialsModal edit-mode inline test", () => {
}, 15_000);
});
+describe("CredentialsModal edit-mode save callback", () => {
+ it("reports the edited credential to onCredentialCreated", async () => {
+ postMock.mockResolvedValueOnce({
+ data: { credential_id: "real-cred-id", name: "Acme Login" },
+ });
+ patchMock.mockResolvedValue({ data: {} });
+ const onCredentialCreated = vi.fn();
+ renderEditPasswordCredentialsModal(
+ editingPasswordCredential,
+ undefined,
+ onCredentialCreated,
+ );
+
+ fireEvent.click(screen.getAllByLabelText("Edit credential values")[0]!);
+ fireEvent.change(screen.getByDisplayValue("[email protected]"), {
+ target: { value: "[email protected]" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Update" }));
+
+ await waitFor(() =>
+ expect(onCredentialCreated).toHaveBeenCalledWith(
+ "real-cred-id",
+ "Acme Login",
+ ),
+ );
+ }, 10_000);
+});
+
describe("CredentialsModal edit-mode password preservation", () => {
const noPasswordLabel = "This login has no password";
@@ -1427,6 +1459,20 @@ describe("CredentialsModal record-browser defaults", () => {
expect(emailMethod.getAttribute("aria-pressed")).toBe("false");
});
+ it("editing a credential without 2FA opens on the default method", async () => {
+ renderEditPasswordCredentialsModal(
+ editingPasswordCredential,
+ undefined,
+ undefined,
+ "authenticator",
+ );
+ const authenticatorMethod = await screen.findByRole("button", {
+ name: /authenticator app/i,
+ });
+ expect(authenticatorMethod.getAttribute("aria-pressed")).toBe("true");
+ expect(screen.queryAllByDisplayValue("••••••••")).toHaveLength(0);
+ });
+
it("opens 2FA on the email method for a magic-link prompt", async () => {
renderRecordingModal({
defaultTotpType: "email",
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx
index 1c9333e42..6fe2b13f5 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx
@@ -698,9 +698,16 @@ function CredentialsModal({
username: cred.username,
password: "",
totp: "",
- totp_type: cred.totp_type,
+ totp_type:
+ cred.totp_type === "none"
+ ? (defaultTotpType ?? "none")
+ : cred.totp_type,
totp_identifier: cred.totp_identifier ?? "",
});
+ // A preselected method has no saved key to mask, so open the values for entry.
+ if (cred.totp_type === "none" && defaultTotpType) {
+ setEditingGroups((prev) => ({ ...prev, values: true }));
+ }
} else if (isCreditCardCredential(cred)) {
setCreditCardCredentialValues({
...createCreditCardCredentialInitialValues(),
@@ -1177,6 +1184,12 @@ function CredentialsModal({
return;
}
+ if (editingCredential) {
+ onCredentialCreated?.(
+ editingCredential.credential_id,
+ capturedName || editingCredential.name,
+ );
+ }
reset();
setIsOpen(false);
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
index c249a26be..1e6becbe2 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
@@ -1,4 +1,5 @@
import { useEffect, useRef } from "react";
+import { HomeTelemetry } from "@/util/homeTelemetry";
import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
@@ -31,7 +32,14 @@ function getIntentExampleKey(
}
}
-function DiscoverPage() {
+type Props = {
+ /** The redesigned home screen; off renders the legacy discover page. */
+ revamp?: boolean;
+ /** Called when the user creates their first agent from the redesigned home. */
+ onRevampComplete?: () => void;
+};
+
+function DiscoverPage({ revamp = false, onRevampComplete }: Props = {}) {
const enableCopilotHandoff =
useFeatureFlag("ENABLE_DISCOVER_COPILOT_HANDOFF") === true;
const createWorkflowMutation = useCreateWorkflowMutation();
@@ -40,6 +48,10 @@ function DiscoverPage() {
const handledFocus = useRef(false);
const onboarding = useOnboardingStateOptional();
+ useEffect(() => {
+ HomeTelemetry.viewed(revamp ? "revamp" : "legacy");
+ }, [revamp]);
+
const createWorkflow = (
request: Parameters<typeof createWorkflowMutation.mutate>[0],
) => {
@@ -84,6 +96,29 @@ function DiscoverPage() {
setSearchParams,
]);
+ const onboardingModal = onboarding ? (
+ <OnboardingErrorBoundary
+ onError={() => OnboardingTelemetry.modalRenderError("discover")}
+ >
+ <GetStartedModal />
+ </OnboardingErrorBoundary>
+ ) : null;
+
+ if (revamp) {
+ return (
+ <div className="flex min-h-[calc(100vh-9rem)] flex-col justify-center">
+ <h1 className="sr-only">Create an agent</h1>
+ <PromptBox
+ ref={promptBoxRef}
+ enableCopilotHandoff={enableCopilotHandoff}
+ minimal
+ onAgentCreated={onRevampComplete}
+ />
+ {onboardingModal}
+ </div>
+ );
+ }
+
return (
<div className="space-y-10">
<h1 className="sr-only">Create an agent</h1>
@@ -98,12 +133,13 @@ function DiscoverPage() {
size="sm"
className="h-11 touch-manipulation text-muted-foreground hover:text-foreground"
disabled={createWorkflowMutation.isPending}
- onClick={() =>
+ onClick={() => {
+ HomeTelemetry.skipToBlankCanvasClicked();
createWorkflow({
...defaultWorkflowRequest,
_via: "blank",
- })
- }
+ });
+ }}
>
{createWorkflowMutation.isPending && (
<ReloadIcon
@@ -116,13 +152,7 @@ function DiscoverPage() {
</div>
</div>
<WorkflowTemplates />
- {onboarding ? (
- <OnboardingErrorBoundary
- onError={() => OnboardingTelemetry.modalRenderError("discover")}
- >
- <GetStartedModal />
- </OnboardingErrorBoundary>
- ) : null}
+ {onboardingModal}
</div>
);
}
diff --git a/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx b/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
index 7561aa509..9b7927637 100644
--- a/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
+++ b/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
@@ -4,6 +4,7 @@ import { workflowEditorPath } from "@/routes/workflows/studioNavigation";
import { useGlobalWorkflowsQuery } from "../workflows/hooks/useGlobalWorkflowsQuery";
import { useNavigate } from "react-router-dom";
import { WorkflowTemplateCard } from "./WorkflowTemplateCard";
+import { HomeTelemetry } from "@/util/homeTelemetry";
import testImg from "@/assets/promptBoxBg.png";
import { TEMPORARY_TEMPLATE_IMAGES } from "./TemporaryTemplateImages";
import {
@@ -56,6 +57,10 @@ function WorkflowTemplates() {
testImg
}
onClick={() => {
+ HomeTelemetry.templateClicked({
+ workflowPermanentId: workflow.workflow_permanent_id,
+ title: workflow.title,
+ });
navigate(
workflowEditorPath(
workflow.workflow_permanent_id,
diff --git a/skyvern-frontend/src/routes/tasks/create/CapabilityExamples.tsx b/skyvern-frontend/src/routes/tasks/create/CapabilityExamples.tsx
new file mode 100644
index 000000000..5a0a0aba0
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/create/CapabilityExamples.tsx
@@ -0,0 +1,343 @@
+import {
+ CalendarIcon,
+ ClockIcon,
+ CodeIcon,
+ DownloadIcon,
+ EnvelopeClosedIcon,
+ FileTextIcon,
+ LockClosedIcon,
+ TableIcon,
+} from "@radix-ui/react-icons";
+import type { ReactNode } from "react";
+
+import { GraphIcon } from "@/components/icons/GraphIcon";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+
+import "./capabilityExamples.css";
+
+type Capability = "forms" | "extract" | "login" | "monitor" | "schedule";
+
+type Example = { label: string; prompt: string; icon: ReactNode };
+
+type Group = {
+ capability: Capability;
+ label: string;
+ caption: string;
+ preview: ReactNode;
+ examples: [Example, Example];
+};
+
+const TruckIcon = (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
+ <path d="M3 7h11v9H3zM14 10h4l3 3v3h-7z" />
+ <circle cx="7" cy="18" r="1.6" />
+ <circle cx="17" cy="18" r="1.6" />
+ </svg>
+);
+
+function Frame({ kind, children }: { kind: string; children: ReactNode }) {
+ return (
+ <div className={`cx-frame ${kind}`} aria-hidden="true">
+ <div className="cx-bar">
+ <span className="cx-dot" />
+ <span className="cx-dot" />
+ <span className="cx-dot" />
+ <span className="cx-url" />
+ </div>
+ <div className="cx-body">{children}</div>
+ </div>
+ );
+}
+
+const GROUPS: ReadonlyArray<Group> = [
+ {
+ capability: "forms",
+ label: "Fill forms",
+ caption: "Skyvern types into each field, then submits the form.",
+ preview: (
+ <Frame kind="cx-form">
+ {[0, 1, 2].map((i) => (
+ <div key={i} className="cx-row">
+ <span className="cx-lab" />
+ <span className="cx-field">
+ <span className="cx-ink" />
+ </span>
+ </div>
+ ))}
+ <div className="cx-row" style={{ margin: 0 }}>
+ <span className="cx-btn">Submit</span>
+ </div>
+ </Frame>
+ ),
+ examples: [
+ {
+ label: "Apply for a job",
+ icon: <EnvelopeClosedIcon />,
+ prompt:
+ "Go to https://jobs.lever.co/leverdemo-8, find the first Solutions Engineer role in Toronto, and apply with the attached resume. Fill in the name and email, submit, and confirm the application went through.",
+ },
+ {
+ label: "Get a quote",
+ icon: <FileTextIcon />,
+ prompt:
+ "Go to https://www.geico.com and generate an auto insurance quote for a 2015 Audi A8 L in Houston, TX. Stop once a premium amount is shown and extract the quote details as JSON.",
+ },
+ ],
+ },
+ {
+ capability: "extract",
+ label: "Extract data",
+ caption: "Skyvern reads the rows on the page and returns structured JSON.",
+ preview: (
+ <Frame kind="cx-table">
+ <div className="cx-split">
+ <div className="cx-rows">
+ <span className="cx-trow" />
+ <span className="cx-trow" />
+ <span className="cx-trow" />
+ <span className="cx-trow" />
+ </div>
+ <div className="cx-json">
+ {"[{\n "}
+ <b>&quot;sku&quot;</b>
+ {':"AX-14",\n '}
+ <b>&quot;price&quot;</b>
+ {":129,\n "}
+ <b>&quot;stock&quot;</b>
+ {":8\n}]"}
+ </div>
+ </div>
+ </Frame>
+ ),
+ examples: [
+ {
+ label: "Scrape a catalog",
+ icon: <TableIcon />,
+ prompt:
+ "Go to the vendor's product listing, page through every result, and collect the SKU, name, price, and stock level for each item.",
+ },
+ {
+ label: "Extract to JSON",
+ icon: <CodeIcon />,
+ prompt:
+ "Open the order confirmation page, extract the order number, line items, and total, and return it as JSON.",
+ },
+ ],
+ },
+ {
+ capability: "login",
+ label: "Log in and download",
+ caption: "Skyvern signs in, reads the 2FA code, and saves the file.",
+ preview: (
+ <Frame kind="cx-login">
+ <div className="cx-row">
+ <span className="cx-lab" />
+ <span className="cx-field">
+ <span className="cx-ink" style={{ width: "64%" }} />
+ </span>
+ </div>
+ <div className="cx-row">
+ <span className="cx-lab" />
+ <span className="cx-field">
+ <span className="cx-dots">
+ <i />
+ <i />
+ <i />
+ <i />
+ <i />
+ <i />
+ </span>
+ </span>
+ </div>
+ <span className="cx-otp">
+ <LockClosedIcon />
+ 482 193
+ </span>
+ <div>
+ <span className="cx-file">
+ <DownloadIcon />
+ invoices-may.pdf
+ </span>
+ </div>
+ </Frame>
+ ),
+ examples: [
+ {
+ label: "Download invoices",
+ icon: <DownloadIcon />,
+ prompt:
+ "Log in to the supplier portal with the saved credentials and download every invoice from last month as PDF.",
+ },
+ {
+ label: "Export a report",
+ icon: <LockClosedIcon />,
+ prompt:
+ "Log in to the payroll system, run the month-end report, and download it as CSV.",
+ },
+ ],
+ },
+ {
+ capability: "monitor",
+ label: "Monitor",
+ caption: "Skyvern re-checks the page and alerts you when the value moves.",
+ preview: (
+ <Frame kind="cx-watch">
+ <div className="cx-price">
+ <span className="cx-p-old">$1,299</span>
+ <span className="cx-p-new">$1,149</span>
+ </div>
+ <div className="cx-meta">Pro plan, checked every morning</div>
+ <svg className="cx-spark" viewBox="0 0 150 34" width="150" height="34">
+ <path
+ className="cx-line"
+ d="M2 10 L26 8 L50 13 L74 9 L98 12 L122 24 L146 26"
+ />
+ <circle className="cx-tip" cx="146" cy="26" r="2.6" />
+ </svg>
+ <span className="cx-bell">
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.8"
+ >
+ <path d="M6 16V11a6 6 0 1 1 12 0v5l2 3H4zM10 22h4" />
+ </svg>
+ </span>
+ </Frame>
+ ),
+ examples: [
+ {
+ label: "Watch a price",
+ icon: <GraphIcon className="size-[22px]" />,
+ prompt:
+ "Check the competitor's pricing page every morning and message me when the Pro plan price changes.",
+ },
+ {
+ label: "Track a shipment",
+ icon: TruckIcon,
+ prompt:
+ "Log in to the carrier site, look up tracking number 1Z999AA10123456784, and report the current status and delivery date.",
+ },
+ ],
+ },
+ {
+ capability: "schedule",
+ label: "Run on a schedule",
+ caption: "Once it works, schedule it to run again from the agent page.",
+ preview: (
+ <Frame kind="cx-cal">
+ <div className="cx-grid">
+ <span className="cx-ring" />
+ {Array.from({ length: 21 }, (_, i) => (
+ <i key={i} />
+ ))}
+ </div>
+ <span className="cx-when">Every Tuesday, 08:00</span>
+ <svg className="cx-clock" viewBox="0 0 34 34">
+ <circle cx="17" cy="17" r="12" />
+ <path className="cx-hand" d="M17 17V8" />
+ </svg>
+ </Frame>
+ ),
+ examples: [
+ {
+ label: "Weekly summary",
+ icon: <CalendarIcon />,
+ prompt:
+ "Log in to the analytics dashboard, download last week's report, and email it to the team.",
+ },
+ {
+ label: "Daily sync",
+ icon: <ClockIcon />,
+ prompt:
+ "Pull today's inventory counts from the warehouse portal and append them to the tracking sheet.",
+ },
+ ],
+ },
+];
+
+// Three groups on top, two centered beneath, at every width.
+const GROUP_ROWS = [GROUPS.slice(0, 3), GROUPS.slice(3)];
+
+type Selection = { capability: Capability; label: string; prompt: string };
+
+type Props = {
+ disabled?: boolean;
+ onSelect: (selection: Selection) => void;
+ onPreview?: (selection: Omit<Selection, "prompt">) => void;
+};
+
+function CapabilityExamples({ disabled = false, onSelect, onPreview }: Props) {
+ return (
+ <TooltipProvider delayDuration={120}>
+ <div className="flex w-full flex-col items-center gap-5">
+ {GROUP_ROWS.map((row, rowIndex) => (
+ <div
+ key={rowIndex}
+ className="flex flex-wrap items-start justify-center gap-x-[18px] gap-y-5"
+ >
+ {row.map((group) => (
+ <div
+ key={group.capability}
+ className="flex w-[196px] flex-col gap-2"
+ >
+ <div className="pl-0.5 text-[10.5px] font-semibold uppercase tracking-[0.1em] text-muted-foreground">
+ {group.label}
+ </div>
+ {group.examples.map((example) => (
+ <Tooltip
+ key={example.label}
+ onOpenChange={(open) => {
+ if (open) {
+ onPreview?.({
+ capability: group.capability,
+ label: example.label,
+ });
+ }
+ }}
+ >
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() =>
+ onSelect({
+ capability: group.capability,
+ label: example.label,
+ prompt: example.prompt,
+ })
+ }
+ className="flex h-12 w-full items-center gap-2.5 rounded-[10px] border border-transparent bg-slate-elevation2 pl-4 pr-5 text-left text-sm text-foreground transition-colors hover:border-border hover:bg-slate-elevation3 disabled:pointer-events-none disabled:opacity-50 [&>svg]:size-[22px] [&>svg]:shrink-0"
+ >
+ {example.icon}
+ <span className="truncate">{example.label}</span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ sideOffset={12}
+ className="w-[260px] whitespace-normal rounded-xl border border-border bg-slate-elevation1 p-2.5 text-foreground shadow-2xl"
+ >
+ {group.preview}
+ <p className="mx-0.5 mt-2 text-[11.5px] leading-snug text-muted-foreground">
+ {group.caption}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ </TooltipProvider>
+ );
+}
+
+export { CapabilityExamples };
diff --git a/skyvern-frontend/src/routes/tasks/create/CyclingPlaceholderTextarea.tsx b/skyvern-frontend/src/routes/tasks/create/CyclingPlaceholderTextarea.tsx
new file mode 100644
index 000000000..82484a5f4
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/create/CyclingPlaceholderTextarea.tsx
@@ -0,0 +1,24 @@
+import { type ComponentProps, forwardRef } from "react";
+
+import { AutoResizingTextarea } from "@/components/AutoResizingTextarea/AutoResizingTextarea";
+
+import { useCyclingPlaceholder } from "./useCyclingPlaceholder";
+
+type Props = Omit<
+ ComponentProps<typeof AutoResizingTextarea>,
+ "placeholder"
+> & {
+ cycling: boolean;
+};
+
+// Leaf so the placeholder's typing tick re-renders only this textarea.
+const CyclingPlaceholderTextarea = forwardRef<HTMLTextAreaElement, Props>(
+ function CyclingPlaceholderTextarea({ cycling, ...props }, ref) {
+ const placeholder = useCyclingPlaceholder(cycling);
+ return (
+ <AutoResizingTextarea ref={ref} placeholder={placeholder} {...props} />
+ );
+ },
+);
+
+export { CyclingPlaceholderTextarea };
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
index 17c70beee..2bc4bd0f4 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
@@ -129,6 +129,21 @@ vi.mock("./ExampleCasePill", () => ({
}));
vi.mock("@radix-ui/react-icons", () => ({
+ CalendarIcon: () => null,
+ CheckIcon: () => null,
+ ClockIcon: () => null,
+ CodeIcon: () => null,
+ DownloadIcon: () => null,
+ EnvelopeClosedIcon: () => null,
+ GlobeIcon: () => null,
+ LockClosedIcon: () => null,
+ TableIcon: () => null,
+ TextAlignLeftIcon: () => null,
+ ChevronDownIcon: () => null,
+ ChevronUpIcon: () => null,
+ PlusIcon: () => null,
+ UploadIcon: () => null,
+ VideoIcon: () => null,
FileTextIcon: () => null,
GearIcon: () => null,
Pencil1Icon: () => null,
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
index ef9ba0265..5658cc09f 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.tsx
@@ -21,12 +21,26 @@ import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
import { CodeEditor } from "@/routes/workflows/components/CodeEditor";
import {
+ CheckIcon,
+ ChevronDownIcon,
+ Cross2Icon,
FileTextIcon,
+ GlobeIcon,
GearIcon,
PaperPlaneIcon,
Pencil1Icon,
+ PlusIcon,
ReloadIcon,
+ TextAlignLeftIcon,
+ UploadIcon,
+ VideoIcon,
} from "@radix-ui/react-icons";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError, type AxiosResponse } from "axios";
import {
@@ -41,7 +55,11 @@ import {
generatePhoneNumber,
generateUniqueEmail,
} from "../data/sampleTaskData";
+import { CapabilityExamples } from "./CapabilityExamples";
import { ExampleCasePill } from "./ExampleCasePill";
+import { CyclingPlaceholderTextarea } from "./CyclingPlaceholderTextarea";
+import type { CopilotAttachedFile } from "@/routes/workflows/copilot/workflowCopilotTypes";
+import { HomeTelemetry } from "@/util/homeTelemetry";
import {
MAX_SCREENSHOT_SCROLLS_DEFAULT,
MAX_STEPS_DEFAULT,
@@ -120,8 +138,34 @@ const exampleCases = [
type ExamplePromptKey = (typeof exampleCases)[number]["key"];
+const UPLOAD_RETENTION_DAYS = 30;
+// Mirrors MAX_ATTACHED_FILES_PER_MESSAGE on the copilot chat request.
+const MAX_HOME_ATTACHMENTS = 20;
+
+const HOW_IT_WORKS = [
+ {
+ title: "Describe",
+ body: "Write the task in plain language, with the site and the outcome you want.",
+ icon: <TextAlignLeftIcon className="size-[15px]" />,
+ },
+ {
+ title: "Skyvern drives a browser",
+ body: "It opens a real browser, navigates, types, clicks, and handles logins and 2FA.",
+ icon: <GlobeIcon className="size-[15px]" />,
+ },
+ {
+ title: "You get the result or data",
+ body: "A confirmation, a downloaded file, or structured JSON you can send anywhere.",
+ icon: <CheckIcon className="size-[15px]" />,
+ },
+];
+
type PromptBoxProps = {
enableCopilotHandoff?: boolean;
+ /** Home-screen variant: no prompt improver and no advanced settings. */
+ minimal?: boolean;
+ /** Fires once an agent has been created from this prompt box. */
+ onAgentCreated?: () => void;
};
type PromptBoxHandle = {
@@ -202,7 +246,11 @@ function showCreateErrorToast(title: string, error: unknown) {
}
function PromptBoxImpl(
- { enableCopilotHandoff = false }: PromptBoxProps,
+ {
+ enableCopilotHandoff = false,
+ minimal = false,
+ onAgentCreated,
+ }: PromptBoxProps,
ref: ForwardedRef<PromptBoxHandle>,
) {
const navigate = useNavigate();
@@ -227,6 +275,10 @@ function PromptBoxImpl(
string | null
>(null);
const [showAdvancedSettings, setShowAdvancedSettings] = useState(false);
+ const [showHowItWorks, setShowHowItWorks] = useState(false);
+ const [promptTouched, setPromptTouched] = useState(false);
+ const [attachedFiles, setAttachedFiles] = useState<CopilotAttachedFile[]>([]);
+ const fileInputRef = useRef<HTMLInputElement>(null);
const [dataSchema, setDataSchema] = useState<string | null>(null);
const [extraHttpHeaders, setExtraHttpHeaders] = useState<string | null>(null);
const { setAutoplay } = useAutoplayStore();
@@ -246,6 +298,72 @@ function PromptBoxImpl(
},
}));
+ const uploadDocumentMutation = useMutation({
+ mutationFn: async (file: File) => {
+ const client = await getClient(credentialGetter);
+ const formData = new FormData();
+ formData.append("file", file);
+ // Bounded so an abandoned upload does not linger until the org retention policy.
+ formData.append("retention_days", String(UPLOAD_RETENTION_DAYS));
+ const result = await client.post<FormData, { data: { file_id: string } }>(
+ "/upload_file",
+ formData,
+ { headers: { "Content-Type": "multipart/form-data" } },
+ );
+ return {
+ file_id: result.data.file_id,
+ filename: file.name,
+ size_bytes: file.size,
+ available: true,
+ } satisfies CopilotAttachedFile;
+ },
+ onSuccess: (attached) => {
+ HomeTelemetry.uploadDocumentFinished(true);
+ setAttachedFiles((current) =>
+ current.length >= MAX_HOME_ATTACHMENTS
+ ? current
+ : [...current, attached],
+ );
+ textareaRef.current?.focus();
+ },
+ onError: (error: AxiosError) => {
+ HomeTelemetry.uploadDocumentFinished(false);
+ showCreateErrorToast("Failed to upload file", error);
+ },
+ });
+
+ const recordTaskMutation = useMutation({
+ mutationFn: async () => {
+ const client = await getClient(credentialGetter);
+ const yaml = convertToYAML(buildBlankWorkflowRequest("Recorded Agent"));
+ const result = await client.post<string, AxiosResponse<unknown>>(
+ "/workflows",
+ yaml,
+ { headers: { "Content-Type": "text/plain" } },
+ );
+ if (!hasWorkflowShape(result.data)) {
+ throw new Error(
+ `workflow create returned an unexpected response shape (${describeResponseEnvelope(result)})`,
+ );
+ }
+ return result.data;
+ },
+ onSuccess: (workflow) => {
+ onAgentCreated?.();
+ queryClient.invalidateQueries({ queryKey: ["workflows"] });
+ navigate(
+ workflowEditorPath(
+ workflow.workflow_permanent_id,
+ studioEnabled,
+ "?record=1",
+ ),
+ );
+ },
+ onError: (error: AxiosError) => {
+ showCreateErrorToast("Could not start recording", error);
+ },
+ });
+
const generateWorkflowMutation = useMutation({
mutationFn: async ({ prompt }: { prompt: string }) => {
const client = await getClient(credentialGetter, "sans-api-v1");
@@ -305,6 +423,7 @@ function PromptBoxImpl(
return result.data;
},
onSuccess: (workflow) => {
+ onAgentCreated?.();
toast({
variant: "success",
title: "Agent Created",
@@ -347,7 +466,7 @@ function PromptBoxImpl(
const yaml = convertToYAML(
buildBlankWorkflowRequest(deriveHandoffTitle(prompt), runWith),
);
- const result = await client.post<string, { data: WorkflowApiResponse }>(
+ const result = await client.post<string, AxiosResponse<unknown>>(
"/workflows",
yaml,
{
@@ -356,9 +475,15 @@ function PromptBoxImpl(
},
},
);
+ if (!hasWorkflowShape(result.data)) {
+ throw new Error(
+ `workflow create returned an unexpected response shape (${describeResponseEnvelope(result)})`,
+ );
+ }
return { data: result.data, prompt };
},
onSuccess: ({ data: workflow, prompt }) => {
+ onAgentCreated?.();
queryClient.invalidateQueries({ queryKey: ["workflows"] });
queryClient.invalidateQueries({ queryKey: ["folders"] });
// Only the studio handoff writes the recovery key. The legacy /build path
@@ -375,7 +500,11 @@ function PromptBoxImpl(
"?via=discover",
),
{
- state: { copilotMessage: prompt },
+ state: {
+ copilotMessage: prompt,
+ copilotAttachedFiles:
+ attachedFiles.length > 0 ? attachedFiles : undefined,
+ },
},
);
},
@@ -388,7 +517,10 @@ function PromptBoxImpl(
});
const isSubmitting =
- generateWorkflowMutation.isPending || handoffWorkflowMutation.isPending;
+ generateWorkflowMutation.isPending ||
+ handoffWorkflowMutation.isPending ||
+ uploadDocumentMutation.isPending ||
+ recordTaskMutation.isPending;
const {
isSupported: isSpeechSupported,
@@ -401,11 +533,23 @@ function PromptBoxImpl(
enabled: !promptImprovalIsPending && !isSubmitting,
});
- const submitPrompt = ({ prompt }: { prompt: string }) => {
+ const submitPrompt = ({
+ prompt,
+ example,
+ }: {
+ prompt: string;
+ example?: string;
+ }) => {
if (submitInFlightRef.current || isSubmitting) {
return;
}
submitInFlightRef.current = true;
+ HomeTelemetry.promptSubmitted({
+ source: example ? "example" : "typed",
+ example,
+ promptLength: prompt.length,
+ handoff: enableCopilotHandoff,
+ });
if (enableCopilotHandoff) {
handoffWorkflowMutation.mutate({ prompt, runWith: "agent" });
return;
@@ -413,306 +557,535 @@ function PromptBoxImpl(
generateWorkflowMutation.mutate({ prompt });
};
- return (
- <div>
- <div
- className="rounded-sm py-[4.25rem]"
- style={{
- background: `url(${img}) 50% / cover no-repeat`,
- }}
- >
- <div className="mx-auto flex min-w-44 flex-col items-center gap-7 px-8">
- <span className="text-2xl">
- What task would you like to accomplish?
- </span>
- <div className="flex w-full max-w-xl flex-col">
- <div
- className={cn(
- "flex w-full items-center gap-2 rounded-xl border border-input bg-background py-2 pr-3 text-muted-foreground shadow-sm transition-colors focus-within:border-foreground/20 focus-within:ring-2 focus-within:ring-ring/10",
- {
- "pointer-events-none opacity-50": promptImprovalIsPending,
- },
- )}
- >
- <SpeechInputButton
- isSupported={isSpeechSupported}
- isListening={isSpeechListening}
- isHearingSpeech={isSpeechHearing}
- disabled={promptImprovalIsPending || isSubmitting}
- onToggle={toggleSpeech}
- className="ml-2 h-9 w-9 border-0 bg-transparent shadow-none hover:bg-muted"
- iconClassName="h-5 w-5"
- />
- <AutoResizingTextarea
- ref={textareaRef}
- id="discover-prompt-input"
- className="min-h-0 resize-none border-0 bg-transparent px-4 py-0 leading-5 text-foreground shadow-none placeholder:text-muted-foreground hover:border-0 focus-visible:ring-0"
- value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
- placeholder="Enter your prompt..."
- />
- <ImprovePrompt
- isVisible={Boolean(prompt.trim())}
- onBegin={() => {
- setPromptImprovalIsPending(true);
- }}
- onEnd={() => {
- setPromptImprovalIsPending(false);
- }}
- onImprove={(prompt) => setPrompt(prompt)}
- prompt={prompt}
- size="large"
- useCase="new_workflow"
- />
- {!enableCopilotHandoff ? (
+ if (!minimal) {
+ return (
+ <div>
+ <div
+ className="rounded-sm py-[4.25rem]"
+ style={{
+ background: `url(${img}) 50% / cover no-repeat`,
+ }}
+ >
+ <div className="mx-auto flex min-w-44 flex-col items-center gap-7 px-8">
+ <span className="text-2xl">
+ What task would you like to accomplish?
+ </span>
+ <div className="flex w-full max-w-xl flex-col">
+ <div
+ className={cn(
+ "flex w-full items-center gap-2 rounded-xl border border-input bg-background py-2 pr-3 text-muted-foreground shadow-sm transition-colors focus-within:border-foreground/20 focus-within:ring-2 focus-within:ring-ring/10",
+ {
+ "pointer-events-none opacity-50": promptImprovalIsPending,
+ },
+ )}
+ >
+ <SpeechInputButton
+ isSupported={isSpeechSupported}
+ isListening={isSpeechListening}
+ isHearingSpeech={isSpeechHearing}
+ disabled={promptImprovalIsPending || isSubmitting}
+ onToggle={() => {
+ HomeTelemetry.voiceToggled();
+ toggleSpeech();
+ }}
+ className="ml-2 h-9 w-9 border-0 bg-transparent shadow-none hover:bg-muted"
+ iconClassName="h-5 w-5"
+ />
+ <AutoResizingTextarea
+ ref={textareaRef}
+ id="discover-prompt-input"
+ className="min-h-0 resize-none border-0 bg-transparent px-4 py-0 leading-5 text-foreground shadow-none placeholder:text-muted-foreground hover:border-0 focus-visible:ring-0"
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder="Enter your prompt..."
+ />
+ <ImprovePrompt
+ isVisible={Boolean(prompt.trim())}
+ onBegin={() => {
+ HomeTelemetry.improvePromptUsed();
+ setPromptImprovalIsPending(true);
+ }}
+ onEnd={() => {
+ setPromptImprovalIsPending(false);
+ }}
+ onImprove={(prompt) => setPrompt(prompt)}
+ prompt={prompt}
+ size="large"
+ useCase="new_workflow"
+ />
+ {!enableCopilotHandoff ? (
+ <button
+ type="button"
+ aria-label="Advanced settings"
+ className="flex items-center justify-center rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ onClick={() => {
+ setShowAdvancedSettings((value) => {
+ HomeTelemetry.advancedSettingsToggled(!value);
+ return !value;
+ });
+ }}
+ >
+ <GearIcon aria-hidden="true" className="size-5 shrink-0" />
+ </button>
+ ) : null}
<button
type="button"
- aria-label="Advanced settings"
- className="flex items-center justify-center rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ aria-label="submit-prompt"
+ disabled={!prompt.trim() || isSubmitting}
+ className="flex items-center justify-center rounded-lg bg-cta p-2 text-cta-foreground shadow-sm transition-colors hover:bg-cta-hover disabled:pointer-events-none disabled:bg-cta/45 disabled:text-cta-foreground/65 disabled:shadow-none"
onClick={() => {
- setShowAdvancedSettings((value) => !value);
+ submitPrompt({ prompt });
}}
>
- <GearIcon aria-hidden="true" className="size-5 shrink-0" />
+ {isSubmitting ? (
+ <ReloadIcon className="size-4 animate-spin" />
+ ) : (
+ <PaperPlaneIcon
+ aria-hidden="true"
+ className="size-4 shrink-0"
+ />
+ )}
</button>
- ) : null}
- <button
- type="button"
- aria-label="submit-prompt"
- disabled={!prompt.trim() || isSubmitting}
- className="flex items-center justify-center rounded-lg bg-cta p-2 text-cta-foreground shadow-sm transition-colors hover:bg-cta-hover disabled:pointer-events-none disabled:bg-cta/45 disabled:text-cta-foreground/65 disabled:shadow-none"
- onClick={() => {
- submitPrompt({ prompt });
- }}
- >
- {isSubmitting ? (
- <ReloadIcon className="size-4 animate-spin" />
- ) : (
- <PaperPlaneIcon
- aria-hidden="true"
- className="size-4 shrink-0"
- />
- )}
- </button>
- </div>
- {showAdvancedSettings ? (
- <div className="rounded-b-lg px-2">
- <div className="space-y-4 rounded-b-xl border border-t-0 border-input bg-background p-4 text-foreground shadow-sm">
- <header>Advanced Settings</header>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Webhook Callback URL</div>
- <div className="text-xs text-muted-foreground">
- The URL of a webhook endpoint to send the extracted
- information
+ </div>
+ {showAdvancedSettings ? (
+ <div className="rounded-b-lg px-2">
+ <div className="space-y-4 rounded-b-xl border border-t-0 border-input bg-background p-4 text-foreground shadow-sm">
+ <header>Advanced Settings</header>
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Webhook Callback URL</div>
+ <div className="text-xs text-muted-foreground">
+ The URL of a webhook endpoint to send the extracted
+ information
+ </div>
+ </div>
+ <div className="flex flex-col gap-2">
+ <Input
+ className="w-full"
+ value={webhookCallbackUrl ?? ""}
+ onChange={(event) => {
+ setWebhookCallbackUrl(event.target.value);
+ }}
+ />
+ <TestWebhookDialog
+ runType="task"
+ runId={null}
+ initialWebhookUrl={webhookCallbackUrl ?? undefined}
+ trigger={
+ <Button
+ type="button"
+ variant="secondary"
+ className="self-start"
+ disabled={!webhookCallbackUrl}
+ >
+ Test Webhook
+ </Button>
+ }
+ />
+ </div>
+ </div>
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Proxy Location</div>
+ <div className="text-xs text-muted-foreground">
+ Route Skyvern through one of our available proxies.
+ </div>
</div>
+ <ProxySelector
+ value={proxyLocation}
+ onChange={setProxyLocation}
+ />
</div>
- <div className="flex flex-col gap-2">
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Browser Session ID</div>
+ <div className="text-xs text-muted-foreground">
+ The ID of a persistent browser session
+ </div>
+ </div>
<Input
- className="w-full"
- value={webhookCallbackUrl ?? ""}
+ value={browserSessionId ?? ""}
+ placeholder="pbs_xxx"
onChange={(event) => {
- setWebhookCallbackUrl(event.target.value);
+ setBrowserSessionId(event.target.value);
}}
/>
- <TestWebhookDialog
- runType="task"
- runId={null}
- initialWebhookUrl={webhookCallbackUrl ?? undefined}
- trigger={
- <Button
- type="button"
- variant="secondary"
- className="self-start"
- disabled={!webhookCallbackUrl}
- >
- Test Webhook
- </Button>
- }
- />
</div>
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Proxy Location</div>
- <div className="text-xs text-muted-foreground">
- Route Skyvern through one of our available proxies.
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Browser Address</div>
+ <div className="text-xs text-muted-foreground">
+ The address of the Browser server to use for the task
+ run.
+ </div>
</div>
+ <Input
+ value={cdpAddress ?? ""}
+ placeholder="http://127.0.0.1:9222"
+ onChange={(event) => {
+ setCdpAddress(event.target.value);
+ }}
+ />
</div>
- <ProxySelector
- value={proxyLocation}
- onChange={setProxyLocation}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Browser Session ID</div>
- <div className="text-xs text-muted-foreground">
- The ID of a persistent browser session
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">2FA Identifier</div>
+ <div className="text-xs text-muted-foreground">
+ The identifier for a 2FA code for this task.
+ </div>
</div>
+ <Input
+ value={totpIdentifier}
+ onChange={(event) => {
+ setTotpIdentifier(event.target.value);
+ }}
+ />
</div>
- <Input
- value={browserSessionId ?? ""}
- placeholder="pbs_xxx"
- onChange={(event) => {
- setBrowserSessionId(event.target.value);
- }}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Browser Address</div>
- <div className="text-xs text-muted-foreground">
- The address of the Browser server to use for the task
- run.
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Extra HTTP Headers</div>
+ <div className="text-xs text-muted-foreground">
+ Specify some self defined HTTP requests headers in
+ Dict format
+ </div>
</div>
- </div>
- <Input
- value={cdpAddress ?? ""}
- placeholder="http://127.0.0.1:9222"
- onChange={(event) => {
- setCdpAddress(event.target.value);
- }}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">2FA Identifier</div>
- <div className="text-xs text-muted-foreground">
- The identifier for a 2FA code for this task.
+ <div className="flex-1">
+ <KeyValueInput
+ value={extraHttpHeaders ?? ""}
+ onChange={(val) =>
+ setExtraHttpHeaders(
+ val === null
+ ? null
+ : typeof val === "string"
+ ? val || null
+ : JSON.stringify(val),
+ )
+ }
+ addButtonText="Add Header"
+ />
</div>
</div>
- <Input
- value={totpIdentifier}
- onChange={(event) => {
- setTotpIdentifier(event.target.value);
- }}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Extra HTTP Headers</div>
- <div className="text-xs text-muted-foreground">
- Specify some self defined HTTP requests headers in Dict
- format
+
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Generate Script</div>
+ <div className="text-xs text-muted-foreground">
+ Whether to generate scripts for this task run (on
+ success).
+ </div>
</div>
- </div>
- <div className="flex-1">
- <KeyValueInput
- value={extraHttpHeaders ?? ""}
- onChange={(val) =>
- setExtraHttpHeaders(
- val === null
- ? null
- : typeof val === "string"
- ? val || null
- : JSON.stringify(val),
- )
- }
- addButtonText="Add Header"
+ <Switch
+ checked={generateScript}
+ onCheckedChange={(checked) => {
+ setGenerateScript(Boolean(checked));
+ }}
/>
</div>
- </div>
-
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Generate Script</div>
- <div className="text-xs text-muted-foreground">
- Whether to generate scripts for this task run (on
- success).
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Publish Agent</div>
+ <div className="text-xs text-muted-foreground">
+ Whether to create an agent alongside this task run.
+ Will also be created if "Generate Scripts" is true.
+ </div>
</div>
+ <Switch
+ checked={publishWorkflow}
+ onCheckedChange={(checked) => {
+ setPublishWorkflow(Boolean(checked));
+ }}
+ />
</div>
- <Switch
- checked={generateScript}
- onCheckedChange={(checked) => {
- setGenerateScript(Boolean(checked));
- }}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Publish Agent</div>
- <div className="text-xs text-muted-foreground">
- Whether to create an agent alongside this task run. Will
- also be created if "Generate Scripts" is true.
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Max Steps Override</div>
+ <div className="text-xs text-muted-foreground">
+ The maximum number of steps to take for this task.
+ </div>
</div>
+ <Input
+ value={maxStepsOverride ?? ""}
+ placeholder={`Default: ${MAX_STEPS_DEFAULT}`}
+ onChange={(event) => {
+ setMaxStepsOverride(event.target.value);
+ }}
+ />
</div>
- <Switch
- checked={publishWorkflow}
- onCheckedChange={(checked) => {
- setPublishWorkflow(Boolean(checked));
- }}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Max Steps Override</div>
- <div className="text-xs text-muted-foreground">
- The maximum number of steps to take for this task.
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Data Schema</div>
+ <div className="text-xs text-muted-foreground">
+ Specify the output data schema in JSON format
+ </div>
</div>
- </div>
- <Input
- value={maxStepsOverride ?? ""}
- placeholder={`Default: ${MAX_STEPS_DEFAULT}`}
- onChange={(event) => {
- setMaxStepsOverride(event.target.value);
- }}
- />
- </div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Data Schema</div>
- <div className="text-xs text-muted-foreground">
- Specify the output data schema in JSON format
+ <div className="flex-1">
+ <CodeEditor
+ value={dataSchema ?? ""}
+ onChange={(value) => setDataSchema(value || null)}
+ language="json"
+ minHeight="100px"
+ maxHeight="500px"
+ fontSize={8}
+ />
</div>
</div>
- <div className="flex-1">
- <CodeEditor
- value={dataSchema ?? ""}
- onChange={(value) => setDataSchema(value || null)}
- language="json"
- minHeight="100px"
- maxHeight="500px"
- fontSize={8}
+ <div className="flex gap-16">
+ <div className="w-48 shrink-0">
+ <div className="text-sm">Max Screenshot Scrolls</div>
+ <div className="text-xs text-muted-foreground">
+ {`The maximum number of scrolls for the post action screenshot. Default is ${MAX_SCREENSHOT_SCROLLS_DEFAULT}. If it's set to 0, it will take the current viewport screenshot.`}
+ </div>
+ </div>
+ <Input
+ value={maxScreenshotScrolls ?? ""}
+ placeholder={`Default: ${MAX_SCREENSHOT_SCROLLS_DEFAULT}`}
+ onChange={(event) => {
+ setMaxScreenshotScrolls(event.target.value);
+ }}
/>
</div>
</div>
- <div className="flex gap-16">
- <div className="w-48 shrink-0">
- <div className="text-sm">Max Screenshot Scrolls</div>
- <div className="text-xs text-muted-foreground">
- {`The maximum number of scrolls for the post action screenshot. Default is ${MAX_SCREENSHOT_SCROLLS_DEFAULT}. If it's set to 0, it will take the current viewport screenshot.`}
- </div>
- </div>
- <Input
- value={maxScreenshotScrolls ?? ""}
- placeholder={`Default: ${MAX_SCREENSHOT_SCROLLS_DEFAULT}`}
- onChange={(event) => {
- setMaxScreenshotScrolls(event.target.value);
- }}
- />
- </div>
</div>
- </div>
- ) : null}
+ ) : null}
+ </div>
</div>
</div>
+ <div className="flex flex-wrap justify-center gap-4 rounded-sm bg-slate-elevation1 p-4">
+ {exampleCases.map((example) => {
+ return (
+ <ExampleCasePill
+ key={example.key}
+ icon={example.icon}
+ label={example.label}
+ disabled={isSubmitting}
+ onClick={() => {
+ HomeTelemetry.exampleClicked({ label: example.label });
+ submitPrompt({
+ prompt: example.prompt,
+ example: example.key,
+ });
+ }}
+ />
+ );
+ })}
+ </div>
</div>
- <div className="flex flex-wrap justify-center gap-4 rounded-sm bg-slate-elevation1 p-4">
- {exampleCases.map((example) => {
- return (
- <ExampleCasePill
- key={example.key}
- icon={example.icon}
- label={example.label}
- disabled={isSubmitting}
- onClick={() => {
- submitPrompt({ prompt: example.prompt });
+ );
+ }
+
+ return (
+ <div className="relative mx-auto flex w-full max-w-2xl flex-col items-center px-4">
+ <div
+ className={cn("flex flex-col items-center text-center", {
+ "mb-6": minimal,
+ "mb-7": !minimal,
+ })}
+ >
+ <span className="text-2xl">What task would you like to do?</span>
+ {minimal ? (
+ <p className="mt-2 max-w-[47rem] text-[13.5px] text-muted-foreground">
+ Describe it like you would to a colleague. Skyvern opens a browser
+ and does it.
+ <button
+ type="button"
+ aria-expanded={showHowItWorks}
+ onClick={() =>
+ setShowHowItWorks((value) => {
+ HomeTelemetry.howItWorksToggled(!value);
+ return !value;
+ })
+ }
+ className="ml-1.5 inline-flex items-center gap-1 text-[13px] text-foreground/80 underline decoration-muted-foreground/60 underline-offset-[3px] hover:text-foreground"
+ >
+ How it works
+ <ChevronDownIcon
+ aria-hidden="true"
+ className={cn("size-3 transition-transform", {
+ "rotate-180": showHowItWorks,
+ })}
+ />
+ </button>
+ </p>
+ ) : null}
+ </div>
+ <div className="flex w-full flex-col">
+ <div
+ className={cn(
+ "flex w-full flex-col rounded-xl border border-input bg-background p-2 text-muted-foreground shadow-sm transition-colors focus-within:border-foreground/20 focus-within:ring-2 focus-within:ring-ring/10",
+ {
+ "pointer-events-none opacity-50": promptImprovalIsPending,
+ },
+ )}
+ >
+ <CyclingPlaceholderTextarea
+ ref={textareaRef}
+ id="discover-prompt-input"
+ className="max-h-[8rem] min-h-[4rem] resize-none overflow-y-auto border-0 bg-transparent px-3 py-3 leading-5 text-foreground shadow-none placeholder:text-muted-foreground hover:border-0 focus-visible:ring-0"
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ onFocus={() => setPromptTouched(true)}
+ cycling={!promptTouched}
+ />
+ {attachedFiles.length > 0 ? (
+ <div className="flex flex-wrap gap-1.5 px-1 pt-2">
+ {attachedFiles.map((file) => (
+ <span
+ key={file.file_id}
+ className="inline-flex items-center gap-1.5 rounded-md border border-input bg-slate-elevation2 px-2 py-1 text-xs text-foreground"
+ >
+ <FileTextIcon aria-hidden="true" className="size-3.5" />
+ <span className="max-w-[16rem] truncate">
+ {file.filename}
+ </span>
+ <button
+ type="button"
+ aria-label={`Remove ${file.filename}`}
+ className="text-muted-foreground hover:text-foreground"
+ onClick={() =>
+ setAttachedFiles((current) =>
+ current.filter((f) => f.file_id !== file.file_id),
+ )
+ }
+ >
+ <Cross2Icon aria-hidden="true" className="size-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ ) : null}
+ <div className="flex items-center gap-1 pt-2">
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (open) HomeTelemetry.addMenuOpened();
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label="Add to prompt"
+ disabled={isSubmitting}
+ className="flex size-8 items-center justify-center rounded-lg border border-input text-foreground transition-colors hover:bg-muted disabled:opacity-50"
+ >
+ {uploadDocumentMutation.isPending ||
+ recordTaskMutation.isPending ? (
+ <ReloadIcon className="size-4 animate-spin" />
+ ) : (
+ <PlusIcon aria-hidden="true" className="size-4" />
+ )}
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {enableCopilotHandoff ? (
+ <DropdownMenuItem
+ disabled={attachedFiles.length >= MAX_HOME_ATTACHMENTS}
+ onSelect={() => {
+ HomeTelemetry.uploadDocumentSelected();
+ fileInputRef.current?.click();
+ }}
+ >
+ <UploadIcon className="mr-2 size-4" />
+ Upload document
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem
+ onSelect={() => {
+ HomeTelemetry.recordTaskSelected();
+ recordTaskMutation.mutate();
+ }}
+ >
+ <VideoIcon className="mr-2 size-4" />
+ Record task
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <input
+ ref={fileInputRef}
+ type="file"
+ className="hidden"
+ aria-label="Upload document"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (file) {
+ uploadDocumentMutation.mutate(file);
+ }
+ event.target.value = "";
}}
/>
- );
- })}
+ <div className="ml-auto flex items-center gap-1">
+ <SpeechInputButton
+ isSupported={isSpeechSupported}
+ isListening={isSpeechListening}
+ isHearingSpeech={isSpeechHearing}
+ disabled={promptImprovalIsPending || isSubmitting}
+ onToggle={() => {
+ HomeTelemetry.voiceToggled();
+ toggleSpeech();
+ }}
+ className="h-8 w-8 border-0 bg-transparent shadow-none hover:bg-muted"
+ iconClassName="h-4 w-4"
+ />
+ <button
+ type="button"
+ aria-label="submit-prompt"
+ disabled={!prompt.trim() || isSubmitting}
+ className="flex size-8 items-center justify-center rounded-lg bg-cta text-cta-foreground shadow-sm transition-colors hover:bg-cta-hover disabled:pointer-events-none disabled:bg-cta/45 disabled:text-cta-foreground/65 disabled:shadow-none"
+ onClick={() => {
+ submitPrompt({ prompt });
+ }}
+ >
+ {isSubmitting ? (
+ <ReloadIcon className="size-4 animate-spin" />
+ ) : (
+ <PaperPlaneIcon
+ aria-hidden="true"
+ className="size-4 shrink-0"
+ />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
</div>
+ {minimal ? (
+ <div className="mt-[34px] flex w-[76rem] max-w-[calc(100vw-8rem)] flex-col items-center">
+ <CapabilityExamples
+ disabled={isSubmitting}
+ onSelect={(example) => {
+ HomeTelemetry.exampleClicked({
+ capability: example.capability,
+ label: example.label,
+ });
+ setPrompt(example.prompt);
+ setPromptTouched(true);
+ textareaRef.current?.focus();
+ }}
+ onPreview={(example) => HomeTelemetry.examplePreviewShown(example)}
+ />
+ {showHowItWorks ? (
+ <div className="mt-6 flex w-full max-w-[54rem] flex-col gap-3.5 rounded-xl border border-border/70 bg-slate-elevation1/60 px-[18px] py-4 md:flex-row md:items-stretch">
+ {HOW_IT_WORKS.map((step, index) => (
+ <div key={step.title} className="flex flex-1 gap-3.5">
+ {index > 0 ? (
+ <div
+ aria-hidden="true"
+ className="hidden w-px shrink-0 self-stretch bg-border/70 md:block"
+ />
+ ) : null}
+ <div className="min-w-0">
+ <div className="mb-1.5 text-indigo-300">{step.icon}</div>
+ <h3 className="mb-1 text-[13px] font-semibold">
+ {step.title}
+ </h3>
+ <p className="text-xs leading-normal text-muted-foreground">
+ {step.body}
+ </p>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
</div>
);
}
diff --git a/skyvern-frontend/src/routes/tasks/create/capabilityExamples.css b/skyvern-frontend/src/routes/tasks/create/capabilityExamples.css
new file mode 100644
index 000000000..9557e64c2
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/create/capabilityExamples.css
@@ -0,0 +1,493 @@
+/* Mini browser frame used by every capability preview. Dark-only by design: it mocks a browser, not the app. */
+.cx-frame {
+ height: 136px;
+ width: 240px;
+ border-radius: 8px;
+ border: 1px solid hsl(215.3 25% 24%);
+ background: #080d1e;
+ overflow: hidden;
+ color: hsl(210 40% 98%);
+}
+.cx-bar {
+ height: 17px;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 0 6px;
+ background: hsl(228 30% 13%);
+ border-bottom: 1px solid hsl(215.3 25% 20%);
+}
+.cx-dot {
+ width: 4px;
+ height: 4px;
+ border-radius: 50%;
+ background: hsl(215 16% 38%);
+ flex: none;
+}
+.cx-url {
+ flex: 1;
+ height: 7px;
+ border-radius: 4px;
+ background: hsl(228 28% 20%);
+ margin-left: 4px;
+}
+.cx-body {
+ position: relative;
+ height: calc(100% - 17px);
+ padding: 9px 10px;
+}
+
+.cx-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+}
+.cx-lab {
+ width: 34px;
+ height: 5px;
+ border-radius: 3px;
+ background: hsl(215 16% 34%);
+ flex: none;
+}
+.cx-field {
+ flex: 1;
+ height: 15px;
+ border-radius: 4px;
+ border: 1px solid hsl(215.3 25% 26%);
+ background: hsl(228 30% 12%);
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ padding: 0 4px;
+}
+.cx-ink {
+ height: 5px;
+ border-radius: 3px;
+ background: hsl(210 40% 88%);
+ width: 100%;
+}
+.cx-btn {
+ height: 16px;
+ border-radius: 4px;
+ background: hsl(210 40% 90%);
+ width: 52px;
+ margin-left: auto;
+ display: grid;
+ place-items: center;
+ font-size: 8px;
+ font-weight: 600;
+ color: #0b1020;
+}
+
+/* Fill forms */
+.cx-form .cx-ink {
+ animation: cx-ink-fill 3s ease-in-out infinite;
+}
+.cx-form .cx-row:nth-child(2) .cx-ink {
+ animation-delay: 0.5s;
+}
+.cx-form .cx-row:nth-child(3) .cx-ink {
+ animation-delay: 1s;
+}
+.cx-form .cx-btn {
+ animation: cx-btn-press 3s ease-in-out infinite;
+}
+@keyframes cx-ink-fill {
+ 0%,
+ 4% {
+ width: 0;
+ }
+ 16%,
+ 92% {
+ width: 100%;
+ }
+ 100% {
+ width: 0;
+ }
+}
+@keyframes cx-btn-press {
+ 0%,
+ 52% {
+ background: hsl(215 16% 30%);
+ color: hsl(215 16% 55%);
+ transform: scale(1);
+ }
+ 58% {
+ transform: scale(0.94);
+ }
+ 62%,
+ 92% {
+ background: hsl(142.1 76.2% 36.3%);
+ color: #eafff2;
+ transform: scale(1);
+ }
+ 100% {
+ background: hsl(215 16% 30%);
+ color: hsl(215 16% 55%);
+ }
+}
+
+/* Extract data */
+.cx-table .cx-split {
+ display: flex;
+ gap: 8px;
+ height: 100%;
+}
+.cx-table .cx-rows {
+ width: 46%;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding-top: 2px;
+}
+.cx-table .cx-trow {
+ height: 11px;
+ border-radius: 3px;
+ background: hsl(228 28% 17%);
+ position: relative;
+}
+.cx-table .cx-trow::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ border-radius: 3px;
+ background: hsl(239 70% 62% / 0.55);
+ animation: cx-row-scan 3s ease-in-out infinite;
+}
+.cx-table .cx-trow:nth-child(2)::after {
+ animation-delay: 0.28s;
+}
+.cx-table .cx-trow:nth-child(3)::after {
+ animation-delay: 0.56s;
+}
+.cx-table .cx-trow:nth-child(4)::after {
+ animation-delay: 0.84s;
+}
+@keyframes cx-row-scan {
+ 0%,
+ 3% {
+ opacity: 0;
+ }
+ 12%,
+ 92% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0;
+ }
+}
+.cx-table .cx-json {
+ flex: 1;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 8px;
+ line-height: 1.55;
+ color: hsl(215 22% 70%);
+ background: hsl(228 32% 12%);
+ border: 1px solid hsl(215.3 25% 22%);
+ border-radius: 5px;
+ padding: 5px 6px;
+ overflow: hidden;
+ white-space: pre;
+ animation: cx-json-in 3s ease-in-out infinite;
+}
+.cx-table .cx-json b {
+ color: hsl(160 60% 62%);
+ font-weight: 500;
+}
+@keyframes cx-json-in {
+ 0%,
+ 42% {
+ opacity: 0;
+ transform: translateY(3px);
+ }
+ 55%,
+ 92% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+ 100% {
+ opacity: 0;
+ }
+}
+
+/* Log in and download */
+.cx-login .cx-dots {
+ display: flex;
+ gap: 3px;
+}
+.cx-login .cx-dots i {
+ width: 4px;
+ height: 4px;
+ border-radius: 50%;
+ background: hsl(210 40% 85%);
+ display: block;
+ animation: cx-dot-in 3s ease-in-out infinite;
+}
+.cx-login .cx-dots i:nth-child(2) {
+ animation-delay: 0.09s;
+}
+.cx-login .cx-dots i:nth-child(3) {
+ animation-delay: 0.18s;
+}
+.cx-login .cx-dots i:nth-child(4) {
+ animation-delay: 0.27s;
+}
+.cx-login .cx-dots i:nth-child(5) {
+ animation-delay: 0.36s;
+}
+.cx-login .cx-dots i:nth-child(6) {
+ animation-delay: 0.45s;
+}
+@keyframes cx-dot-in {
+ 0%,
+ 5% {
+ opacity: 0;
+ }
+ 14%,
+ 92% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0;
+ }
+}
+.cx-login .cx-otp {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin-top: 4px;
+ border: 1px solid hsl(239 60% 55%);
+ background: hsl(239 60% 30% / 0.35);
+ color: hsl(228 90% 88%);
+ border-radius: 6px;
+ padding: 3px 7px;
+ font-family: ui-monospace, Menlo, monospace;
+ font-size: 9px;
+ letter-spacing: 0.08em;
+ animation: cx-otp-in 3s ease-in-out infinite;
+}
+.cx-login .cx-otp svg {
+ width: 9px;
+ height: 9px;
+}
+@keyframes cx-otp-in {
+ 0%,
+ 26% {
+ opacity: 0;
+ transform: translateX(-6px);
+ }
+ 38%,
+ 92% {
+ opacity: 1;
+ transform: translateX(0);
+ }
+ 100% {
+ opacity: 0;
+ }
+}
+.cx-login .cx-file {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin-top: 9px;
+ border: 1px solid hsl(215.3 25% 30%);
+ background: hsl(228 30% 15%);
+ border-radius: 6px;
+ padding: 4px 8px;
+ font-size: 9.5px;
+ color: hsl(210 30% 88%);
+ animation: cx-file-in 3s ease-in-out infinite;
+}
+.cx-login .cx-file svg {
+ width: 10px;
+ height: 10px;
+ color: hsl(142.1 76.2% 36.3%);
+}
+@keyframes cx-file-in {
+ 0%,
+ 58% {
+ opacity: 0;
+ transform: translateY(6px);
+ }
+ 70%,
+ 92% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+ 100% {
+ opacity: 0;
+ }
+}
+
+/* Monitor */
+.cx-watch .cx-price {
+ position: relative;
+ height: 22px;
+ font-size: 17px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+.cx-watch .cx-price span {
+ position: absolute;
+ left: 0;
+ top: 0;
+}
+.cx-watch .cx-p-old {
+ color: hsl(215 20% 72%);
+ animation: cx-p-old 3s ease-in-out infinite;
+}
+.cx-watch .cx-p-new {
+ color: hsl(142 60% 62%);
+ animation: cx-p-new 3s ease-in-out infinite;
+}
+@keyframes cx-p-old {
+ 0%,
+ 44% {
+ opacity: 1;
+ }
+ 50%,
+ 100% {
+ opacity: 0;
+ }
+}
+@keyframes cx-p-new {
+ 0%,
+ 44% {
+ opacity: 0;
+ }
+ 52%,
+ 100% {
+ opacity: 1;
+ }
+}
+.cx-watch .cx-meta {
+ font-size: 9.5px;
+ color: hsl(215 18% 55%);
+ margin-top: 1px;
+}
+.cx-watch .cx-spark {
+ margin-top: 6px;
+}
+.cx-watch .cx-spark .cx-line {
+ stroke: hsl(239 70% 68%);
+ stroke-width: 1.4;
+ fill: none;
+}
+.cx-watch .cx-spark .cx-tip {
+ fill: hsl(142 60% 62%);
+}
+.cx-watch .cx-bell {
+ position: absolute;
+ right: 12px;
+ top: 12px;
+ color: hsl(45 90% 65%);
+ transform-origin: 50% 12%;
+ animation: cx-bell 3s ease-in-out infinite;
+}
+.cx-watch .cx-bell svg {
+ width: 17px;
+ height: 17px;
+}
+@keyframes cx-bell {
+ 0%,
+ 46% {
+ transform: rotate(0deg);
+ opacity: 0.35;
+ }
+ 52% {
+ transform: rotate(16deg);
+ opacity: 1;
+ }
+ 58% {
+ transform: rotate(-13deg);
+ }
+ 64% {
+ transform: rotate(9deg);
+ }
+ 70%,
+ 100% {
+ transform: rotate(0deg);
+ opacity: 1;
+ }
+}
+
+/* Run on a schedule */
+.cx-cal .cx-grid {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: 5px;
+ width: 152px;
+ position: relative;
+}
+.cx-cal .cx-grid i {
+ height: 11px;
+ border-radius: 3px;
+ background: hsl(228 28% 18%);
+ display: block;
+}
+.cx-cal .cx-ring {
+ position: absolute;
+ width: 17px;
+ height: 15px;
+ border-radius: 4px;
+ left: -2px;
+ top: -2px;
+ border: 1.5px solid hsl(239 75% 70%);
+ background: hsl(239 70% 60% / 0.22);
+ animation: cx-cal-step 3s steps(1, end) infinite;
+}
+@keyframes cx-cal-step {
+ 0%,
+ 32% {
+ transform: translate(85px, 0);
+ }
+ 33%,
+ 65% {
+ transform: translate(85px, 16px);
+ }
+ 66%,
+ 100% {
+ transform: translate(85px, 32px);
+ }
+}
+.cx-cal .cx-clock {
+ position: absolute;
+ right: 12px;
+ bottom: 12px;
+ width: 34px;
+ height: 34px;
+}
+.cx-cal .cx-clock circle {
+ fill: none;
+ stroke: hsl(215.3 25% 32%);
+ stroke-width: 1.4;
+}
+.cx-cal .cx-clock .cx-hand {
+ stroke: hsl(210 40% 90%);
+ stroke-width: 1.4;
+ stroke-linecap: round;
+ transform-origin: 17px 17px;
+ animation: cx-hand-spin 3s linear infinite;
+}
+@keyframes cx-hand-spin {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
+.cx-cal .cx-when {
+ position: absolute;
+ left: 10px;
+ bottom: 11px;
+ font-size: 9.5px;
+ color: hsl(215 18% 58%);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .cx-frame * {
+ animation: none !important;
+ }
+}
diff --git a/skyvern-frontend/src/routes/tasks/create/useCyclingPlaceholder.ts b/skyvern-frontend/src/routes/tasks/create/useCyclingPlaceholder.ts
new file mode 100644
index 000000000..03d95e19b
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/create/useCyclingPlaceholder.ts
@@ -0,0 +1,58 @@
+import { useEffect, useState } from "react";
+
+const PLACEHOLDERS = [
+ "Go to a supplier portal, log in, and download last month's invoices as PDF",
+ "Search a job board for Solutions Engineer roles in Toronto and apply to the first three",
+ "Pull every row out of the vendor price list and return it as JSON",
+ "Check the competitor's pricing page each morning and tell me when it changes",
+ "Log in to the claims portal, submit the form, and save the confirmation number",
+];
+const RESTING = "Enter your prompt...";
+
+// Types out example prompts as the placeholder until the user engages; then rests.
+function useCyclingPlaceholder(active: boolean): string {
+ const [text, setText] = useState(RESTING);
+
+ useEffect(() => {
+ if (!active) {
+ setText(RESTING);
+ return;
+ }
+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ setText(PLACEHOLDERS[0]!);
+ return;
+ }
+ let index = 0;
+ let cursor = 0;
+ let deleting = false;
+ let timer = window.setTimeout(tick, 700);
+ function tick() {
+ const full = PLACEHOLDERS[index]!;
+ if (!deleting) {
+ cursor += 1;
+ setText(`${full.slice(0, cursor)}|`);
+ if (cursor < full.length) {
+ timer = window.setTimeout(tick, 34);
+ } else {
+ deleting = true;
+ timer = window.setTimeout(tick, 1500);
+ }
+ } else {
+ cursor -= 1;
+ setText(`${full.slice(0, cursor)}|`);
+ if (cursor > 0) {
+ timer = window.setTimeout(tick, 14);
+ } else {
+ deleting = false;
+ index = (index + 1) % PLACEHOLDERS.length;
+ timer = window.setTimeout(tick, 320);
+ }
+ }
+ }
+ return () => window.clearTimeout(timer);
+ }, [active]);
+
+ return text;
+}
+
+export { useCyclingPlaceholder };
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
index d126851b4..6ebdcce74 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
@@ -8,6 +8,7 @@ import {
waitFor,
within,
} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
@@ -41,6 +42,7 @@ const {
credsFail,
modalOverrideType,
modalDefaultTestUrl,
+ modalEditingCredentialId,
toastFn,
} = vi.hoisted(() => {
const calls: StreamCall[] = [];
@@ -89,6 +91,12 @@ const {
? Promise.reject(new Error("network"))
: Promise.resolve({ data: creds.current });
}
+ if (path.startsWith("/credentials/")) {
+ const id = decodeURIComponent(path.slice("/credentials/".length));
+ return Promise.resolve({
+ data: creds.current.find((c) => c.credential_id === id),
+ });
+ }
return Promise.resolve(history);
});
// Route post by API version: copilot routes (credential-response) must use
@@ -111,6 +119,7 @@ const {
credsFail: fail,
modalOverrideType: { current: undefined as string | undefined },
modalDefaultTestUrl: { current: undefined as string | undefined },
+ modalEditingCredentialId: { current: undefined as string | undefined },
toastFn: vi.fn(),
};
});
@@ -210,14 +219,17 @@ vi.mock("@/routes/credentials/CredentialsModal", () => ({
onCredentialCreated,
overrideType,
defaultTestUrl,
+ editingCredential,
}: {
isOpen?: boolean;
onCredentialCreated?: (id: string, name?: string) => void;
overrideType?: string;
defaultTestUrl?: string;
+ editingCredential?: { credential_id: string };
}) => {
modalOverrideType.current = overrideType;
modalDefaultTestUrl.current = defaultTestUrl;
+ modalEditingCredentialId.current = editingCredential?.credential_id;
return isOpen ? (
<button
type="button"
@@ -303,7 +315,14 @@ vi.mock("@/routes/workflows/hooks/useWorkflowRunQuery", () => ({
import { WorkflowCopilotChat } from "./WorkflowCopilotChat";
async function renderChat() {
- const view = render(<WorkflowCopilotChat docked={false} />);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const view = render(
+ <QueryClientProvider client={queryClient}>
+ <WorkflowCopilotChat docked={false} />
+ </QueryClientProvider>,
+ );
await waitFor(() => expect(screen.getByRole("textbox")).toBeTruthy());
return view;
}
@@ -471,6 +490,7 @@ beforeEach(() => {
credsFail.current = false;
modalOverrideType.current = undefined;
modalDefaultTestUrl.current = undefined;
+ modalEditingCredentialId.current = undefined;
historyResponse.data = {
workflow_copilot_chat_id: "chat-1",
chat_history: [],
@@ -756,6 +776,58 @@ describe("WorkflowCopilotChat — credential card wiring", () => {
expect(await screen.findByText(/Credential 'HN Login' added/)).toBeTruthy();
});
+ it("a second card in the same turn stays actionable and answers with its own resume token", async () => {
+ credentialsData.current = [
+ {
+ credential_id: "cred-hn",
+ name: "HN Login",
+ tested_url: "https://news.ycombinator.com/login",
+ },
+ ];
+ await renderChat();
+ await submit("build me a workflow");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage(turnStart());
+ streamCalls[0]!.onMessage(credentialFrame());
+ });
+ await act(async () => {
+ fireEvent.click(await screen.findByRole("combobox"));
+ });
+ await act(async () => {
+ fireEvent.click(await screen.findByRole("button", { name: "HN Login" }));
+ });
+ await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));
+
+ await act(async () => {
+ streamCalls[0]!.onMessage(
+ credentialFrame({
+ resume_token: "rt-update",
+ reason: "credential_missing_totp",
+ credential_refs: ["cred-hn"],
+ }),
+ );
+ });
+ const update = await screen.findByRole("button", {
+ name: "Add 2FA method",
+ });
+ await waitFor(() =>
+ expect((update as HTMLButtonElement).disabled).toBe(false),
+ );
+ await act(async () => {
+ fireEvent.click(update);
+ });
+ expect(modalEditingCredentialId.current).toBe("cred-hn");
+ await act(async () => {
+ fireEvent.click(await screen.findByTestId("mock-create-credential"));
+ });
+ await waitFor(() => expect(credentialResponsePosts()).toHaveLength(2));
+ expect(credentialResponsePosts()[1]![1]).toMatchObject({
+ resume_token: "rt-update",
+ action: "connected",
+ });
+ });
+
it("connect CTA opens the modal, then a created credential POSTs connected", async () => {
await renderChat();
await submit("build me a workflow");
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
index 2ae9549ed..a99dc12e8 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
@@ -6,13 +6,14 @@ import {
screen,
waitFor,
} from "@testing-library/react";
-import type { ComponentProps } from "react";
+import { useState, type ComponentProps } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { toast } from "@/components/ui/use-toast";
import { getSseClient } from "@/api/sse";
import { FeatureFlagContext } from "@/hooks/useFeatureFlag";
import { useCopilotActionStore } from "@/store/useCopilotActionStore";
+import { useCopilotHeaderStore } from "@/store/useCopilotHeaderStore";
import type { WorkflowCopilotStreamResponseUpdate } from "./workflowCopilotTypes";
@@ -230,6 +231,30 @@ async function renderChat(
return view;
}
+function HomeHandoffChat({
+ isLiveBrowserReady,
+ docked = false,
+}: {
+ isLiveBrowserReady: boolean;
+ docked?: boolean;
+}) {
+ const [initialMessage, setInitialMessage] = useState<string | undefined>(
+ "Create a workflow that opens example.com",
+ );
+
+ return (
+ <WorkflowCopilotChat
+ initialMessage={initialMessage}
+ onInitialMessageConsumed={() => setInitialMessage(undefined)}
+ requiresLiveBrowser
+ isLiveBrowserReady={isLiveBrowserReady}
+ liveBrowserSessionId={isLiveBrowserReady ? "pbs_live_1" : null}
+ docked={docked}
+ portalTarget={docked ? document.body : undefined}
+ />
+ );
+}
+
async function renderChatWithFlags(booleanFlags: Record<string, boolean>) {
const view = render(
<FeatureFlagContext.Provider value={(name) => booleanFlags[name]}>
@@ -344,6 +369,7 @@ beforeEach(() => {
proposed_workflow: null,
auto_accept: false,
};
+ saveData.workflow.workflow_id = "wf_1";
useCopilotActionStore.setState({
pendingBuild: null,
generatingBlockLabel: null,
@@ -615,6 +641,123 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
expect(screen.queryByRole("button", { name: "Queue" })).toBeNull();
});
+ it("shows a Home handoff prompt before the Copilot is ready", async () => {
+ const prompt = "Create a workflow that opens example.com";
+ historyResponse.data.chat_history = [
+ {
+ sender: "ai",
+ content: "Ready to build your workflow.",
+ created_at: "2026-05-25T00:00:00Z",
+ },
+ ];
+ const view = render(<HomeHandoffChat isLiveBrowserReady={false} />);
+
+ expect(screen.getByText(prompt)).toBeTruthy();
+
+ await waitFor(() =>
+ expect(
+ screen.getByText("Prompt queued. Waiting for live browser..."),
+ ).toBeTruthy(),
+ );
+ expect(screen.getAllByText(prompt)).toHaveLength(1);
+
+ view.rerender(<HomeHandoffChat isLiveBrowserReady />);
+
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ expect(streamCalls[0]?.body.message).toBe(prompt);
+ expect(screen.getAllByText(prompt)).toHaveLength(1);
+
+ await completeOldestStream("Workflow built.");
+ expect(screen.getAllByText(prompt)).toHaveLength(1);
+ const promptBubble = screen.getByText(prompt);
+ const responseBubble = screen.getByText("Workflow built.");
+ expect(
+ promptBubble.compareDocumentPosition(responseBubble) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it("does not carry the Home handoff prompt into another history chat", async () => {
+ const prompt = "Create a workflow that opens example.com";
+ render(<HomeHandoffChat isLiveBrowserReady={false} docked />);
+
+ await waitFor(() =>
+ expect(
+ screen.getByText("Prompt queued. Waiting for live browser..."),
+ ).toBeTruthy(),
+ );
+ historyResponse.data = {
+ ...historyResponse.data,
+ workflow_copilot_chat_id: "chat-2",
+ chat_history: [
+ {
+ sender: "ai",
+ content: "This belongs to a different chat.",
+ created_at: "2026-05-25T00:01:00Z",
+ },
+ ],
+ };
+
+ await act(async () => {
+ await useCopilotHeaderStore.getState().controls?.onSelectChat?.({
+ workflow_copilot_chat_id: "chat-2",
+ } as Parameters<
+ NonNullable<
+ NonNullable<
+ ReturnType<typeof useCopilotHeaderStore.getState>["controls"]
+ >["onSelectChat"]
+ >
+ >[0]);
+ });
+
+ expect(screen.queryByText(prompt)).toBeNull();
+ expect(screen.getByText("This belongs to a different chat.")).toBeTruthy();
+ });
+
+ it("keeps the Home handoff prompt during a same-chat reload", async () => {
+ const prompt = "Create a workflow that opens example.com";
+ const workflowId = saveData.workflow.workflow_id;
+ saveData.workflow.workflow_id = "";
+ historyResponse.data = {
+ ...historyResponse.data,
+ workflow_copilot_chat_id: "chat-1",
+ };
+ Object.assign(historyResponse.data, {
+ question_interactions: [
+ {
+ interaction_id: "interaction-1",
+ turn_id: "turn-1",
+ tool_call_id: "call-1",
+ status: "pending",
+ response: null,
+ created_at: "2026-05-25T00:00:00Z",
+ resolved_at: null,
+ parts: [
+ {
+ part_id: "part-1",
+ prompt: "Which site?",
+ choices: [],
+ },
+ ],
+ },
+ ],
+ pending_question_cancel_token: "cancel-1",
+ });
+
+ render(<HomeHandoffChat isLiveBrowserReady={false} />);
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Cancel question" }),
+ ).toBeTruthy(),
+ );
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Cancel question" }));
+ });
+
+ expect(screen.getByText(prompt)).toBeTruthy();
+ saveData.workflow.workflow_id = workflowId;
+ });
+
it("explains that the next send waits while the live browser is starting", async () => {
render(
<WorkflowCopilotChat requiresLiveBrowser isLiveBrowserReady={false} />,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 5da1dc93b..ce48fe986 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -9,7 +9,11 @@ import {
memo,
} from "react";
import { getClient, deleteUploadedFileOnPageExit } from "@/api/AxiosClient";
-import { ActionsApiResponse, getReadableActionType } from "@/api/types";
+import {
+ ActionsApiResponse,
+ type CredentialApiResponse,
+ getReadableActionType,
+} from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { CredentialsModal } from "@/routes/credentials/CredentialsModal";
import { CredentialModalTypes } from "@/routes/credentials/useCredentialModalState";
@@ -475,7 +479,11 @@ export interface ChatMessage {
// turns. Live in-flight narrative is rendered separately at the bottom.
narrative?: TurnNarrativeState;
// FE-synthetic rows (never persisted, never sent to the LLM).
- kind?: "run_lifecycle" | "status_notice" | "recording_refinement";
+ kind?:
+ | "run_lifecycle"
+ | "status_notice"
+ | "recording_refinement"
+ | "initial_handoff";
recoveryTurnId?: string;
recordingRefinement?: {
actionCount: number;
@@ -721,6 +729,7 @@ type QueuedPrompt = {
type SendOptions = {
selectedConnectedAccountId?: string;
queuedMessageId?: string;
+ optimisticMessageId?: string;
skipQueue?: boolean;
audioBlob?: Blob | null;
idempotencyKey?: string;
@@ -808,17 +817,17 @@ type CredentialResolution = CredentialPauseHistorical & {
continued?: boolean;
};
-// Append a resolution keyed by turn, capping the map with oldest-eviction like
+// Append a resolution under its key (a turn or a card), capping the map with oldest-eviction like
// the sibling per-turn maps (turnSnapshots/turnOwnedRunIds). delete-then-set
-// re-inserts an existing turn as newest so an active turn isn't evicted.
+// re-inserts an existing key as newest so an active one isn't evicted.
function withCappedResolution(
prev: Record<string, CredentialResolution>,
- turnId: string,
+ key: string,
value: CredentialResolution,
): Record<string, CredentialResolution> {
const next = { ...prev };
- delete next[turnId];
- next[turnId] = value;
+ delete next[key];
+ next[key] = value;
const keys = Object.keys(next);
for (const key of keys.slice(
0,
@@ -972,6 +981,8 @@ interface WorkflowCopilotChatProps {
requiresLiveBrowser?: boolean;
isLiveBrowserReady?: boolean;
initialMessage?: string;
+ /** Files uploaded before the handoff; sent with the initial message. */
+ initialAttachments?: Array<CopilotAttachedFile>;
initialAction?: CopilotProductAction;
onInitialMessageConsumed?: () => void;
onUploadSOP?: (file: File) => void;
@@ -1078,6 +1089,7 @@ export function WorkflowCopilotChat({
requiresLiveBrowser = false,
isLiveBrowserReady = false,
initialMessage,
+ initialAttachments,
initialAction,
onInitialMessageConsumed,
onUploadSOP,
@@ -1090,6 +1102,8 @@ export function WorkflowCopilotChat({
chromeless = false,
portalTarget,
}: WorkflowCopilotChatProps = {}) {
+ const workflowPermanentId = useWorkflowPermanentId();
+ const initialHandoffMessageId = `initial-copilot-message-${workflowPermanentId ?? "pending"}`;
const sopFileInputRef = useRef<HTMLInputElement>(null);
const recordingAuthoringActive = useRecordingStore(
(state) => state.isRecording || state.finishRequested || state.isCommitting,
@@ -1120,7 +1134,19 @@ export function WorkflowCopilotChat({
// dropdown rather than a separate toggle.
const codeOptionAvailable = codeBlockModeEnabled;
const codeStateActive = codeWorkflow && codeOptionAvailable;
- const [messages, setMessages] = useState<ChatMessage[]>([]);
+ const [messages, setMessages] = useState<ChatMessage[]>(() =>
+ !initialAction && initialMessage
+ ? [
+ {
+ id: initialHandoffMessageId,
+ sender: "user",
+ content: initialMessage,
+ kind: "initial_handoff",
+ attachedFiles: initialAttachments,
+ },
+ ]
+ : [],
+ );
const [workPlan, setWorkPlan] = useState<string[]>([]);
const [proposedWorkflow, setProposedWorkflow] =
useState<WorkflowApiResponse | null>(null);
@@ -1356,6 +1382,10 @@ export function WorkflowCopilotChat({
const [credentialResolutions, setCredentialResolutions] = useState<
Record<string, CredentialResolution>
>({});
+ // Live pause answers keyed by resume_token: one turn can raise a pick card and then an update card.
+ const [pauseCardResolutions, setPauseCardResolutions] = useState<
+ Record<string, CredentialResolution>
+ >({});
// Terminal asks whose auto-continue send failed: the optimistic "connected"
// receipt is rolled back and the ask is forced actionable again (it is no
// longer the tail) so the user can re-pick instead of hitting a dead end.
@@ -1372,6 +1402,7 @@ export function WorkflowCopilotChat({
frame: WorkflowCopilotCredentialRequiredUpdate | null;
turnId: string;
isLastMessage: boolean;
+ editingCredential?: CredentialApiResponse;
} | null>(null);
// Original ask turnId whose auto-continue send is in flight, so a stream
// failure can roll its optimistic resolution back. Cleared in handleSend's
@@ -1569,7 +1600,44 @@ export function WorkflowCopilotChat({
const { workflowRunId: routeWorkflowRunId } = useParams();
const navigate = useNavigate();
const location = useLocation();
- const workflowPermanentId = useWorkflowPermanentId();
+ const initialMessageIdentityRef = useRef({
+ workflowPermanentId,
+ initialMessage,
+ });
+ useEffect(() => {
+ const previousIdentity = initialMessageIdentityRef.current;
+ const workflowChanged =
+ previousIdentity.workflowPermanentId !== workflowPermanentId;
+ const messageChanged = previousIdentity.initialMessage !== initialMessage;
+ initialMessageIdentityRef.current = { workflowPermanentId, initialMessage };
+
+ if (
+ !initialAction &&
+ initialMessage &&
+ (workflowChanged || messageChanged)
+ ) {
+ setMessages((current) => [
+ {
+ id: initialHandoffMessageId,
+ sender: "user",
+ content: initialMessage,
+ kind: "initial_handoff",
+ attachedFiles: initialAttachments,
+ },
+ ...current.filter((message) => message.kind !== "initial_handoff"),
+ ]);
+ } else if (workflowChanged) {
+ setMessages((current) =>
+ current.filter((message) => message.kind !== "initial_handoff"),
+ );
+ }
+ }, [
+ initialAction,
+ initialAttachments,
+ initialHandoffMessageId,
+ initialMessage,
+ workflowPermanentId,
+ ]);
// The studio focuses a run via ?wr= (not a path param), so the route param is
// empty there; an explicit prop grounds the chat in that run and wins.
const workflowRunId = workflowRunIdProp ?? routeWorkflowRunId;
@@ -1808,15 +1876,19 @@ export function WorkflowCopilotChat({
frame.turn_id,
);
}
- setCredentialResolutions((prev) =>
- withCappedResolution(
- prev,
- frame.turn_id,
- action === "connected"
- ? { outcome: "connected", credentialId, name }
- : { outcome: "skipped" },
- ),
+ const resolution: CredentialResolution =
+ action === "connected"
+ ? { outcome: "connected", credentialId, name }
+ : { outcome: "skipped" };
+ setPauseCardResolutions((prev) =>
+ withCappedResolution(prev, frame.resume_token, resolution),
);
+ // An update card fixes the credential the turn already chose, so the turn's answer stays put.
+ if (frame.reason !== "credential_missing_totp") {
+ setCredentialResolutions((prev) =>
+ withCappedResolution(prev, frame.turn_id, resolution),
+ );
+ }
} catch (error) {
// Log only the message: the AxiosError serializes config.data, which
// carries the one-time resume_token, into the console otherwise.
@@ -1932,8 +2004,14 @@ export function WorkflowCopilotChat({
frame: WorkflowCopilotCredentialRequiredUpdate | null,
turnId: string,
isLastMessage = false,
+ editingCredential?: CredentialApiResponse,
) => {
- pendingCredentialConnect.current = { frame, turnId, isLastMessage };
+ pendingCredentialConnect.current = {
+ frame,
+ turnId,
+ isLastMessage,
+ editingCredential,
+ };
setCredentialModalOpen(true);
},
[],
@@ -2246,7 +2324,20 @@ export function WorkflowCopilotChat({
// History never carries run_lifecycle lines (local-only); carry them
// forward only for the mount-race caller, not an explicit chat switch.
setMessages((prev) => {
+ const initialHandoff = carryForwardLifecycle
+ ? prev.find((message) => message.kind === "initial_handoff")
+ : undefined;
+ const historyIncludesInitialHandoff =
+ initialHandoff !== undefined &&
+ historyMessages.some(
+ (message) =>
+ message.sender === "user" &&
+ message.content === initialHandoff.content,
+ );
const nextMessages: ChatMessage[] = [
+ ...(initialHandoff && !historyIncludesInitialHandoff
+ ? [initialHandoff]
+ : []),
...historyMessages,
...(carryForwardLifecycle
? prev.filter((message) => message.kind === "run_lifecycle")
@@ -2713,7 +2804,8 @@ export function WorkflowCopilotChat({
const loadChatInPlace = useCallback(
async (chatId: string) => {
if (!workflowPermanentId) return;
- if (workflowCopilotChatIdRef.current !== chatId) {
+ const isChatSwitch = workflowCopilotChatIdRef.current !== chatId;
+ if (isChatSwitch) {
streamingAbortController.current?.abort();
streamingAbortController.current = null;
inFlightRef.current = false;
@@ -2755,7 +2847,7 @@ export function WorkflowCopilotChat({
) {
return;
}
- applyHistoryResponse(response.data, false);
+ applyHistoryResponse(response.data, !isChatSwitch);
adoptRecoveredTurns(response.data);
// Mark history loaded for this workflow so the mount effect won't reload
// the latest chat over the one the user just selected.
@@ -4553,7 +4645,10 @@ export function WorkflowCopilotChat({
if (action === "queue_working" || action === "queue_live_browser") {
const reason: QueuedPromptReason =
action === "queue_working" ? "working" : "live_browser";
- const queuedId = options.queuedMessageId ?? crypto.randomUUID();
+ const queuedId =
+ options.queuedMessageId ??
+ options.optimisticMessageId ??
+ crypto.randomUUID();
updateQueuedPrompt({
id: queuedId,
content: candidate,
@@ -4568,7 +4663,7 @@ export function WorkflowCopilotChat({
}
// First queue adds the user bubble; a re-queue (a working drain that
// then had to wait for the browser) reuses the existing bubble.
- if (!options.queuedMessageId) {
+ if (!options.queuedMessageId && !options.optimisticMessageId) {
setMessages((prev) => [
...prev,
{
@@ -4601,7 +4696,10 @@ export function WorkflowCopilotChat({
return;
}
- const userMessageId = options.queuedMessageId ?? Date.now().toString();
+ const userMessageId =
+ options.queuedMessageId ??
+ options.optimisticMessageId ??
+ Date.now().toString();
const sendOwnsTray = composerSend;
const recordingRefinementAction =
productActionRef.current?.action === "refine_recording"
@@ -4637,7 +4735,7 @@ export function WorkflowCopilotChat({
lastFollowedLabelRef.current = null;
pendingMessageId.current = userMessageId;
- if (!options.queuedMessageId) {
+ if (!options.queuedMessageId && !options.optimisticMessageId) {
setMessages((prev) => [...prev, userMessage]);
} else {
// Also when the filtered list is empty: a queued bubble must not keep showing files the
@@ -5986,13 +6084,25 @@ export function WorkflowCopilotChat({
}
: { action: "refine_recording", nonce: initialAction.nonce };
}
- handleSend(autoSendMessage).catch((error) => {
+ handleSend(
+ autoSendMessage,
+ !initialAction
+ ? {
+ optimisticMessageId: initialHandoffMessageId,
+ attachments: initialAttachments,
+ }
+ : initialAttachments && initialAttachments.length > 0
+ ? { attachments: initialAttachments }
+ : undefined,
+ ).catch((error) => {
console.error("Auto-send failed:", error);
});
}, [
handleSend,
autoSendMessage,
+ initialAttachments,
initialAction,
+ initialHandoffMessageId,
acceptUnresolved,
isLoading,
isLoadingHistory,
@@ -7075,11 +7185,11 @@ export function WorkflowCopilotChat({
)
.map((frame) => (
<CredentialCard
- key={frame.turn_id}
+ key={frame.resume_token}
frame={liveFrameToCardFrame(frame)}
mode="inline-pause"
reloadKey={credentialsReloadKey}
- resolvedOutcome={credentialResolutions[frame.turn_id]}
+ resolvedOutcome={pauseCardResolutions[frame.resume_token]}
onConnect={(credentialId, name) =>
credentialId
? void respondToCredentialPause(
@@ -7090,6 +7200,14 @@ export function WorkflowCopilotChat({
)
: openCredentialModal(frame, frame.turn_id)
}
+ onUpdateCredential={(credential) =>
+ openCredentialModal(
+ frame,
+ frame.turn_id,
+ false,
+ credential,
+ )
+ }
onSkip={() => void respondToCredentialPause(frame, "skip")}
/>
))}
@@ -7108,11 +7226,20 @@ export function WorkflowCopilotChat({
livePauseFrame &&
livePauseFrame.turn_id === narrative.turnId ? (
<CredentialCard
+ key={livePauseFrame.resume_token}
frame={liveFrameToCardFrame(livePauseFrame)}
mode="inline-pause"
reloadKey={credentialsReloadKey}
resolvedOutcome={
- credentialResolutions[livePauseFrame.turn_id]
+ pauseCardResolutions[livePauseFrame.resume_token]
+ }
+ onUpdateCredential={(credential) =>
+ openCredentialModal(
+ livePauseFrame,
+ livePauseFrame.turn_id,
+ false,
+ credential,
+ )
}
// A picked credential (id + name from the fetched list) answers through the typed
// resume POST, which origin-binds; the Add-credential CTA (no id) opens the modal.
@@ -7603,6 +7730,15 @@ export function WorkflowCopilotChat({
defaultTestUrl={
pendingCredentialConnect.current?.frame?.login_page_urls?.[0]
}
+ editingCredential={
+ pendingCredentialConnect.current?.editingCredential
+ }
+ // The chat edits a saved credential only to add its missing authenticator.
+ defaultTotpType={
+ pendingCredentialConnect.current?.editingCredential
+ ? "authenticator"
+ : undefined
+ }
onOpenChange={(open) => {
setCredentialModalOpen(open);
if (!open) pendingCredentialConnect.current = null;
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts
index c672163d0..10642a509 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts
@@ -50,6 +50,11 @@ export const CREDENTIAL_REQUIRED_FRAME_BY_REASON = {
reason: "credential_deferred_draft",
message: "Picking back up on the credential you held off on earlier.",
}),
+ credential_missing_totp: buildCredentialRequiredFrame({
+ reason: "credential_missing_totp",
+ message: "The sign-in reached a 2-Step Verification page.",
+ credential_refs: ["cred_hn"],
+ }),
} as const;
// No dynamic ask text; only a richer, timed pause signal supplies one.
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
index 31583170d..134fd368c 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
@@ -7,6 +7,7 @@ import {
screen,
waitFor,
} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
@@ -41,6 +42,13 @@ const { getClientMock, credsData, credsFail, clientGet } = vi.hoisted(() => {
// can prove the picker's box reaches the server rather than filtering the fetched page.
const get = vi.fn(
(path: string, config?: { params?: { search?: string } }) => {
+ if (path.startsWith("/credentials/")) {
+ if (fail.current) return Promise.reject(new Error("network"));
+ const id = decodeURIComponent(path.slice("/credentials/".length));
+ return Promise.resolve({
+ data: data.current.find((c) => c.credential_id === id),
+ });
+ }
if (path !== "/credentials") return Promise.resolve({ data: {} });
if (fail.current) return Promise.reject(new Error("network"));
const term = config?.params?.search?.toLowerCase();
@@ -1574,3 +1582,97 @@ describe("CredentialCard auto-bound receipt", () => {
expect(onConnect).toHaveBeenCalledWith("cred_other", "Other login");
});
});
+
+describe("CredentialCard missing-authenticator ask", () => {
+ const frame = CREDENTIAL_REQUIRED_FRAME_BY_REASON.credential_missing_totp;
+
+ function renderUpdateAsk(onUpdateCredential = vi.fn(), onSkip = vi.fn()) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <CredentialCard
+ frame={frame}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={onSkip}
+ onUpdateCredential={onUpdateCredential}
+ />
+ </QueryClientProvider>,
+ );
+ }
+
+ it("names the credential and hands its saved record to the editor, with no picker or input", async () => {
+ const onUpdateCredential = vi.fn();
+ const onSkip = vi.fn();
+ const record = {
+ credential_id: "cred_hn",
+ name: "HN login",
+ credential_type: "password",
+ credential: { username: "hn-user" },
+ };
+ credsData.current = [record];
+ const { container } = renderUpdateAsk(onUpdateCredential, onSkip);
+
+ const update = screen.getByRole("button", { name: "Add 2FA method" });
+ expect((update as HTMLButtonElement).disabled).toBe(true);
+ expect(
+ await screen.findByText(
+ "Add 2FA to 'HN login' to sign in to https://news.ycombinator.com",
+ ),
+ ).toBeTruthy();
+ fireEvent.click(update);
+ expect(onUpdateCredential).toHaveBeenCalledWith(record);
+ expect(container.querySelector("input, textarea")).toBeNull();
+ expect(screen.queryByRole("combobox")).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "Connect credential" }),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));
+ expect(onSkip).toHaveBeenCalled();
+ });
+
+ it("does not claim 2FA was added when the editor saves", () => {
+ render(
+ <CredentialCard
+ frame={frame}
+ mode="inline-pause"
+ resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(
+ screen.getByText("Saved 'HN login', retrying the verification step"),
+ ).toBeTruthy();
+ expect(screen.queryByText(/added|updated/)).toBeNull();
+ });
+
+ it("offers Retry and Skip, never the generic picker, when the saved record cannot load", async () => {
+ credsFail.current = true;
+ credsData.current = [{ credential_id: "cred_hn", name: "HN login" }];
+ renderUpdateAsk();
+
+ const retry = await screen.findByRole("button", { name: "Retry" });
+ expect(screen.getByRole("status").textContent).toBe(
+ "Couldn't load this saved login.",
+ );
+ expect(screen.getByRole("button", { name: "Skip for now" })).toBeTruthy();
+ expect(
+ screen.queryByRole("button", { name: "Connect credential" }),
+ ).toBeNull();
+
+ credsFail.current = false;
+ fireEvent.click(retry);
+ await waitFor(() =>
+ expect(
+ (
+ screen.getByRole("button", {
+ name: "Add 2FA method",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false),
+ );
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
index aa71b4623..4b0f64896 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
@@ -23,6 +23,10 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import {
+ isCredentialNotFoundError,
+ useCredentialQuery,
+} from "@/routes/workflows/hooks/useCredentialQuery";
// Union of both a request-policy-time classifier's real reason tokens and a
// mid-build run-failure reason that isn't emitted by any shipped backend
@@ -36,7 +40,8 @@ export type CredentialRequiredReason =
| "raw_secret"
| "credential_deferred_draft"
| "assistant_directed"
- | "missing_credential_run_failure";
+ | "missing_credential_run_failure"
+ | "credential_missing_totp";
export interface CredentialRequiredFrame {
type: "credential_required";
@@ -87,6 +92,8 @@ export interface CredentialCardProps {
// receipt shows it and the resume/continue references it without a lookup.
onConnect: (credentialId?: string, name?: string) => void;
onSkip: () => void;
+ // Opens the credential editor on the saved record a credential_missing_totp ask names.
+ onUpdateCredential?: (credential: CredentialApiResponse) => void;
// Terminal connect auto-sends a "continue" turn; the receipt says so instead
// of the plain "added". Defaults false so inline-pause and every other caller
// keep the existing copy.
@@ -123,6 +130,8 @@ export const CREDENTIAL_WHY_LINE_BY_REASON: Record<
"The last run stopped here because no credential was available — connect one so it can sign in automatically next time.",
credential_deferred_draft:
"You held off on this earlier — connect a credential now so the workflow can sign in when it runs.",
+ credential_missing_totp:
+ "This saved login has no 2FA method, so the workflow can't pass the verification step. Add one in the credential editor — codes never go through chat.",
};
// Mirrors the credentials route: it caps `search` at 200 characters and pages at 100. A longer term
@@ -374,7 +383,175 @@ function CredentialPicker({
);
}
-export function CredentialCard({
+// Read from the page rather than inferred from `mode`: an inline pause restored after a reload
+// renders outside the chat's live region, so the mode alone cannot say whether one surrounds us.
+function useInsideLiveRegion() {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [insideLiveRegion, setInsideLiveRegion] = useState(false);
+ useLayoutEffect(() => {
+ setInsideLiveRegion(
+ Boolean(rootRef.current?.parentElement?.closest(LIVE_REGION_SELECTOR)),
+ );
+ }, []);
+ return [rootRef, insideLiveRegion] as const;
+}
+
+function PauseCountdown({
+ remainingMs,
+ expired,
+}: {
+ remainingMs: number;
+ expired: boolean;
+}) {
+ return (
+ <>
+ <span
+ aria-hidden="true"
+ className="flex-none text-[11px] tabular-nums text-muted-foreground"
+ >
+ {expired ? "Timed out" : formatCountdown(remainingMs)}
+ </span>
+ {/* Separate from the visible per-second display: this text only
+ changes once a minute, so screen readers aren't spammed. */}
+ <span className="sr-only" aria-live="polite">
+ {expired ? "Timed out" : formatCountdownAnnouncement(remainingMs)}
+ </span>
+ </>
+ );
+}
+
+function SkipButton({
+ onSkip,
+ disabled,
+}: {
+ onSkip: () => void;
+ disabled: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label="Skip for now"
+ onClick={() => onSkip()}
+ disabled={disabled}
+ className="flex h-5 w-5 flex-none items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 dark:text-slate-500"
+ >
+ <Cross2Icon className="h-3 w-3" />
+ </button>
+ );
+}
+
+// Asks to fix the one credential already in use, so it offers no picker and no way to add another.
+function CredentialUpdateAsk({
+ frame,
+ credentialId,
+ onUpdateCredential,
+ onSkip,
+}: {
+ frame: CredentialRequiredFrame;
+ credentialId: string;
+ onUpdateCredential?: (credential: CredentialApiResponse) => void;
+ onSkip: () => void;
+}) {
+ const { remainingMs, expired } = useCountdown(frame.expires_at ?? "", true);
+ const [rootRef, insideLiveRegion] = useInsideLiveRegion();
+ const credentialQuery = useCredentialQuery(credentialId, { retry: false });
+ const credential = credentialQuery.data;
+ const site = siteFromLoginPageUrls(frame.login_page_urls);
+ const notFound =
+ credentialQuery.isError && isCredentialNotFoundError(credentialQuery.error);
+ const loadFailure = credentialQuery.isError
+ ? notFound
+ ? "This saved login no longer exists."
+ : "Couldn't load this saved login."
+ : null;
+ const status = credential ? "" : (loadFailure ?? "Loading saved login…");
+
+ return (
+ <div ref={rootRef}>
+ {frame.message ? (
+ <p className="text-sm leading-relaxed text-foreground">
+ {frame.message}
+ </p>
+ ) : null}
+ <div
+ className={`rounded-lg border border-border bg-slate-elevation2 p-3 ${frame.message ? "mt-2" : ""}`}
+ >
+ <div className="flex items-start gap-2">
+ <span className="flex h-5 w-5 flex-none items-center justify-center rounded-md bg-warning/10 text-warning">
+ <LockClosedIcon className="h-3 w-3" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="break-words text-xs font-semibold text-foreground">
+ {credential
+ ? `Add 2FA to '${credential.name}' to sign in to ${site}`
+ : `Add 2FA to your saved login for ${site}`}
+ </div>
+ <p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">
+ {CREDENTIAL_WHY_LINE_BY_REASON.credential_missing_totp}
+ </p>
+ </div>
+ <PauseCountdown remainingMs={remainingMs} expired={expired} />
+ <SkipButton onSkip={onSkip} disabled={expired} />
+ </div>
+ <div className="ml-7 mt-2.5 flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ disabled={expired || !credential || !onUpdateCredential}
+ onClick={() => credential && onUpdateCredential?.(credential)}
+ className="rounded-md bg-cta px-3 py-1 text-xs font-medium text-cta-foreground hover:bg-cta-hover disabled:pointer-events-none disabled:opacity-50"
+ >
+ Add 2FA method
+ </button>
+ {status ? (
+ <span className="text-xs text-muted-foreground">{status}</span>
+ ) : null}
+ {loadFailure && !notFound ? (
+ <button
+ type="button"
+ disabled={expired}
+ onClick={() => void credentialQuery.refetch()}
+ className="rounded-md border border-border px-2 py-1 text-xs font-medium text-foreground hover:bg-accent disabled:pointer-events-none disabled:opacity-50"
+ >
+ Retry
+ </button>
+ ) : null}
+ {/* Mounted for the card's lifetime so only its text changes; inside an outer live region
+ the visible status is already announced. */}
+ <span
+ className="sr-only"
+ role={insideLiveRegion ? undefined : "status"}
+ >
+ {insideLiveRegion ? "" : status}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function CredentialCard(props: Readonly<CredentialCardProps>) {
+ const updateTargetId =
+ props.frame.reason === "credential_missing_totp"
+ ? props.frame.credential_refs?.[0]
+ : undefined;
+ if (
+ updateTargetId &&
+ props.mode === "inline-pause" &&
+ !props.resolvedOutcome
+ ) {
+ return (
+ <CredentialUpdateAsk
+ frame={props.frame}
+ credentialId={updateTargetId}
+ onUpdateCredential={props.onUpdateCredential}
+ onSkip={props.onSkip}
+ />
+ );
+ }
+ return <CredentialAskCard {...props} />;
+}
+
+function CredentialAskCard({
frame,
mode,
resolvedOutcome,
@@ -411,15 +588,7 @@ export function CredentialCard({
// the empty term, and a boolean keyed on a non-empty term reads that failure as no failure, which
// leaves the rows permanently out of step with the box and the picker gone with no way back.
const [failedSearch, setFailedSearch] = useState<string | null>(null);
- // Read from the page rather than inferred from `mode`: an inline pause restored after a reload
- // renders outside the chat's live region, so the mode alone cannot say whether one surrounds us.
- const rootRef = useRef<HTMLDivElement>(null);
- const [insideLiveRegion, setInsideLiveRegion] = useState(false);
- useLayoutEffect(() => {
- setInsideLiveRegion(
- Boolean(rootRef.current?.parentElement?.closest(LIVE_REGION_SELECTOR)),
- );
- }, []);
+ const [rootRef, insideLiveRegion] = useInsideLiveRegion();
const fetchGeneration = useRef(0);
// Any credential ask (terminal or inline-pause) lists every org login credential so the user can
// pick or create. credential_type=password since the card only ever asks for a sign-in; the API
@@ -534,13 +703,16 @@ export function CredentialCard({
return <CredentialSystemRow text={TIMEOUT_COPY} />;
case "connected": {
const name = resolvedOutcome.name;
+ // A save from the editor does not prove 2FA was added; the retried step says whether it was.
const heading = continued
? name
? `Continuing with '${name}'…`
: "Continuing…"
- : name
- ? `Credential '${name}' added`
- : "Credential added";
+ : frame.reason === "credential_missing_totp"
+ ? `Saved ${name ? `'${name}'` : "the credential"}, retrying the verification step`
+ : name
+ ? `Credential '${name}' added`
+ : "Credential added";
return (
<div className="rounded-lg border border-border bg-slate-elevation2 p-3">
<div className="flex items-center gap-2 text-xs font-semibold text-foreground">
@@ -647,7 +819,6 @@ export function CredentialCard({
}
const site = siteFromLoginPageUrls(frame.login_page_urls);
-
return (
<div ref={rootRef}>
{frame.message ? (
@@ -676,31 +847,9 @@ export function CredentialCard({
) : null}
</div>
{countdownActive ? (
- <>
- <span
- aria-hidden="true"
- className="flex-none text-[11px] tabular-nums text-muted-foreground"
- >
- {expired ? "Timed out" : formatCountdown(remainingMs)}
- </span>
- {/* Separate from the visible per-second display: this text only
- changes once a minute, so screen readers aren't spammed. */}
- <span className="sr-only" aria-live="polite">
- {expired
- ? "Timed out"
- : formatCountdownAnnouncement(remainingMs)}
- </span>
- </>
+ <PauseCountdown remainingMs={remainingMs} expired={expired} />
) : null}
- <button
- type="button"
- aria-label="Skip for now"
- onClick={() => onSkip()}
- disabled={disabled}
- className="flex h-5 w-5 flex-none items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 dark:text-slate-500"
- >
- <Cross2Icon className="h-3 w-3" />
- </button>
+ <SkipButton onSkip={onSkip} disabled={disabled} />
</div>
<div className="ml-7 mt-2.5 flex flex-wrap items-center gap-2">
<button
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.ts
index 84865c091..0d65e30b1 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.credentialPause.test.ts
@@ -65,6 +65,12 @@ describe("parseCredentialPause", () => {
});
});
+ it("keeps an answered card visible when its credential was not admitted", () => {
+ expect(
+ parseCredentialPause({ outcome: "not_admitted", credentialId: "c1" }),
+ ).toEqual({ outcome: "skipped", credentialId: null });
+ });
+
it("rejects unknown or malformed outcomes so the renderer can't crash", () => {
expect(parseCredentialPause(null)).toBeNull();
expect(parseCredentialPause({ outcome: "exploded" })).toBeNull();
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index db909e649..9efd41dc6 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -516,6 +516,10 @@ export function parseCredentialPause(
if (!value || typeof value !== "object") return null;
const o = value as Record<string, unknown>;
const outcome = o.outcome;
+ // The user answered but nothing was bound, which the card already renders as a skip.
+ if (outcome === "not_admitted") {
+ return { outcome: "skipped", credentialId: null };
+ }
if (
outcome !== "connected" &&
outcome !== "skipped" &&
@@ -681,6 +685,7 @@ const ACTIVITY_TOOL_DISPLAY_LABELS: Record<string, string> = {
discover_workflow_entrypoint: "Finding the entry page",
inspect_page_for_composition: "Inspecting the page",
list_credentials: "Checking saved credentials",
+ get_organization_usage_quota: "Checking account usage",
fill_credential_field: "Entering saved credentials",
edit_block: "Editing block",
add_block: "Adding block",
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index d2586b5d7..2b423bd59 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -197,6 +197,7 @@ import {
import { useStudioShellContext } from "../studio/StudioShellContext";
import { StudioShellPanelPortal } from "../studio/StudioShellPanelPortal";
import { useRecordingLauncherStore } from "@/store/useRecordingLauncherStore";
+import type { CopilotAttachedFile } from "@/routes/workflows/copilot/workflowCopilotTypes";
import { useSopToBlocksMutation } from "../hooks/useSopToBlocksMutation";
import {
applySopResultAtCurrentAppend,
@@ -222,6 +223,20 @@ import {
} from "./workflowVersionFromSaveData";
import "./workspace-styles.css";
+function readCopilotAttachedFiles(
+ value: unknown,
+): Array<CopilotAttachedFile> | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const files = value.filter(
+ (item): item is CopilotAttachedFile =>
+ typeof item === "object" &&
+ item !== null &&
+ typeof (item as CopilotAttachedFile).file_id === "string" &&
+ typeof (item as CopilotAttachedFile).filename === "string",
+ );
+ return files.length > 0 ? files : undefined;
+}
+
function readCopilotProductAction(value: unknown): CopilotProductAction | null {
if (!value || typeof value !== "object") {
return null;
@@ -419,8 +434,13 @@ function Workspace({
const [searchParams] = useSearchParams();
const locationState = location.state as {
copilotMessage?: unknown;
+ copilotAttachedFiles?: unknown;
copilotAction?: unknown;
} | null;
+ const routeInitialCopilotAttachments = useMemo(
+ () => readCopilotAttachedFiles(locationState?.copilotAttachedFiles),
+ [locationState?.copilotAttachedFiles],
+ );
const routeInitialCopilotMessage =
typeof locationState?.copilotMessage === "string"
? locationState.copilotMessage
@@ -1516,6 +1536,28 @@ function Workspace({
},
[authoringActionAvailability.canUploadSOP, sopToBlocksMutation],
);
+ // `/discover`'s "Record task" lands here with ?record=1; start once the browser is ready.
+ const [, setRecordSearchParams] = useSearchParams();
+ const autoRecordRequested = searchParams.get("record") === "1";
+ useEffect(() => {
+ if (!autoRecordRequested || !authoringActionAvailability.canRecordTask) {
+ return;
+ }
+ startRecordingAtEnd();
+ setRecordSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete("record");
+ return next;
+ },
+ { replace: true },
+ );
+ }, [
+ autoRecordRequested,
+ authoringActionAvailability.canRecordTask,
+ startRecordingAtEnd,
+ setRecordSearchParams,
+ ]);
useEffect(() => {
if (!embedded) {
return;
@@ -3004,6 +3046,7 @@ function Workspace({
requiresLiveBrowser={copilotRequiresLiveBrowser}
isLiveBrowserReady={copilotLiveBrowserReady}
initialMessage={initialCopilotMessage ?? undefined}
+ initialAttachments={routeInitialCopilotAttachments}
initialAction={initialCopilotAction ?? undefined}
onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
onUploadSOP={uploadSOPAtEnd}
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.test.ts b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.test.ts
index aa1d72226..9fdb4b5a1 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.test.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.test.ts
@@ -300,6 +300,35 @@ describe("describeCodeBlockFailure", () => {
});
});
+ test("a machinery failure inside Skyvern is never the block's own raise", () => {
+ for (const exception of ["KeyError", "TimeoutError"]) {
+ const failure = describeCodeBlockFailure(
+ block({
+ failure_reason: `CodeBlock failed with ${exception} inside Skyvern while running line 3.`,
+ }),
+ );
+ expect(failure).toMatchObject({
+ kind: "infrastructure",
+ code: null,
+ line: 3,
+ recovery: "retry",
+ });
+ expect(failure?.title).not.toContain("raised");
+ }
+ });
+
+ test("a user exception whose message mimics the machinery wording stays a user-code failure", () => {
+ const failure = describeCodeBlockFailure(
+ block({
+ failure_reason:
+ "Failed to execute code block. Reason: ValueError: failed inside Skyvern while running line 999",
+ actions: [failedAction(3)],
+ }),
+ );
+ expect(failure).toMatchObject({ kind: "user-code", code: null, line: 3 });
+ expect(failure?.recovery).not.toBe("retry");
+ });
+
test("falls back to the failing action's line when the reason has none", () => {
expect(
describeCodeBlockFailure(
@@ -416,7 +445,7 @@ describe("failureSupportsScreenshot", () => {
});
describe("guard denials under unsupported_page_operation", () => {
- // All four guards report the same error code, so the code alone cannot pick the remedy.
+ // All five guards report the same error code, so the code alone cannot pick the remedy.
// The regression these guard against: telling someone who exhausted the per-run operation
// budget, or who navigated somewhere refused, to "use a supported page method" instead.
const denial = (exceptionClass: string | null): FailedBlock =>
@@ -447,6 +476,20 @@ describe("guard denials under unsupported_page_operation", () => {
expect(egress?.guidance).toMatch(/url|destination/i);
});
+ test("a handle-table breach is told apart from the operation quota", () => {
+ const handles = describeCodeBlockFailure(
+ denial("codeblock.page_operation_broker.HandleLimitExceeded"),
+ );
+ const quota = describeCodeBlockFailure(
+ denial("codeblock.page_operation_broker.PageOperationLimitExceeded"),
+ );
+
+ expect(handles?.kind).toBe("limit");
+ expect(handles?.title).not.toBe(quota?.title);
+ expect(handles?.guidance).not.toMatch(/supported page method/i);
+ expect(handles?.guidance).toMatch(/browser (elements|objects)|handles/i);
+ });
+
test("an unrecognised or absent class still falls back to the generic denial", () => {
for (const value of [
null,
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts
index e4d593ae4..169d4bcb7 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/codeBlockFailure.ts
@@ -234,6 +234,14 @@ const REASON_ONLY_FAILURES: Array<{
recovery: "retry",
},
},
+ // The inline engine's "CodeBlock failed with X inside Skyvern" is block machinery
+ // failing around the user's code, so the named exception is not one their code raised.
+ // Anchored: a user exception message can contain the same words.
+ {
+ pattern:
+ /^CodeBlock failed(?: with [A-Za-z_][A-Za-z0-9_]*)? inside Skyvern\b/,
+ template: INFRASTRUCTURE,
+ },
];
const EXCEPTION_NAME_PATTERNS = [
@@ -252,7 +260,10 @@ function exceptionName(reason: string): string | null {
}
function lineFromReason(reason: string): number | null {
- const match = reason.match(/\bat line (\d+)\b/);
+ const match =
+ reason.match(
+ /^CodeBlock failed(?: with [A-Za-z_][A-Za-z0-9_]*)? inside Skyvern while running line (\d+)\b/,
+ ) ?? reason.match(/\bat line (\d+)\b/);
if (!match?.[1]) {
return null;
}
@@ -284,7 +295,7 @@ export function failingCodeLineFromActions(
return failingAction ? actionCodeLine(failingAction) : null;
}
-// unsupported_page_operation is one error code for four different guards, so the code alone
+// unsupported_page_operation is one error code for five different guards, so the code alone
// cannot pick a remedy. codeblock/workflow.py puts the runner-authored class name on the failure
// output for exactly this; the names come from SAFE_DENIED_OPERATION_EXCEPTION_CLASSES, which
// allowlists them as carrying no page or parameter data.
@@ -296,6 +307,13 @@ const DENIAL_TEMPLATES: Record<string, CodeBlockFailureTemplate> = {
"This block issued more browser operations in a single run than the per-run limit allows. Split the work across several runs, or narrow what each run processes.",
recovery: "fix",
},
+ "codeblock.page_operation_broker.HandleLimitExceeded": {
+ kind: "limit",
+ title: "The block held too many browser objects",
+ guidance:
+ "This block used more live browser objects in a single run than the per-run limit allows. Every query_selector or element_handle result, .all() on a filtered, get_by_* or frame-rooted locator, and each locator passed as an argument holds one object for the rest of the run. Read rows through page.locator(...), .nth() and .all() chains instead, which hold none, or split the work across several runs.",
+ recovery: "fix",
+ },
"codeblock.page_operation_broker.BlockedEgressError": {
kind: "browser",
title: "The block navigated to a blocked destination",
diff --git a/skyvern-frontend/src/store/SidebarStore.ts b/skyvern-frontend/src/store/SidebarStore.ts
index eacf5b01c..6e0dc6e8f 100644
--- a/skyvern-frontend/src/store/SidebarStore.ts
+++ b/skyvern-frontend/src/store/SidebarStore.ts
@@ -45,4 +45,4 @@ const useSidebarStore = create<SidebarStore>((set) => {
};
});
-export { useSidebarStore };
+export { SIDEBAR_COLLAPSED_STORAGE_KEY, useSidebarStore };
diff --git a/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx b/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx
index a8f0079e9..9dba0afb9 100644
--- a/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx
+++ b/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx
@@ -1,5 +1,7 @@
// @vitest-environment jsdom
import { useState } from "react";
+import { AxiosHeaders } from "axios";
+import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
import {
act,
cleanup,
@@ -18,20 +20,21 @@ import type {
QuestionnaireStateV1,
} from "./types";
-const { mockGet, mockPost, mockAuth } = vi.hoisted(() => ({
+const { mockGet, mockPost, mockAuth, mockRequestClient } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockPost: vi.fn(),
- mockAuth: { userId: "user-a" },
+ mockAuth: { userId: "user-a", orgId: null as string | null },
+ mockRequestClient: vi.fn(),
}));
vi.mock("@clerk/clerk-react", () => ({
- useAuth: () => ({ isSignedIn: true, userId: mockAuth.userId }),
+ useAuth: () => ({ isSignedIn: true, ...mockAuth }),
}));
vi.mock("@/hooks/useCredentialGetter", () => ({
useCredentialGetter: () => () => Promise.resolve("test-token"),
}));
vi.mock("@/api/AxiosClient", () => ({
- getClient: () => Promise.resolve({ get: mockGet, post: mockPost }),
+ getClientWithRequestHeaders: mockRequestClient,
}));
vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
OnboardingTelemetry: {
@@ -168,6 +171,9 @@ function Consumer({ prefix = "" }: Readonly<{ prefix?: string }>) {
<span data-testid={`${prefix}revision`}>
{state?.questionnaire?.revision ?? 0}
</span>
+ <span data-testid={`${prefix}owner`}>
+ {state?.questionnaire?.project_owner?.professional_email ?? "none"}
+ </span>
<span data-testid={`${prefix}prompted`}>
{String(state?.questionnaire_prompted_at)}
</span>
@@ -273,6 +279,10 @@ function renderProviderPair() {
}
beforeEach(() => {
+ mockRequestClient.mockImplementation(async () => ({
+ client: { get: mockGet, post: mockPost },
+ headers: new AxiosHeaders({ "X-API-Key": "stale-key" }),
+ }));
FakeBroadcastChannel.channels = [];
vi.stubGlobal("BroadcastChannel", FakeBroadcastChannel);
});
@@ -283,9 +293,90 @@ afterEach(() => {
vi.unstubAllGlobals();
FakeBroadcastChannel.channels = [];
mockAuth.userId = "user-a";
+ mockAuth.orgId = null;
});
describe("OnboardingProvider writes", () => {
+ it.each(["query", "mutation"])(
+ "ignores an old organization's late %s response",
+ async (kind) => {
+ mockAuth.orgId = "org_a";
+ const oldResponse = deferred<{ data: OnboardingStateResponse }>();
+ const withOwner = response({
+ questionnaire: {
+ ...questionnaire(),
+ project_owner: {
+ version: 1,
+ organization_id: "o_a",
+ reported_by_user_id: "user-a",
+ source: "signup_user_reported",
+ verification: "unverified",
+ contact_permission: "not_granted",
+ professional_email: "[email protected]",
+ reported_at: "2026-09-19T00:00:00Z",
+ updated_at: "2026-09-19T00:00:00Z",
+ },
+ },
+ });
+ mockGet.mockResolvedValue({ data: response() });
+ if (kind === "query") mockGet.mockReturnValueOnce(oldResponse.promise);
+ else mockPost.mockReturnValueOnce(oldResponse.promise);
+ const { rerenderProvider, queryClient } = renderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
+ expect(mockGet.mock.calls[0]?.[1].headers.get("X-API-Key")).toBeNull();
+ if (kind === "mutation") {
+ fireEvent.click(screen.getByText("confirm"));
+ await waitFor(() => expect(mockPost).toHaveBeenCalledOnce());
+ }
+ mockAuth.orgId = "org_b";
+ rerenderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(2));
+ await act(async () => oldResponse.resolve({ data: withOwner }));
+ await waitFor(() => expect(queryClient.isMutating()).toBe(0));
+ expect(OnboardingTelemetry.error).not.toHaveBeenCalled();
+ expect(screen.getByTestId("owner").textContent).toBe("none");
+ expect(
+ queryClient.getQueryData(["userOnboarding", "user-a", "org_a"]),
+ ).toBeUndefined();
+ mockAuth.orgId = null;
+ rerenderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(3));
+ expect(screen.getByTestId("owner").textContent).toBe("none");
+ },
+ );
+
+ it.each(["confirm", "dismiss"])(
+ "drops queued and credential-waiting writes after an org switch: %s",
+ async (action) => {
+ mockAuth.orgId = "org_a";
+ mockGet.mockResolvedValue({ data: response() });
+ const { rerenderProvider, queryClient } = renderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
+ const credentials = deferred<{
+ client: { get: typeof mockGet; post: typeof mockPost };
+ headers: AxiosHeaders;
+ }>();
+ mockRequestClient.mockReturnValueOnce(credentials.promise);
+ fireEvent.click(screen.getByText(action));
+ await waitFor(() => expect(mockRequestClient).toHaveBeenCalledTimes(2));
+ fireEvent.click(screen.getByText(action));
+ mockAuth.orgId = "org_b";
+ rerenderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(2));
+ mockAuth.orgId = "org_a";
+ rerenderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(3));
+ await act(async () =>
+ credentials.resolve({
+ client: { get: mockGet, post: mockPost },
+ headers: new AxiosHeaders(),
+ }),
+ );
+ await waitFor(() => expect(queryClient.isMutating()).toBe(0));
+ expect(mockPost).not.toHaveBeenCalled();
+ expect(OnboardingTelemetry.error).not.toHaveBeenCalled();
+ },
+ );
it("keeps confirmed POST success when the background refetch fails", async () => {
const confirmed = response({ questionnaire: questionnaire() });
mockGet
@@ -300,6 +391,8 @@ describe("OnboardingProvider writes", () => {
await waitFor(() =>
expect(screen.getByTestId("confirmed").textContent).toBe("saved"),
);
+ expect(mockPost.mock.calls[0]?.[1]).toEqual({ questionnaire: COMPLETE });
+ expect(mockPost.mock.calls[0]?.[2].headers.get("X-API-Key")).toBeNull();
expect(screen.getByTestId("revision").textContent).toBe("1");
});
@@ -356,6 +449,9 @@ describe("OnboardingProvider writes", () => {
]),
);
expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT);
+ expect(OnboardingTelemetry.error).toHaveBeenCalledExactlyOnceWith(
+ "dashboard",
+ );
});
it("lets a later successful field value supersede an older failure", async () => {
@@ -452,6 +548,9 @@ describe("OnboardingProvider writes", () => {
await waitFor(() =>
expect(screen.getByTestId("confirmed").textContent).toBe("thrown"),
);
+ expect(OnboardingTelemetry.error).toHaveBeenCalledExactlyOnceWith(
+ "dashboard",
+ );
});
it("isolates B's failed overlay while A settles after the switch", async () => {
@@ -491,8 +590,9 @@ describe("OnboardingProvider writes", () => {
queryClient.getQueryData<OnboardingStateResponse>([
"userOnboarding",
"user-a",
+ null,
])?.onboarding_state.modal_dismissed_at,
- ).toBeNull();
+ ).toBeUndefined();
aWrite.resolve({ data: response({ seen_canvas: true }) });
await waitFor(() => expect(mockPost).toHaveBeenCalledTimes(2));
await act(invalidate);
diff --git a/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx b/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx
index 70c1f254b..574fcc76c 100644
--- a/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx
+++ b/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx
@@ -1,8 +1,13 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { isAxiosError } from "axios";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ CancelledError,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
import { useAuth } from "@clerk/clerk-react";
-import { getClient } from "@/api/AxiosClient";
+import { getClientWithRequestHeaders } from "@/api/AxiosClient";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { OnboardingContext } from "./useOnboardingState";
import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
@@ -66,8 +71,19 @@ type LegacyWrite = {
type LegacyMutationContext = {
legacyWriteVersion: number;
- userId: string | null | undefined;
- queryKey: readonly ["userOnboarding", string | null | undefined];
+ generation: number;
+ queryKey: OnboardingQueryKey;
+};
+
+type OnboardingQueryKey = readonly [
+ "userOnboarding",
+ string | null | undefined,
+ string | null,
+];
+type ScopedWrite<Patch> = {
+ patch: Patch;
+ generation: number;
+ queryKey: OnboardingQueryKey;
};
function legacyFieldsToReplay(
@@ -106,36 +122,65 @@ type Props = {
function OnboardingProvider({ children }: Readonly<Props>) {
const credentialGetter = useCredentialGetter();
- const { isSignedIn, userId } = useAuth();
+ const { isSignedIn, userId, orgId } = useAuth();
const queryClient = useQueryClient();
const queryKey = useMemo(
- (): readonly ["userOnboarding", typeof userId] => [
- "userOnboarding",
- userId,
- ],
- [userId],
+ (): OnboardingQueryKey => ["userOnboarding", userId, orgId ?? null],
+ [userId, orgId],
);
const legacyWriteVersionRef = useRef(0);
const legacyWritesRef = useRef<LegacyWrite[]>([]);
- const previousUserIdRef = useRef<string | null | undefined>(undefined);
+ const currentScopeRef = useRef({ queryKey, generation: 0 });
const conflictRefetchPendingRef = useRef(false);
const channelRef = useRef<BroadcastChannel | null>(null);
-
- if (previousUserIdRef.current !== userId) {
+ const activeRef = useRef(true);
+ if (currentScopeRef.current.queryKey !== queryKey) {
legacyWritesRef.current = [];
legacyWriteVersionRef.current = 0;
- previousUserIdRef.current = userId;
+ conflictRefetchPendingRef.current = false;
+ currentScopeRef.current = {
+ queryKey,
+ generation: currentScopeRef.current.generation + 1,
+ };
}
+ const generation = currentScopeRef.current.generation;
+ const isCurrent = useCallback(
+ (value: number) =>
+ activeRef.current && currentScopeRef.current.generation === value,
+ [],
+ );
+ useEffect(() => {
+ activeRef.current = true;
+ return () => {
+ activeRef.current = false;
+ };
+ }, []);
+ useEffect(
+ () => () => {
+ queryClient.removeQueries({ queryKey, exact: true });
+ },
+ [queryClient, queryKey],
+ );
+ const requestClient = useCallback(
+ async (writeGeneration: number) => {
+ if (!isCurrent(writeGeneration)) throw new CancelledError();
+ const request = await getClientWithRequestHeaders(credentialGetter);
+ if (!isCurrent(writeGeneration)) throw new CancelledError();
+ // A stale global API key must not override the bearer's organization.
+ request.headers.set("X-API-Key", null);
+ return request;
+ },
+ [credentialGetter, isCurrent],
+ );
const { data, isLoading } = useQuery<OnboardingStateResponse>({
queryKey,
queryFn: async () => {
- const client = await getClient(credentialGetter);
+ const { client, headers } = await requestClient(generation);
const response = await client.get<OnboardingStateResponse>(
"/users/me/onboarding",
+ { headers },
);
- if (previousUserIdRef.current !== userId) {
- return response.data;
- }
+ if (!isCurrent(generation)) throw new CancelledError();
const legacyFields = legacyFieldsToReplay(
legacyWritesRef.current,
legacyWriteVersionRef.current + 1,
@@ -176,26 +221,36 @@ function OnboardingProvider({ children }: Readonly<Props>) {
}, [queryClient, queryKey, userId]);
const writeState = useCallback(
- async (patch: ConfirmedPatch) => {
- const client = await getClient(credentialGetter);
+ async ({
+ patch,
+ generation: writeGeneration,
+ }: ScopedWrite<ConfirmedPatch>) => {
+ const { client, headers } = await requestClient(writeGeneration);
const response = await client.post<OnboardingStateResponse>(
"/users/me/onboarding",
patch,
+ { headers },
);
+ if (!isCurrent(writeGeneration)) throw new CancelledError();
return response.data;
},
- [credentialGetter],
+ [requestClient, isCurrent],
);
const legacyMutation = useMutation<
OnboardingStateResponse,
unknown,
- LegacyOnboardingStatePatch,
+ ScopedWrite<LegacyOnboardingStatePatch>,
LegacyMutationContext
>({
scope: MUTATION_SCOPE,
mutationFn: writeState,
- onMutate: async (patch) => {
+ onMutate: async ({
+ patch,
+ generation: writeGeneration,
+ queryKey: writeKey,
+ }) => {
+ if (!isCurrent(writeGeneration)) throw new CancelledError();
const legacyWriteVersion = legacyWriteVersionRef.current + 1;
legacyWriteVersionRef.current = legacyWriteVersion;
legacyWritesRef.current.push({
@@ -204,20 +259,27 @@ function OnboardingProvider({ children }: Readonly<Props>) {
status: "pending",
});
if (!conflictRefetchPendingRef.current) {
- await queryClient.cancelQueries({ queryKey: queryKey });
+ await queryClient.cancelQueries({ queryKey: writeKey });
}
+ if (!isCurrent(writeGeneration)) throw new CancelledError();
const previous =
- queryClient.getQueryData<OnboardingStateResponse>(queryKey);
+ queryClient.getQueryData<OnboardingStateResponse>(writeKey);
if (previous) {
- queryClient.setQueryData<OnboardingStateResponse>(queryKey, {
+ queryClient.setQueryData<OnboardingStateResponse>(writeKey, {
...previous,
onboarding_state: { ...previous.onboarding_state, ...patch },
});
}
- return { legacyWriteVersion, userId, queryKey };
+ return {
+ legacyWriteVersion,
+ generation: writeGeneration,
+ queryKey: writeKey,
+ };
},
- onError: (_error, _patch, context) => {
- if (context && context.userId === previousUserIdRef.current) {
+ onError: (error, write, context) => {
+ if (!isCurrent(write.generation) || error instanceof CancelledError)
+ return;
+ if (context && isCurrent(context.generation)) {
const write = legacyWritesRef.current.find(
({ version }) => version === context.legacyWriteVersion,
);
@@ -226,14 +288,13 @@ function OnboardingProvider({ children }: Readonly<Props>) {
OnboardingTelemetry.error("dashboard");
},
onSuccess: async (_nextState, _patch, context) => {
- if (context.userId === previousUserIdRef.current) {
- const write = legacyWritesRef.current.find(
- ({ version }) => version === context.legacyWriteVersion,
- );
- if (write) write.status = "succeeded";
- }
+ if (!isCurrent(context.generation)) return;
+ const write = legacyWritesRef.current.find(
+ ({ version }) => version === context.legacyWriteVersion,
+ );
+ if (write) write.status = "succeeded";
await queryClient.invalidateQueries({ queryKey: context.queryKey });
- if (context.userId !== previousUserIdRef.current) return;
+ if (!isCurrent(context.generation)) return;
const newerFields = legacyFieldsToReplay(
legacyWritesRef.current,
context.legacyWriteVersion,
@@ -252,30 +313,41 @@ function OnboardingProvider({ children }: Readonly<Props>) {
const confirmedMutation = useMutation<
OnboardingStateResponse,
unknown,
- ConfirmedPatch
+ ScopedWrite<ConfirmedPatch>
>({
scope: MUTATION_SCOPE,
- mutationFn: async (patch) => {
+ mutationFn: async (write) => {
try {
- return await writeState(patch);
+ return await writeState(write);
} catch (error) {
+ if (!isCurrent(write.generation)) throw new CancelledError();
if (!isAxiosError(error) || error.response?.status !== 409) throw error;
conflictRefetchPendingRef.current = true;
await queryClient
- .invalidateQueries({ queryKey: queryKey }, { throwOnError: true })
- .finally(() => (conflictRefetchPendingRef.current = false));
+ .invalidateQueries(
+ { queryKey: write.queryKey },
+ { throwOnError: true },
+ )
+ .finally(() => {
+ if (isCurrent(write.generation)) {
+ conflictRefetchPendingRef.current = false;
+ }
+ });
throw error;
}
},
- onMutate: async () => {
+ onMutate: async (write) => {
+ if (!isCurrent(write.generation)) throw new CancelledError();
if (!conflictRefetchPendingRef.current) {
- await queryClient.cancelQueries({ queryKey: queryKey });
+ await queryClient.cancelQueries({ queryKey: write.queryKey });
}
},
- onSuccess: (nextState) => {
+ onSuccess: (nextState, write) => {
+ if (!isCurrent(write.generation)) return;
if (isAuthoritativeConfirmedResponse(nextState)) {
- queryClient.setQueryData<OnboardingStateResponse>(queryKey, (current) =>
- mergeConfirmedResponse(current, nextState),
+ queryClient.setQueryData<OnboardingStateResponse>(
+ write.queryKey,
+ (current) => mergeConfirmedResponse(current, nextState),
);
const promptedAt = nextState.onboarding_state.questionnaire_prompted_at;
if (typeof userId === "string" && promptedAt) {
@@ -290,9 +362,13 @@ function OnboardingProvider({ children }: Readonly<Props>) {
}
}
}
- void queryClient.invalidateQueries({ queryKey });
+ void queryClient.invalidateQueries({ queryKey: write.queryKey });
+ },
+ onError: (error, write) => {
+ if (!isCurrent(write.generation) || error instanceof CancelledError)
+ return;
+ OnboardingTelemetry.error("dashboard");
},
- onError: () => OnboardingTelemetry.error("dashboard"),
});
const isNewUser =
@@ -323,14 +399,18 @@ function OnboardingProvider({ children }: Readonly<Props>) {
const updateState = useCallback(
(patch: LegacyOnboardingStatePatch) => {
- legacyMutation.mutate(patch);
+ legacyMutation.mutate({ patch, generation, queryKey });
},
- [legacyMutation],
+ [legacyMutation, generation, queryKey],
);
const updateStateConfirmed = useCallback(
async (patch: ConfirmedPatch): Promise<ConfirmedWriteResult> => {
try {
- return await confirmedMutation.mutateAsync(patch);
+ return await confirmedMutation.mutateAsync({
+ patch,
+ generation,
+ queryKey,
+ });
} catch (error) {
if (isAxiosError<{ detail?: string }>(error)) {
const status = error.response?.status;
@@ -341,11 +421,19 @@ function OnboardingProvider({ children }: Readonly<Props>) {
case "questionnaire_requires_user_intent":
case "questionnaire_update_requires_response":
case "questionnaire_invalid_transition":
+ case "project_owner_organization_conflict":
return { code: detail };
default:
return { code: "unknown" };
}
}
+ if (
+ status === 422 &&
+ patch.questionnaire &&
+ "project_owner" in patch.questionnaire
+ ) {
+ return { code: "project_owner_invalid" };
+ }
if (
status === 403 &&
detail === "onboarding_questionnaire_disabled"
@@ -356,7 +444,7 @@ function OnboardingProvider({ children }: Readonly<Props>) {
throw error;
}
},
- [confirmedMutation],
+ [confirmedMutation, generation, queryKey],
);
return (
diff --git a/skyvern-frontend/src/store/onboarding/types.ts b/skyvern-frontend/src/store/onboarding/types.ts
index 052a63279..795d8c1d6 100644
--- a/skyvern-frontend/src/store/onboarding/types.ts
+++ b/skyvern-frontend/src/store/onboarding/types.ts
@@ -68,6 +68,7 @@ export type QuestionnairePatchV1 =
mutation_id: string;
expected_revision: number;
action: "complete" | "update";
+ project_owner?: ProjectOwnerPatchV1;
} & QuestionnaireAnswersV1)
| {
version: 1;
@@ -84,6 +85,27 @@ export type QuestionnairePromptResultV1 =
export type QuestionnaireStatusV1 = "completed" | "skipped" | "deferred";
+export type ProjectOwnerFieldsV1 = {
+ name?: string | null;
+ professional_email?: string | null;
+ role?: string | null;
+};
+
+export type ProjectOwnerPatchV1 =
+ | ({ action: "set"; expected_organization_id: string } & ProjectOwnerFieldsV1)
+ | { action: "clear"; expected_organization_id: string };
+
+export type ProjectOwnerReportV1 = ProjectOwnerFieldsV1 & {
+ version: 1;
+ organization_id: string;
+ reported_by_user_id: string;
+ source: "signup_user_reported";
+ verification: "unverified";
+ contact_permission: "not_granted";
+ reported_at: string;
+ updated_at: string;
+};
+
export type QuestionnaireStateV1 = {
version: 1;
response_id: string;
@@ -99,6 +121,7 @@ export type QuestionnaireStateV1 = {
deferred_at: string | null;
updated_at: string;
defer_prompt_count: 0 | 1;
+ project_owner?: ProjectOwnerReportV1 | null;
};
export type OnboardingState = {
@@ -129,6 +152,7 @@ export type RecoveryGuidanceAssignment = {
export type OnboardingStateResponse = {
onboarding_state: OnboardingState;
+ project_owner_supported?: boolean;
launch_date_at_signup: string | null;
recovery_guidance_assignment: RecoveryGuidanceAssignment | null;
questionnaire_prompt_result?: QuestionnairePromptResultV1 | null;
@@ -136,6 +160,8 @@ export type OnboardingStateResponse = {
};
export type ConfirmedWriteCode =
+ | "project_owner_organization_conflict"
+ | "project_owner_invalid"
| "questionnaire_revision_conflict"
| "questionnaire_requires_user_intent"
| "questionnaire_update_requires_response"
diff --git a/skyvern-frontend/src/util/homeTelemetry.ts b/skyvern-frontend/src/util/homeTelemetry.ts
new file mode 100644
index 000000000..907313fff
--- /dev/null
+++ b/skyvern-frontend/src/util/homeTelemetry.ts
@@ -0,0 +1,40 @@
+import posthog, { type Properties } from "posthog-js";
+
+type Variant = "legacy" | "revamp";
+
+function capture(event: string, properties: Properties = {}): void {
+ try {
+ posthog.capture(`home.${event}`, properties);
+ } catch {
+ // PostHog may be unavailable in tests or before init.
+ }
+}
+
+export const HomeTelemetry = {
+ viewed: (variant: Variant) => capture("viewed", { variant }),
+ promptSubmitted: (input: {
+ source: "typed" | "example";
+ example?: string;
+ promptLength: number;
+ handoff: boolean;
+ }) => capture("prompt_submitted", input),
+ exampleClicked: (input: { capability?: string; label: string }) =>
+ capture("example_clicked", input),
+ examplePreviewShown: (input: { capability: string; label: string }) =>
+ capture("example_preview_shown", input),
+ howItWorksToggled: (open: boolean) =>
+ capture("how_it_works_toggled", { open }),
+ addMenuOpened: () => capture("add_menu_opened"),
+ uploadDocumentSelected: () => capture("upload_document_selected"),
+ uploadDocumentFinished: (ok: boolean) =>
+ capture("upload_document_finished", { ok }),
+ recordTaskSelected: () => capture("record_task_selected"),
+ voiceToggled: () => capture("voice_toggled"),
+ // Legacy home only
+ skipToBlankCanvasClicked: () => capture("skip_blank_canvas_clicked"),
+ templateClicked: (input: { workflowPermanentId: string; title: string }) =>
+ capture("template_clicked", input),
+ advancedSettingsToggled: (open: boolean) =>
+ capture("advanced_settings_toggled", { open }),
+ improvePromptUsed: () => capture("improve_prompt_used"),
+} as const;
diff --git a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts
index f68c0d232..845eeae56 100644
--- a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts
+++ b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts
@@ -156,6 +156,10 @@ describe("OnboardingTelemetry", () => {
...answers,
organization_id: "org_123",
step_id: "onboarding_questionnaire_completed:v1",
+ project_owner_reported: false,
+ project_owner_name_present: false,
+ project_owner_email_present: false,
+ project_owner_role_present: false,
},
);
expect(posthog.capture).toHaveBeenNthCalledWith(
@@ -187,10 +191,83 @@ describe("OnboardingTelemetry", () => {
...answers,
organization_id: "org_123",
step_id: "onboarding_questionnaire_updated:v1",
+ project_owner_reported: false,
+ project_owner_name_present: false,
+ project_owner_email_present: false,
+ project_owner_role_present: false,
},
);
expect(JSON.stringify(vi.mocked(posthog.capture).mock.calls)).not.toContain(
customDedupeProperty,
);
});
+
+ it("projects only current-org presence and never owner PII", () => {
+ const input = {
+ responseId: "response",
+ revision: 2,
+ primaryIntent: "fill_forms" as const,
+ organizationId: "o_a",
+ previousStatus: "completed" as const,
+ answers: {
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+ } as const,
+ projectOwner: {
+ version: 1,
+ organization_id: "o_a",
+ reported_by_user_id: "user_a",
+ source: "signup_user_reported",
+ verification: "unverified",
+ contact_permission: "not_granted",
+ name: "Synthetic Owner",
+ professional_email: "[email protected]",
+ role: "Synthetic sponsor role",
+ reported_at: "2026-09-19T00:00:00Z",
+ updated_at: "2026-09-19T00:00:00Z",
+ } as const,
+ };
+ OnboardingTelemetry.questionnaireCompleted(input);
+ OnboardingTelemetry.questionnaireUpdated(input);
+ for (const [, properties] of vi.mocked(posthog.capture).mock.calls) {
+ expect(properties).toEqual(
+ expect.objectContaining({
+ organization_id: "o_a",
+ project_owner_reported: true,
+ project_owner_name_present: true,
+ project_owner_email_present: true,
+ project_owner_role_present: true,
+ project_owner_source: "signup_user_reported",
+ }),
+ );
+ }
+ OnboardingTelemetry.questionnaireUpdated({
+ ...input,
+ organizationId: "o_b",
+ });
+ expect(posthog.capture).toHaveBeenLastCalledWith(
+ "onboarding_questionnaire_updated",
+ expect.objectContaining({
+ organization_id: "o_b",
+ project_owner_reported: false,
+ project_owner_email_present: false,
+ }),
+ );
+ const sent = JSON.stringify(vi.mocked(posthog.capture).mock.calls);
+ for (const value of [
+ input.projectOwner.name,
+ input.projectOwner.professional_email,
+ input.projectOwner.role,
+ ]) {
+ expect(sent).not.toContain(value);
+ }
+ vi.mocked(posthog.capture).mockImplementationOnce(() => {
+ throw new Error("offline");
+ });
+ expect(() =>
+ OnboardingTelemetry.questionnaireCompleted(input),
+ ).not.toThrow();
+ });
});
diff --git a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts
index 549462a21..1cb8e1149 100644
--- a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts
+++ b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts
@@ -3,6 +3,7 @@ import type {
QuestionnaireAnswersV1,
QuestionnaireStatusV1,
QuestionnaireUserIntentV1,
+ ProjectOwnerReportV1,
} from "@/store/onboarding/types";
type Surface =
@@ -24,11 +25,13 @@ type QuestionnaireShownInput = {
type QuestionnaireResponseInput = {
responseId: string;
revision: number;
+ organizationId?: string | null;
};
type QuestionnaireAnswerInput = QuestionnaireResponseInput & {
primaryIntent: QuestionnaireUserIntentV1;
answers: QuestionnaireAnswersV1;
+ projectOwner?: ProjectOwnerReportV1 | null;
};
type QuestionnaireSkippedInput = QuestionnaireResponseInput & {
@@ -165,6 +168,7 @@ function questionnaireResponseProperties(input: QuestionnaireResponseInput) {
surface: "get_started_modal",
response_id: input.responseId,
revision: input.revision,
+ ...(input.organizationId ? { organization_id: input.organizationId } : {}),
};
}
@@ -188,11 +192,26 @@ function questionnaireShown(input: QuestionnaireShownInput): boolean {
});
}
+function projectOwnerProperties(input: QuestionnaireAnswerInput) {
+ const owner =
+ input.projectOwner?.organization_id === input.organizationId
+ ? input.projectOwner
+ : null;
+ return {
+ project_owner_reported: !!owner,
+ project_owner_name_present: !!owner?.name,
+ project_owner_email_present: !!owner?.professional_email,
+ project_owner_role_present: !!owner?.role,
+ ...(owner ? { project_owner_source: "signup_user_reported" } : {}),
+ };
+}
+
function questionnaireCompleted(input: QuestionnaireAnswerInput): void {
capture("onboarding_questionnaire_completed", {
...questionnaireResponseProperties(input),
primary_intent: input.primaryIntent,
...questionnaireAnswerProperties(input.answers),
+ ...projectOwnerProperties(input),
});
}
@@ -210,6 +229,7 @@ function questionnaireUpdated(input: QuestionnaireUpdatedInput): void {
primary_intent: input.primaryIntent,
previous_status: input.previousStatus,
...questionnaireAnswerProperties(input.answers),
+ ...projectOwnerProperties(input),
});
}
diff --git a/skyvern/cli/mcp_tools/blocks.py b/skyvern/cli/mcp_tools/blocks.py
index 56d9e164e..99519ca8f 100644
--- a/skyvern/cli/mcp_tools/blocks.py
+++ b/skyvern/cli/mcp_tools/blocks.py
@@ -340,7 +340,7 @@ BLOCK_EXAMPLES: dict[str, dict[str, Any]] = {
"range": "A1",
"credential_id": "{{ google_credential_id }}",
"write_mode": "append",
- "values": "{{ output_data | tojson }}",
+ "values": "[[{{ extract_metric.output.metric | tojson }}]]",
},
}
@@ -380,6 +380,7 @@ WORKFLOW_KNOWLEDGE_TOPIC_HEADERS: dict[str, str] = {
"proxy_location": "** PROXY LOCATION AND BROWSER PROFILE (proxy_location) **",
"text_prompt_block": "** TEXT PROMPT BLOCK (text_prompt) **",
"http_request_block": "** HTTP REQUEST BLOCK (http_request) **",
+ "google_sheets_write_block": "** GOOGLE SHEETS WRITE BLOCK (google_sheets_write) **",
"parameter_templating": "** PARAMETER TEMPLATING **",
"error_handling_and_retries": "** ERROR HANDLING AND RETRIES **",
"workflow_execution_flow": "** WORKFLOW EXECUTION FLOW **",
diff --git a/skyvern/config.py b/skyvern/config.py
index 9de093ac6..141be8e9f 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -566,6 +566,10 @@ class Settings(BaseSettings):
# executes only in the sandboxed runner and is withheld whenever that runner is unavailable --
# there is no in-process execution path to fall back to.
TASK_V3_CODE_TOOL_SURFACE: Literal["off", "add", "replace"] = "off"
+ # How long the Task V3 navigate tool waits for the committed document's domcontentloaded and then
+ # load events. Carved OUT OF BROWSER_LOADING_TIMEOUT_MS, never added to it -- the commit attempt
+ # gets the remainder, so one navigate call's worst case stays at that total.
+ TASK_V3_NAVIGATE_READINESS_TIMEOUT_MS: int = 20000
# Workflows whose permanent id was born at or after this instant run their task blocks on Task V3
# when the organization resolves to the self-serve billing tier (an unknown tier is not enrolled),
# bypassing WORKFLOW_TASK_V3_AB. None disables the rule (the OSS default). Setting it is not
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index f8c630b60..88aefdc94 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -95,6 +95,7 @@ from skyvern.forge.sdk.api.files import (
get_path_for_workflow_download_directory,
list_downloading_files_in_directory,
list_files_in_directory,
+ normalize_download_identity,
recover_download_extension,
rename_file,
resolve_run_download_id,
@@ -218,6 +219,7 @@ from skyvern.utils.prompt_engine import (
from skyvern.utils.prompt_truncation import truncate_extraction_schema, truncate_page_html_for_summary
from skyvern.utils.secret_redaction import (
clears_numeric_secret_floor,
+ collect_redactable_secret_values,
redact_console_log_bytes,
redact_har_bytes,
redact_secrets_from_text,
@@ -286,6 +288,10 @@ RECOVERABLE_BLANK_WORKFLOW_TASK_URLS = {":"}
# any successful step-body scrape.
EMPTY_PAGE_RECOVERY_MAX_ATTEMPTS = 3
+# Poll cadence for the read-only claimed-dead-blank settlement observation (mirrors the 1s cadence of
+# the download-finished waiter). The observation is bounded by the reservation's remaining grace.
+_CLAIMED_DOWNLOAD_GRACE_POLL_SECONDS = 1.0
+
EXTRACT_ACTION_TEMPLATE = "extract-action"
DECISIVE_CRITERION_VALIDATE_TEMPLATE = "decisive-criterion-validate"
@@ -435,6 +441,25 @@ def _taskv3_row_intention(
return None
+def _taskv3_row_secret_values(workflow_run_id: str | None) -> set[str]:
+ """What a persisted v3 action row scrubs.
+
+ The one-time code the run typed is deliberately absent: it is a record the customer has to be
+ able to read back off the row, and only the seed that mints codes is a secret. A model-hidden
+ runtime value (a magic sign-in link) stays in -- a signed URL is a secret whatever minted it, and
+ ``exclude_runtime_otp`` drops the whole task-scoped set that holds both.
+ """
+ secret_values = (
+ set(app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run(workflow_run_id, exclude_runtime_otp=True))
+ if app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled(workflow_run_id)
+ else set()
+ )
+ current_context = skyvern_context.current()
+ if current_context is None or not settings.ENABLE_SECRET_ARTIFACT_REDACTION:
+ return secret_values
+ return secret_values | collect_redactable_secret_values({}, otp_values=list(current_context.model_hidden_values))
+
+
def _redact_tool_args(args: dict[str, Any], secret_values: set[str]) -> dict[str, Any]:
if not secret_values:
return args
@@ -1381,30 +1406,29 @@ class ForgeAgent:
return files_to_rename
async def _close_claimed_download_popups(
- self, task: Task, browser_state: BrowserState | None, claims: list[Page]
+ self,
+ task: Task,
+ browser_state: BrowserState | None,
+ claims: list[Page],
+ late_candidates: list[Page] | None = None,
) -> None:
- """Bounded best-effort close of exactly the given recorded download-popup claims.
-
- A file-download click that opens a new page is expected to have that page closed once the
- download finishes, regardless of its URL/commit/scrape state. On dynamic/remote-CDP runs the
- download is carried by the CDP monitor and credited by the file-scan task lifecycle after the
- action seam has returned, so no Playwright popup download event fires and the in-seam cleanup
- never sees it — the popup lingers and the next task can select it as the working page, wedging
- on screenshot/scrape/reload. Called only once a download is durably credited, this closes each
- recorded popup that is still open and still belongs to the run's current BrowserContext.
- Cleanup liveness is structural ownership, not scraper validity, so it is NOT gated on the
- scraper-oriented ``list_valid_pages()`` (which omits PDF-viewer/odd-scheme pages and would
- strand a genuinely live wedged popup). A stale-context/foreign-context page, an already-closed
- page, or a close failure never closes an unrelated page and never overturns the durable credit;
- the opener (never recorded as a claim) is never touched.
+ """Close exact owned pages in the current BrowserContext after durable download credit.
+
+ Action claims and context-listener candidates share one deadline and close regardless of URL,
+ commit state, content, or scraper visibility.
"""
- if not claims:
+ owned_pages = list(claims)
+ for candidate in late_candidates or []:
+ if all(candidate is not owned for owned in owned_pages):
+ owned_pages.append(candidate)
+ if not owned_pages:
return
+ total = len(owned_pages)
if browser_state is None:
LOG.info(
"Skipping credited download popup close: no browser state",
task_id=task.task_id,
- claims_taken=len(claims),
+ claims_taken=total,
skip_reason="no_browser_state",
)
return
@@ -1417,7 +1441,7 @@ class ForgeAgent:
LOG.info(
"Skipping credited download popup close: browser context unavailable",
task_id=task.task_id,
- claims_taken=len(claims),
+ claims_taken=total,
skip_reason="context_unavailable",
)
return
@@ -1430,7 +1454,7 @@ class ForgeAgent:
# cannot delay the credited-task handoff by N x BROWSER_PAGE_CLOSE_TIMEOUT: each attempted close
# gets only the remaining budget, and once it is exhausted the rest are consumed without a close.
batch_deadline = time.monotonic() + BROWSER_PAGE_CLOSE_TIMEOUT
- for popup in claims:
+ for popup in owned_pages:
try:
if popup.is_closed():
skipped_already_closed += 1
@@ -1457,7 +1481,7 @@ class ForgeAgent:
LOG.info(
"Closed credited download popups",
task_id=task.task_id,
- claims_taken=len(claims),
+ claims_taken=total,
closed=closed,
close_failed=close_failed,
skipped_already_closed=skipped_already_closed,
@@ -1472,7 +1496,8 @@ class ForgeAgent:
if context is None:
return
claims = context.take_download_popup_claims(task.task_id)
- await self._close_claimed_download_popups(task, browser_state, claims)
+ late_candidates = context.take_download_popup_late_candidates(task.task_id)
+ await self._close_claimed_download_popups(task, browser_state, claims, late_candidates)
async def _wait_for_in_flight_downloads(
self,
@@ -2265,13 +2290,7 @@ class ForgeAgent:
)
except Exception:
LOG.warning("task_v3 failed to capture post-action screenshot", task_id=task.task_id, exc_info=True)
- # Opted-out runs still floor runtime-resolved secrets (e.g. verification codes),
- # matching the recording/HAR finalization sites.
- secret_values = (
- app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run(task.workflow_run_id)
- if app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled(task.workflow_run_id)
- else app.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts()
- )
+ secret_values = _taskv3_row_secret_values(task.workflow_run_id)
if turn_reasoning:
if secret_values:
# Default (substring) matching: turn text is free-form prose, where a long secret
@@ -3243,6 +3262,8 @@ class ForgeAgent:
engine=engine,
cua_response=cua_response,
llm_caller=llm_caller,
+ attempt_started_at=attempt_started_at,
+ list_files_before=list_files_before,
)
await app.AGENT_FUNCTION.post_step_execution(task, step)
task = await self.update_task_errors_from_detailed_output(task, detailed_output) # type: ignore
@@ -3298,6 +3319,14 @@ class ForgeAgent:
)
return last_step, detailed_output, None
+ # No durable credit at this step's complete-on-download seam: release a
+ # dispatched-then-failed action's deferred reservations now, before the retry scrape,
+ # so generic blank-page recovery becomes eligible again. A no-op when nothing was
+ # deferred or when credit already consumed the registries.
+ release_context = skyvern_context.current()
+ if release_context is not None:
+ release_context.apply_pending_download_reservation_release(task.task_id)
+
# If the step failed, mark the step as failed and retry
if step.status == StepStatus.failed:
maybe_next_step = await self.handle_failed_step(organization, task, step)
@@ -3918,6 +3947,8 @@ class ForgeAgent:
complete_verification: bool = True,
cua_response: OpenAIResponse | None = None,
llm_caller: LLMCaller | None = None,
+ attempt_started_at: datetime | None = None,
+ list_files_before: list[str] | None = None,
) -> tuple[Step, DetailedAgentStepOutput]:
# task_id, step_id, workflow_run_id, organization_id overlap with auto-
# attached context attrs from @traced. Kept because the Task/Step objects
@@ -4020,9 +4051,28 @@ class ForgeAgent:
# The working page is a dead blank after the scrape ladder. If a survivor exists,
# recover by injecting a single ClosePageAction (no LLM); otherwise re-raise so
# the existing terminal handler fails the task exactly as on main.
- recovery_actions = await self._empty_page_recovery_plan(task, step, browser_state)
+ recovery_actions = await self._empty_page_recovery_plan(
+ task,
+ step,
+ browser_state,
+ task_block=task_block,
+ attempt_started_at=attempt_started_at,
+ list_files_before=list_files_before,
+ )
if recovery_actions is None:
raise
+ if recovery_actions == []:
+ # A credited complete-on-download recovery: the download settled within its
+ # bounded grace. execute_step's single complete-on-download seam owns the one
+ # finalize + task completion, so return a completed (never failed) step here
+ # instead of tripping the zero-action failed-step path below.
+ detailed_agent_step_output.actions = []
+ step = await self.update_step(
+ step=step,
+ status=StepStatus.completed,
+ output=detailed_agent_step_output.to_agent_step_output(),
+ )
+ return step, detailed_agent_step_output
injected_actions = recovery_actions
scraped_page = ScrapedPage(
elements=[],
@@ -6285,29 +6335,243 @@ class ForgeAgent:
allow_transient_ui_suppression=True,
)
+ async def _observe_claimed_download_within_grace(
+ self,
+ task: Task,
+ task_block: BaseTaskBlock | None,
+ *,
+ remaining: float,
+ list_files_before: list[str],
+ attempt_started_at: datetime | None,
+ observe_session: bool = True,
+ allow_new_file_credit: bool = True,
+ ) -> bool:
+ """Read-only bounded observation of real download file state for a claimed dead-blank page.
+
+ Returns True as soon as a NEW final (completed) file appears since the pre-step baseline within
+ the remaining budget -- covering a download that lands directly as a final file (no
+ ``.crdownload``), one that settles from an in-flight ``.crdownload``, and one that lands only in
+ persistent browser-session storage. The local run dir and browser-session storage are unioned to
+ mirror the authoritative credit seam. Reuses the existing cancellable in-flight waiter for the
+ partial case. Never renames/finalizes (the single authoritative finalize stays at the
+ complete-on-download credit seam) and never polls the claim. Returns False when the budget
+ elapses with nothing credited.
+
+ ``observe_session`` gates the browser-session union: a claim whose baseline was NOT built with a
+ session listing (the v4 false-click path, which must not do remote listings) passes False, so a
+ session-only file cannot be miscredited to it -- there is no session reference to tell a genuinely
+ new file from one an earlier action already produced.
+
+ ``allow_new_file_credit`` False suppresses the new-completed-file early return (a same-action
+ sibling delta popup in a non-complete block: a new file cannot be attributed to it over a
+ sibling). The bounded in-flight settle still runs so the page's OWN download can complete, but the
+ observer waits its full grace and returns False rather than closing early on a sibling's file.
+ """
+ context = skyvern_context.current()
+ if context is None:
+ return False
+ # A workflow-less standalone task keys its download dir by task_id; resolve exactly as the
+ # authoritative credit seam does (``workflow_run_id or task_id``) so such a task is still observed.
+ download_id = resolve_run_download_id(context, fallback_run_id=task.workflow_run_id or task.task_id)
+ if not download_id:
+ return False
+ download_dir = get_path_for_workflow_download_directory(download_id)
+ # Normalize the baseline so an earlier download still in-flight at claim time (``<final>.crdownload``
+ # or the interceptor's ``<final>.<32-hex>.crdownload``) collapses to its settled ``<final>`` identity;
+ # otherwise it would read as a brand-new arrival once it settles during the grace and miscredit this
+ # page. Same normalization the v4 false-click path uses.
+ baseline = {normalize_download_identity(path) for path in list_files_before}
+
+ async def _bounded_session_read(lister: Callable[..., Awaitable[list[str]]]) -> list[str]:
+ # Bound every remote session read by the remaining per-Page grace: a stalled storage call must
+ # never hold the step past the download deadline. An exhausted budget skips the read entirely
+ # (no unbounded read even on the pre-deadline first pass); a read that overruns OR fails yields
+ # no observation -- an empty result, so the bounded wait, expiry, exact-claim release, and
+ # recovery still happen (never credit, never release early; the loop's deadline check owns
+ # expiry). A listing error must not escape to the caller's broad catch and re-raise the blank
+ # failure. CancelledError (BaseException) is not caught and always propagates.
+ budget = deadline - time.monotonic()
+ if budget <= 0:
+ return []
+ try:
+ return await asyncio.wait_for(
+ lister(organization_id=task.organization_id, browser_session_id=task.browser_session_id),
+ timeout=budget,
+ )
+ except Exception:
+ return []
+
+ async def _new_final_file_present() -> bool:
+ files = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
+ if observe_session and task.browser_session_id:
+ # A persistent-session download can land ONLY in session storage; mirror the credit
+ # seam's local+session union so it is not missed through the grace. Only for claims whose
+ # baseline was session-aware (never the local-only v4 false-click claim).
+ files = files + await _bounded_session_read(app.STORAGE.list_downloaded_files_in_browser_session)
+ return any(
+ Path(path).suffix != BROWSER_DOWNLOADING_SUFFIX and normalize_download_identity(path) not in baseline
+ for path in files
+ )
+
+ async def _in_flight_present() -> bool:
+ if list_downloading_files_in_directory(download_dir, attempt_started_at=attempt_started_at):
+ return True
+ if observe_session and task.browser_session_id:
+ return bool(await _bounded_session_read(app.STORAGE.list_downloading_files_in_browser_session))
+ return False
+
+ deadline = time.monotonic() + max(0.0, remaining)
+ while True:
+ if allow_new_file_credit and await _new_final_file_present():
+ return True
+ now = time.monotonic()
+ if now >= deadline:
+ return False
+ if task_block is not None and await _in_flight_present():
+ # An in-flight download (local .crdownload or a browser-session partial) exists: reuse the
+ # cancellable settle machinery, then re-check for the file. The whole nested call is bounded
+ # by the remaining per-Page grace -- not just its internal wait -- because its own
+ # browser-session listing runs BEFORE that internal cap, so a stalled remote read there
+ # could otherwise hold the step past the deadline. A legitimate settle that fits inside the
+ # budget still returns before this bound fires (never truncated); a bound hit is treated as
+ # no settle. The nested waiter also does its OWN session listing, so contain any ordinary
+ # error from it (not just the timeout) as no settle for this iteration -- otherwise it would
+ # escape to the caller's broad catch and re-raise the blank failure instead of observing to
+ # expiry and releasing the claim. No credit, no early release; CancelledError still propagates.
+ budget = deadline - time.monotonic()
+ if budget > 0:
+ try:
+ await asyncio.wait_for(
+ self._wait_for_in_flight_downloads(
+ task,
+ task_block,
+ task.organization_id,
+ timeout_cap=budget,
+ attempt_started_at=attempt_started_at,
+ ),
+ timeout=budget,
+ )
+ except Exception:
+ pass
+ if allow_new_file_credit and await _new_final_file_present():
+ return True
+ # A .crdownload may be abandoned with no final file; keep observing until the budget.
+ await asyncio.sleep(min(_CLAIMED_DOWNLOAD_GRACE_POLL_SECONDS, max(0.0, deadline - time.monotonic())))
+
async def _empty_page_recovery_plan(
- self, task: Task, step: Step, browser_state: BrowserState
+ self,
+ task: Task,
+ step: Step,
+ browser_state: BrowserState,
+ task_block: BaseTaskBlock | None = None,
+ attempt_started_at: datetime | None = None,
+ list_files_before: list[str] | None = None,
) -> list[Action] | None:
"""Fail-closed eligibility for dead-blank recovery.
Returns a single internal-recovery ClosePageAction when the current working page is a dead
- blank, holds no download-popup claim, a usable http/https survivor exists, and the per-task
- attempt cap is not reached. Any uncertainty (or exception) returns None so the caller
- re-raises the original blank exception and reproduces main's terminal behavior exactly.
+ blank, a usable http/https survivor exists, and the per-task attempt cap is not reached. Any
+ uncertainty (or exception) returns None so the caller re-raises the original blank exception and
+ reproduces main's terminal behavior exactly.
+
+ A dead blank that still holds a download-popup claim is not vetoed forever: it is given a
+ bounded chance (its own remaining budget from reservation creation) for the download to settle,
+ observed via real file state. On credit in a complete-on-download block, returns ``[]`` so the
+ single authoritative credit seam finalizes and completes the task; otherwise (grace elapsed with
+ no credit, or a non-complete-on-download block) the exact page is released from both reservation
+ registries and recovery proceeds.
"""
try:
context = skyvern_context.current()
page = await browser_state.get_working_page()
if context is None or page is None or not page_is_dead_blank(page):
return None
- if context.has_download_popup_claim(task.task_id, page):
- return None
+ had_claim = context.has_download_popup_claim(task.task_id, page)
+ if had_claim:
+ grace = (
+ (task_block.download_timeout if task_block is not None else None)
+ or task.download_timeout
+ or BROWSER_DOWNLOAD_TIMEOUT
+ )
+ # Anchor the recovery-observation grace to THIS first eligible observation (first-wins per
+ # exact Page), not to claim creation: the handler's own post-click wait already spent its
+ # separate budget, so a silent/late final file still gets ~one full grace here. Re-entry or
+ # cancellation reuses the same anchor (never restarts it); siblings are independent; a later
+ # recovery call consumes the remaining budget.
+ now = time.monotonic()
+ context.anchor_download_popup_recovery_grace(task.task_id, page, now)
+ remaining = context.remaining_download_popup_grace(task.task_id, page, grace, now)
+ if remaining is None:
+ remaining = grace # defensive; the anchor above guarantees a value
+ # Observe against THIS exact page's own baseline (files present when its claim was created)
+ # unioned with the block baseline, so a file that landed for an earlier action/sibling
+ # before this page's claim is never miscredited to it. Falls back to the block baseline
+ # when no page snapshot was anchored.
+ page_baseline = context.download_popup_claim_baseline_for(task.task_id, page)
+ observation_baseline = list(list_files_before or [])
+ if page_baseline is not None:
+ observation_baseline = list({*observation_baseline, *page_baseline})
+ # Union the augmented session baseline (every session observation across re-records): the
+ # event-recorded popup anchored a stale pre-action session snapshot, but the action-finally
+ # resnapshot augmented it, so an earlier action's session file that settled before this
+ # popup's mint is baselined out rather than miscredited as new.
+ session_page_baseline = context.download_popup_claim_session_baseline_for(task.task_id, page)
+ if session_page_baseline is not None:
+ observation_baseline = list({*observation_baseline, *session_page_baseline})
+ # Only union session files into the observation for a claim whose baseline was built with a
+ # session listing. A v4 false-click claim (local-only baseline, no remote listing) would
+ # otherwise see an earlier action's session-only file as new and be miscredited.
+ observe_session = context.download_popup_claim_session_was_observed(task.task_id, page)
+ complete_on_download = bool(
+ task_block is not None and task_block.complete_on_download and task.workflow_run_id
+ )
+ # A same-action sibling delta popup owns no file unambiguously: outside the complete seam
+ # (where the first download completes the task by design), do not early-credit-and-close it
+ # on a new file that could be a sibling's -- wait its full grace so its own in-flight
+ # download can settle first, rather than cancelling it. A lone popup keeps the fast credit.
+ allow_new_file_credit = complete_on_download or not context.download_popup_claim_has_delta_siblings(
+ task.task_id, page
+ )
+ credited = await self._observe_claimed_download_within_grace(
+ task,
+ task_block,
+ remaining=remaining,
+ list_files_before=observation_baseline,
+ attempt_started_at=attempt_started_at,
+ observe_session=observe_session,
+ allow_new_file_credit=allow_new_file_credit,
+ )
+ if credited and complete_on_download:
+ # Zero actions: agent_step persists a completed step and execute_step's
+ # complete-on-download seam performs the single finalize -> closes the exact claimed
+ # popups and completes the task. No recovery attempt is consumed.
+ return []
+ # No credit (or a non-complete-on-download block): the download had its full bounded
+ # budget. The grace wait is a TOCTOU window, so revalidate BEFORE any mutation that the
+ # SAME exact Page is still the working dead blank and still owns the claim (it may have
+ # been adopted/replaced/credited while waiting). Fail closed with the claim intact
+ # otherwise -- a premature release would strand a late download with no claim for terminal
+ # cleanup to settle. The exact claim is released only once recovery is committed, below.
+ revalidated = await browser_state.get_working_page()
+ if (
+ revalidated is not page
+ or not page_is_dead_blank(page)
+ or not context.has_download_popup_claim(task.task_id, page)
+ ):
+ return None
+ # Recovery eligibility is checked in full BEFORE releasing the exact claim: no survivor or an
+ # exhausted attempt cap returns None with all claim / late-candidate / baseline / anchor
+ # ownership intact, so terminal cleanup can still settle a late download under the original claim.
pages = await browser_state.list_valid_pages(max_pages=0)
if not any(p is not page and page_is_http_survivor(p) for p in pages):
return None
attempts = context.empty_page_recovery_attempts.get(task.task_id, 0)
if attempts >= EMPTY_PAGE_RECOVERY_MAX_ATTEMPTS:
return None
+ # Eligibility confirmed -> now release ONLY this exact Page's claim (never a sibling) and
+ # commit the recovery attempt.
+ if had_claim:
+ context.release_download_popup_claim(task.task_id, page)
context.empty_page_recovery_attempts[task.task_id] = attempts + 1
context.empty_page_recovery_step_id = step.step_id
# A pending reload must not substitute for the close inside the action loop.
@@ -7544,6 +7808,35 @@ class ForgeAgent:
browser_session_id: str | None = None,
download_suffix: str | None = None,
list_files_before: list[str] | None = None,
+ ) -> None:
+ context = skyvern_context.current()
+ try:
+ await self._clean_up_task(
+ task,
+ last_step,
+ api_key=api_key,
+ need_call_webhook=need_call_webhook,
+ close_browser_on_completion=close_browser_on_completion,
+ need_final_screenshot=need_final_screenshot,
+ browser_session_id=browser_session_id,
+ download_suffix=download_suffix,
+ list_files_before=list_files_before,
+ )
+ finally:
+ if context is not None:
+ context.clear_download_popup_claims(task.task_id)
+
+ async def _clean_up_task(
+ self,
+ task: Task,
+ last_step: Step,
+ api_key: str | None = None,
+ need_call_webhook: bool = True,
+ close_browser_on_completion: bool = True,
+ need_final_screenshot: bool = True,
+ browser_session_id: str | None = None,
+ download_suffix: str | None = None,
+ list_files_before: list[str] | None = None,
) -> None:
"""
send the task response to the webhook callback url
@@ -7552,26 +7845,22 @@ class ForgeAgent:
if cleanup_context is not None:
cleanup_context.clear_multi_field_totp_state(task.task_id)
- # Task-terminal expiry for download-popup claims: clean_up_task runs exactly when a task
- # reaches a terminal state (and not on retries, where the same task's next step may still
- # credit the download). Take (and drop) the claims into a local now, so terminal expiry holds
- # even if the DB refresh or later cleanup raises; if cleanup's own download finalization proves
- # a durable credit below, these held claims get the same bounded popup close as the
- # complete_on_download seam, otherwise they simply expire. (That seam already popped its own
- # claims, so this is empty on the completed-download path.)
+ # Keep any still-current capture window alive through settle/finalize; only durable credit
+ # permits closing reservations. The outer finally releases ownership on every terminal exit.
_claim_context = skyvern_context.current()
- cleanup_download_popup_claims = (
- _claim_context.take_download_popup_claims(task.task_id) if _claim_context is not None else []
- )
- if cleanup_download_popup_claims:
- # These reach terminal cleanup only when the complete_on_download seam did not already pop
- # them (e.g. a failed/terminated task); they close below iff cleanup finalization proves a
- # durable credit, otherwise they expire here without a destructive close.
- LOG.info(
- "Download popup claims carried into terminal cleanup",
- task_id=task.task_id,
- claims_carried=len(cleanup_download_popup_claims),
+ _download_popup_state_taken = False
+
+ def _take_download_popup_state() -> tuple[list[Page], list[Page]]:
+ """Exactly-once: detach the task listener and pop this task's strong claims + late candidates."""
+ nonlocal _download_popup_state_taken
+ if _download_popup_state_taken or _claim_context is None:
+ return [], []
+ _download_popup_state_taken = True
+ return (
+ _claim_context.take_download_popup_claims(task.task_id),
+ _claim_context.take_download_popup_late_candidates(task.task_id),
)
+
_cleanup_span = otel_trace.get_current_span()
# task_id, workflow_run_id auto-attached by @traced from SkyvernContext.
_cleanup_span.set_attribute("close_browser_on_completion", bool(close_browser_on_completion))
@@ -7590,6 +7879,8 @@ class ForgeAgent:
"Failed to get task from db when clean up task",
task_id=task.task_id,
)
+ # Terminal-expiry: a DB-refresh failure must not leave the task listener/claim state armed.
+ _take_download_popup_state()
raise TaskNotFound(task_id=task.task_id) from e
task = refreshed_task
@@ -7608,18 +7899,21 @@ class ForgeAgent:
# since the browser is not initialized properly or the proxy is not working.
browser_state = app.BROWSER_MANAGER.get_for_task(task.task_id)
- if browser_state is not None and await browser_state.get_working_page() is not None:
+ if browser_state is not None:
+ # get_working_page() is inside the try so a raise here cannot propagate and strand the
+ # task listener/claim state armed (terminal-expiry promise).
try:
- try:
- screenshot = await browser_state.take_fullpage_screenshot()
- except TimeoutError as e:
- # Same capture-deadline conversion as record_artifacts_after_action; the write stays at error.
- raise SkyvernPageAnalysisTimeout("Timed out taking the final screenshot") from e
- await app.ARTIFACT_MANAGER.create_artifact(
- step=last_step,
- artifact_type=ArtifactType.SCREENSHOT_FINAL,
- data=screenshot,
- )
+ if await browser_state.get_working_page() is not None:
+ try:
+ screenshot = await browser_state.take_fullpage_screenshot()
+ except TimeoutError as e:
+ # Same capture-deadline conversion as record_artifacts_after_action; the write stays at error.
+ raise SkyvernPageAnalysisTimeout("Timed out taking the final screenshot") from e
+ await app.ARTIFACT_MANAGER.create_artifact(
+ step=last_step,
+ artifact_type=ArtifactType.SCREENSHOT_FINAL,
+ data=screenshot,
+ )
except (TargetClosedError, ScreenshotTargetClosed):
LOG.warning(
"Failed to take screenshot before sending task response, page is closed",
@@ -7662,12 +7956,17 @@ class ForgeAgent:
randomize_if_missing=False,
attempt_started_at=attempt_started_at,
)
- # Cleanup finalization is the second durable-credit seam: only when it
- # proves a new file did the download land, so only then close the popups the
- # download action opened (using the claims taken at cleanup entry).
+ # Cleanup finalization is the second durable-credit seam: only when it proves a new
+ # file did the download land, so only then take the claims/late-candidates (now that
+ # any marker joining during settle/finalize has been recorded by the still-armed
+ # listener) and close the popups the download action opened.
if cleanup_finalized_files:
+ cleanup_claims, cleanup_late_candidates = _take_download_popup_state()
await self._close_claimed_download_popups(
- task, browser_state, cleanup_download_popup_claims
+ task,
+ browser_state,
+ cleanup_claims,
+ cleanup_late_candidates,
)
try:
await app.STORAGE.save_downloaded_files(
@@ -7747,6 +8046,11 @@ class ForgeAgent:
workflow_run_id=task.workflow_run_id,
)
finally:
+ # Terminal-expiry for the download-popup lifecycle: after settle/finalize (even on a
+ # timeout/exception caught above, or the no-credit path), detach the listener and expire
+ # the claims/candidates exactly once. The credited close above already took them, so this
+ # is a no-op there; on every other path it expires without a destructive close.
+ _take_download_popup_state()
if track_download_outcome:
record_download_artifact_outcome_for_context(
browser_context,
@@ -7769,6 +8073,10 @@ class ForgeAgent:
workflow_run_id=task.workflow_run_id,
)
+ # Terminal-expiry backstop for the org-less path (the credited/finally take above runs only inside the
+ # `if task.organization_id:` block): detach the listener and expire any claims/candidates. Idempotent.
+ _take_download_popup_state()
+
# Reaching this line means the download half has had its run: the save is wrapped in its own
# try that swallows TimeoutError and Exception. Marked here rather than on entry because the
# task refresh above raises TaskNotFound before the download half ever starts, and marking on
@@ -9593,6 +9901,11 @@ class ForgeAgent:
# always open a new tab to navigate to the magic link
page = await browser_state.new_page()
context = skyvern_context.ensure_context()
+ # This tab is deliberately created and stays blank until the returned GotoUrlAction navigates it later.
+ # The context.on("page") owner records it the instant new_page() joins the context, so retire it from
+ # both download-popup registries now -- before add_magic_link_page, returning, or the later navigation --
+ # so a delayed download credit cannot close the intentional magic-link tab. Idempotent.
+ context.retire_intentional_page(task.task_id, page)
context.add_magic_link_page(task.task_id, page)
return [
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index ba4de4576..f67ce3706 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -96,7 +96,10 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
from skyvern.forge.sdk.schemas.totp_codes import OTPType
from skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultService
- from skyvern.forge.sdk.workflow.code_block_authorized_files import AuthorizedFileMaterialization
+ from skyvern.forge.sdk.workflow.code_block_authorized_files import (
+ AuthorizedFileMaterialization,
+ BlockDownloadLog,
+ )
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
from skyvern.forge.sdk.workflow.models.block import DownloadEvidenceProbe
from skyvern.forge.sdk.workflow.models.code_block_recorder import RecordingPage
@@ -230,6 +233,23 @@ class CopilotEntrypointCandidate:
association: CopilotSiteOriginAssociation
+@dataclass(frozen=True)
+class CopilotOrganizationUsage:
+ """A null field is one the deployment or account does not record; ``credits_note`` says why
+ when nothing is recorded at all."""
+
+ plan_tier: str | None = None
+ current_period_start: str | None = None
+ current_period_end: str | None = None
+ included_credits: int | None = None
+ consumed_credits: int | None = None
+ remaining_credits: int | None = None
+ topup_credits_remaining: int | None = None
+ overage_enabled: bool | None = None
+ credits_note: str | None = None
+ billing_page_path: str | None = None
+
+
@dataclass(frozen=True)
class FieldOptionResolution:
matched_index: int | None
@@ -1303,6 +1323,7 @@ class AgentFunction:
download_run_id: str | None = None,
download_binding: DownloadBinding | None = None,
download_evidence: DownloadEvidenceProbe | None = None,
+ download_log: BlockDownloadLog | None = None,
) -> CodeBlockEngineResult | None:
"""Run a CodeBlock through the secure runner, or return None for legacy.
@@ -1342,6 +1363,15 @@ class AgentFunction:
"Browser code is not available on this deployment.", error_code="unavailable"
)
+ async def get_organization_usage_quota(
+ self,
+ *,
+ organization_id: str,
+ ) -> CopilotOrganizationUsage:
+ """OSS keeps no billing records; cloud overrides this with the authenticated read."""
+ del organization_id
+ return CopilotOrganizationUsage(credits_note="This deployment does not track billing.")
+
def resolve_copilot_dispatch_trigger_type(self) -> WorkflowRunTriggerType | None:
"""Base no-op (no dispatch routing hint); overridden per deployment."""
return None
@@ -2092,9 +2122,15 @@ class AgentFunction:
or credential_cache_age is None
or credential_cache_age >= EMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS
):
+ # Marked before the await so a cancelled refresh is not mistaken for a
+ # completed one; CancelledError bypasses the handler below.
+ source_context.credential_list_refresh_failed = True
try:
source_context.credential_ids = await source.list_credential_ids(organization_id)
source_context.credential_ids_loaded_at = now
+ source_context.credential_list_refresh_failed = False
+ source_context.failed_credential_ids &= set(source_context.credential_ids)
+ source_context.completed_credential_ids &= set(source_context.credential_ids)
except Exception:
LOG.warning("Failed to list email OTP credentials", source=source.name, exc_info=True)
continue
@@ -2118,6 +2154,7 @@ class AgentFunction:
client=client,
)
except EmailOTPSearchError as exc:
+ source_context.failed_credential_ids.add(credential_id)
LOG.warning(
"Email OTP lookup failed",
source=source.name,
@@ -2127,6 +2164,7 @@ class AgentFunction:
)
continue
except Exception:
+ source_context.failed_credential_ids.add(credential_id)
LOG.warning(
"Unexpected email OTP lookup failure",
source=source.name,
@@ -2135,9 +2173,14 @@ class AgentFunction:
)
continue
+ source_context.failed_credential_ids.discard(credential_id)
+ source_context.completed_credential_ids.add(credential_id)
for candidate in candidates:
if source_context.has_seen_message(credential_id, candidate.message_id):
continue
+ # Marked before the await so a wait cancelled mid-parse still shows the
+ # message reached the parser; CancelledError bypasses the handler below.
+ source_context.unreadable_message_keys.add((credential_id, candidate.message_id))
try:
otp_value = await parse_otp_login(
candidate.content,
@@ -2145,6 +2188,7 @@ class AgentFunction:
enforced_otp_type=expected_otp_type,
)
except InsufficientCreditsForOTPParse:
+ source_context.unreadable_message_keys.discard((credential_id, candidate.message_id))
source_context.remember_message(credential_id, candidate.message_id)
return None
except Exception:
@@ -2156,6 +2200,7 @@ class AgentFunction:
exc_info=True,
)
continue
+ source_context.unreadable_message_keys.discard((credential_id, candidate.message_id))
source_context.remember_message(credential_id, candidate.message_id)
if otp_value is None and expected_otp_type is OTPType.TOTP:
# An enforced parse reports "not found" rather than the type it did see,
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index b1b80b570..78336ee5e 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -554,9 +554,10 @@ def create_api_app() -> FastAPI:
@fastapi_app.exception_handler(RequestValidationError)
async def handle_request_validation_error(request: Request, exc: RequestValidationError) -> Response:
- # Only credential routes carry passkey/secret material worth stripping from 422 detail; every
- # other route keeps FastAPI's default input/ctx to preserve debuggable validation errors.
path = request.url.path.rstrip("/")
+ if path == "/api/v1/users/me/onboarding":
+ # Both validation messages and unknown field names can contain reported contact details.
+ return JSONResponse(status_code=422, content={"detail": "invalid_onboarding_data"})
credential_prefixes = ("/v1/credentials", "/api/v1/credentials")
if not any(path == prefix or path.startswith(f"{prefix}/") for prefix in credential_prefixes):
return await request_validation_exception_handler(request, exc)
diff --git a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
index 7999ad1b5..9b6dc2ac1 100644
--- a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
+++ b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
@@ -891,6 +891,22 @@ workflow_definition:
data: "{{ get_data.output }}"
parameter_keys: []
+** GOOGLE SHEETS WRITE BLOCK (google_sheets_write) **
+
+Purpose: Write rows to a Google Sheet, appended below existing data or written over the cells at `range`. `values` is template text the block parses as JSON after rendering, so it must render to one of these shapes.
+- A two-dimensional array with one inner array per row: `[["30 %", 12], ["51.91%", 7]]`. One cell is `[["30 %"]]`.
+- That array wrapped under `values` or `rows`: `{"values": [["30 %"]]}`.
+- A list of objects plus `column_mapping` (object key -> column letter). A single object is written as one row and also needs `column_mapping`.
+- Rich cells: `{"cells": [[<Sheets CellData>, ...]], "merges": [{"start_row_index": 0, "end_row_index": 1, "start_column_index": 0, "end_column_index": 2}]}`.
+Every cell is a JSON value, so a string cell must be quoted. `| tojson` quotes and escapes a referenced value: `[[{{ extract_metric.output.metric | tojson }}]]` renders `[["30 %"]]`, while `[[{{ extract_metric.output.metric }}]]` renders `[[30 %]]`, which is not JSON. A bare scalar such as 30 %, 6.97K or 10200 fails with "Invalid values payload".
+A reference must match the producer's output shape. A browser-task block (extraction, navigation, action, login) holds its payload under `.output`: `{{ extract_metric.output.metric }}`. A code or text_prompt block holds its returned fields on the label itself: `{{ compute_metric.metric }}` (a text_prompt without json_schema returns `llm_response`). An http_request block holds the parsed response body under `.body`: `{{ fetch_metric.body.metric }}`.
+A reference to a value no upstream block produced fails the block with "references a value no upstream block produced", and nothing is written.
+
+Use Cases:
+- Write an extracted metric into one cell
+- Append one row per extracted record
+- Update a fixed range with computed values
+
** PARAMETER TEMPLATING **
All string fields in blocks support Jinja2 templating to reference parameters and block outputs.
@@ -916,11 +932,15 @@ IMPORTANT — block output shapes are NOT uniform across block types. Using the
* File download blocks (file_download):
- `{{ fetch_report.downloaded_file_urls }}` — the URLs of the downloaded files; `{{ fetch_report.downloaded_files }}` holds the full file records. Use these, NOT `{{ fetch_report.output.downloaded_file_urls }}`: a download has no extracted payload, so `.output` holds nothing to read from and renders blank on its own.
-* Non-task blocks (text_prompt, http_request, file_url_parser):
+* Non-task blocks (text_prompt, code, file_url_parser):
- `{{ label.<field> }}` — fields from the returned JSON are on the block directly; there is NO `.output` wrapper.
- Example: `{{ summarize_notes.summary }}` (NOT `{{ summarize_notes.output.summary }}`).
- Writing `{{ summarize_notes.output.summary }}` raises "dict object has no attribute 'output'" because `summarize_notes` IS the dict.
+* HTTP request blocks (http_request):
+ - `{{ fetch_metric.body }}` — the response body, parsed as JSON when the response is JSON; `{{ fetch_metric.status_code }}` and `{{ fetch_metric.headers }}` sit beside it.
+ - Example: `{{ fetch_metric.body.metric }}`. The label itself has no `metric` key, only the recorded response fields.
+
NULL-GUARD RULE — when a downstream field may legitimately be null/empty (e.g., a text_prompt returned `{"store_url": null}` because no such link exists on the page), wrap the reference in a `conditional` block BEFORE using it as a URL. Unguarded `goto_url` with `url: "{{ x.field }}"` where `x.field` is None renders as `https://None` and is not recoverable by retrying the same workflow — it is a nullity bug, not a navigation bug.
Examples - Workflow Parameters:
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index 5ce1beb3e..318ef43a9 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -31,6 +31,8 @@ if typing.TYPE_CHECKING: # pragma: no cover - import only for type hints
LOG = structlog.get_logger()
_SENSITIVE_ENDPOINTS = {
+ "GET /api/v1/users/me/onboarding",
+ "POST /api/v1/users/me/onboarding",
"POST /api/v1/credentials",
"POST /v1/credentials",
"POST /v1/credentials/onepassword/create",
diff --git a/skyvern/forge/sdk/api/files.py b/skyvern/forge/sdk/api/files.py
index 06dd062bf..2801d67f8 100644
--- a/skyvern/forge/sdk/api/files.py
+++ b/skyvern/forge/sdk/api/files.py
@@ -1006,6 +1006,22 @@ def resolve_run_download_id(context: "SkyvernContext | None", fallback_run_id: s
return fallback_run_id
+# The CDP download interceptor names its in-flight temp file ``<final>.<uuid4().hex>.crdownload`` (32
+# lowercase hex chars) before hard-linking to ``<final>``; Chrome-native downloads use ``<final>.crdownload``.
+# Stripped after the ``.crdownload`` suffix, this collapses both temp shapes to the same ``<final>`` identity.
+_INTERCEPTOR_TEMP_IDENTITY_RE = re.compile(r"\.[0-9a-f]{32}$")
+
+
+def normalize_download_identity(file: str) -> str:
+ """Collapse an in-flight download temp name to its settled ``<final>`` identity: Chrome-native
+ ``<final>.crdownload`` and the interceptor's ``<final>.<32-lowercase-hex>.crdownload`` both map to
+ ``<final>``; an already-final name is returned unchanged. Lets a file counted mid-flight and again once
+ settled read as one identity rather than a new arrival."""
+ if not file.endswith(BROWSER_DOWNLOADING_SUFFIX):
+ return file
+ return _INTERCEPTOR_TEMP_IDENTITY_RE.sub("", file.removesuffix(BROWSER_DOWNLOADING_SUFFIX))
+
+
def list_files_in_directory(
directory: Path, recursive: bool = False, *, attempt_started_at: datetime | None = None
) -> list[str]:
diff --git a/skyvern/forge/sdk/browser_egress_policy.py b/skyvern/forge/sdk/browser_egress_policy.py
index 9b64f8414..aea09e022 100644
--- a/skyvern/forge/sdk/browser_egress_policy.py
+++ b/skyvern/forge/sdk/browser_egress_policy.py
@@ -190,7 +190,7 @@ def resolve_public_destination(url: str) -> ResolvedDestination | None:
except ValueError as exc:
raise DestinationBlockedError("blocked egress: malformed host or port") from exc
if not raw_host:
- raise DestinationBlockedError("blocked egress: URL has no host")
+ raise DestinationBlockedError(f"blocked egress: URL has no host ({url!r})")
if port is None:
port = _DEFAULT_PORTS.get(scheme)
if port is None or not 1 <= port <= 65535:
@@ -198,7 +198,7 @@ def resolve_public_destination(url: str) -> ResolvedDestination | None:
host = normalize_host(raw_host)
if not host:
- raise DestinationBlockedError("blocked egress: URL has no host")
+ raise DestinationBlockedError(f"blocked egress: URL has no host ({url!r})")
allowed_locally = host.lower().rstrip(".") in _locally_allowed_hosts()
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 88070a049..b0db9d8ed 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -570,6 +570,42 @@ def _historical_turn_facts_projection(
return projection
+def _recorded_run_ids(messages: Sequence[WorkflowCopilotChatHistoryMessage]) -> list[str]:
+ """Oldest first, from the untruncated log rather than the prompt window: a run that scrolled past
+ ``CHAT_HISTORY_CONTEXT_MESSAGES`` still owns the browser this chat last tested in."""
+ run_ids: list[str] = []
+ for message in messages:
+ if chat_history_role(message.sender) != "ai":
+ continue
+ projection = _historical_turn_facts_projection(message.narrative_payload)
+ if projection is None:
+ continue
+ run_id = projection["facts"].get("runId")
+ if isinstance(run_id, str) and run_id:
+ run_ids.append(run_id)
+ return run_ids
+
+
+def _last_recorded_run_id(messages: Sequence[WorkflowCopilotChatHistoryMessage]) -> str | None:
+ run_ids = _recorded_run_ids(messages)
+ return run_ids[-1] if run_ids else None
+
+
+def _run_to_inherit(
+ requested_run_id: str | None,
+ proposal_run_id: str | None,
+ messages: Sequence[WorkflowCopilotChatHistoryMessage],
+) -> str | None:
+ """``last_run`` means the most recent test, so a candidate's run gives way to one the chat recorded
+ after it; a candidate run the log never recorded has no position to compare and keeps its claim."""
+ if requested_run_id:
+ return requested_run_id
+ recorded = _recorded_run_ids(messages)
+ if proposal_run_id and (proposal_run_id not in recorded or recorded[-1] == proposal_run_id):
+ return proposal_run_id
+ return recorded[-1] if recorded else proposal_run_id
+
+
def _format_chat_history(chat_history: list[WorkflowCopilotChatHistoryMessage]) -> str:
if not chat_history:
return ""
@@ -1695,7 +1731,7 @@ def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> st
)
# No run row means nothing executed, so claiming the draft was tested is false.
- if ctx.last_failure_category_top == "UNRECOVERABLE_TOOL_ERROR" and ctx.last_run_blocks_workflow_run_id is None:
+ if ctx.last_failure_category_top == "UNRECOVERABLE_TOOL_ERROR" and not ctx.dispatched_run_ids_this_turn:
return (
f"I created {draft_phrase}, but I couldn't start a test run: "
f"{_normalize_failure_reason(ctx.last_test_failure_reason)}. "
@@ -5220,13 +5256,21 @@ async def _run_copilot_turn_impl(
await hydrate_work_plan(ctx)
chat_request.workflow_yaml = ctx.workflow_yaml
safe_workflow_yaml = redact_raw_secrets_for_prompt(ctx.workflow_yaml or "")
- # Before the turn acts: a repair opened about a failed run inherits that run's identity and the
- # browser it used, so a tool asked to look at the run has something to look at from the first
- # call rather than only after this turn has run something itself.
+ # Before the turn acts: a tool asked to look at ``last_run`` has something to look at from the
+ # first call rather than only after this turn has run something itself.
# The run the caller named wins; a restored candidate's exact run is the fallback.
associated_run_id = chat_request.workflow_run_id or ctx.proposal_workflow_run_id
- repair_origin_binding = await seed_repair_origin_run(ctx, workflow_run_id=associated_run_id)
- if ctx.proposal_workflow_run_id is not None and associated_run_id == ctx.proposal_workflow_run_id:
+ # Only the ``last_run`` binding follows a test recorded after the candidate's run; the packet and
+ # candidate ownership below stay with the candidate's run.
+ last_run_seed_id = _run_to_inherit(
+ chat_request.workflow_run_id, ctx.proposal_workflow_run_id, safe_prior_user_messages
+ )
+ repair_origin_binding = await seed_repair_origin_run(ctx, workflow_run_id=last_run_seed_id)
+ if (
+ ctx.proposal_workflow_run_id is not None
+ and associated_run_id == ctx.proposal_workflow_run_id
+ and last_run_seed_id == associated_run_id
+ ):
# Exact candidate ownership wins over the generic latest-final-run fallback even when
# the run has no retained browser or row details are no longer available.
ctx.last_run_blocks_workflow_run_id = associated_run_id
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index 3182dcf42..965dcc46e 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -25,6 +25,8 @@ RecoveryHint = Literal[
LOG = structlog.get_logger()
BROWSER_SESSION_LOST_BLOCKER_REASON_CODE = "tool_error_browser_session_lost"
+CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE = "credential_origin_mismatch_recovery"
+CREDENTIAL_ORIGIN_RECOVERY_DECLINED_REASON_CODE = "credential_origin_mismatch_declined"
# Matched case-insensitively. Imperative variants are narrow ("do not run" etc.) so plain "do not worry" prose doesn't false-positive.
@@ -179,6 +181,7 @@ class _ActiveRunEvidenceResetCtx(Protocol):
last_run_blocks_workflow_run_id: str | None
last_successful_run_blocks_workflow_run_id: str | None
last_run_blocks_browser_session_id: str | None
+ last_run_binding_unavailable_reason: str | None
recorded_persisted_block_run_workflow_run_id: str | None
last_run_blocks_block_ids: list[str]
last_run_blocks_block_labels: list[str]
@@ -214,6 +217,7 @@ def clear_active_run_evidence_on_workflow_edit(ctx: _ActiveRunEvidenceResetCtx)
ctx.last_run_blocks_workflow_run_id = None
ctx.last_successful_run_blocks_workflow_run_id = None
ctx.last_run_blocks_browser_session_id = None
+ ctx.last_run_binding_unavailable_reason = None
ctx.recorded_persisted_block_run_workflow_run_id = None
ctx.last_run_blocks_block_ids = []
ctx.last_run_blocks_block_labels = []
diff --git a/skyvern/forge/sdk/copilot/browser_code_contract.py b/skyvern/forge/sdk/copilot/browser_code_contract.py
index 85f24e02c..2e2e3552d 100644
--- a/skyvern/forge/sdk/copilot/browser_code_contract.py
+++ b/skyvern/forge/sdk/copilot/browser_code_contract.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import uuid
from collections.abc import Mapping
from dataclasses import dataclass, field
-from typing import Any, Protocol
+from typing import Any, Literal, Protocol
from playwright.async_api import Page
@@ -136,6 +136,39 @@ class BrowserCodeCellResult:
)
+ExecutedBrowserCodeSourceStatus = Literal[
+ "valid",
+ "missing",
+ "wrong_owner",
+ "wrong_turn",
+ "wrong_generation",
+ "wrong_session",
+ "expired",
+]
+
+
+@dataclass(frozen=True)
+class ExecutedBrowserCodeSource:
+ source: str
+ execution_ok: bool
+ execution_error_code: str | None
+ owner_fingerprint: str
+ turn_token: str
+ browser_session_id: str | None
+ browser_session_generation: int
+ # Set when the cell ran against the last run's browser; the reference stays valid only while that
+ # run is still the last one, since that browser follows the run rather than the chat.
+ last_run_workflow_run_id: str | None = None
+
+
+@dataclass(frozen=True)
+class ExecutedBrowserCodeSourceResolution:
+ status: ExecutedBrowserCodeSourceStatus
+ source: str | None = None
+ execution_ok: bool | None = None
+ execution_error_code: str | None = None
+
+
class BrowserCodeSession(Protocol):
@property
def session_id(self) -> str: ...
@@ -145,6 +178,8 @@ class BrowserCodeSession(Protocol):
async def rebind(self, page: Page) -> None: ...
+ async def reset_namespace(self) -> None: ...
+
async def run_cell(
self, code: str, *, timeout_seconds: float, deny_pixels: bool = False
) -> BrowserCodeCellResult: ...
@@ -167,3 +202,6 @@ class BrowserCodeHost:
sessions_opened: int = 0
interrupted: bool = False
interrupted_operation: BrowserCodeOperation | None = None
+ source_turn_token: str = field(default_factory=lambda: uuid.uuid4().hex)
+ executed_sources: dict[str, ExecutedBrowserCodeSource] = field(default_factory=dict)
+ expired_source_references: set[str] = field(default_factory=set)
diff --git a/skyvern/forge/sdk/copilot/browser_target.py b/skyvern/forge/sdk/copilot/browser_target.py
index b612643a7..9a369c6c2 100644
--- a/skyvern/forge/sdk/copilot/browser_target.py
+++ b/skyvern/forge/sdk/copilot/browser_target.py
@@ -69,6 +69,18 @@ class BrowserSessionBinding:
return stamp
+def last_run_facts(copilot_ctx: AgentContext, failed_browser_session_id: str | None) -> dict[str, str]:
+ """The browser ``last_run`` would bind, stated on a failed call so the model sees the other
+ browser it can name. Facts only: nothing here redirects the call that failed."""
+ run_session_id = copilot_ctx.last_run_blocks_browser_session_id
+ if not run_session_id or run_session_id == failed_browser_session_id:
+ return {}
+ facts = {"last_run_browser_session_id": run_session_id}
+ if copilot_ctx.last_run_blocks_workflow_run_id:
+ facts["last_run_workflow_run_id"] = copilot_ctx.last_run_blocks_workflow_run_id
+ return facts
+
+
def resolve_browser_session_binding(copilot_ctx: AgentContext, arguments: dict[str, Any]) -> BrowserSessionBinding:
"""Bind this call to the browser the model named, or report why that browser is not addressable.
@@ -102,7 +114,10 @@ def resolve_browser_session_binding(copilot_ctx: AgentContext, arguments: dict[s
session_id_override=None,
workflow_run_id=workflow_run_id,
source_matches_target=False,
- unavailable_reason="No test run has recorded a browser session in this chat yet.",
+ unavailable_reason=(
+ copilot_ctx.last_run_binding_unavailable_reason
+ or "No test run has recorded a browser session in this chat yet."
+ ),
)
if run_session_id == copilot_ctx.browser_session_id:
# The run executed in this chat's own browser, so there is nothing to redirect. Overriding
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 6ad4c19b2..74099db46 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -804,7 +804,7 @@ def record_approved_credentials_in_global_llm_context(ctx: CopilotContext, raw_c
# A stamp the carry restored is not page evidence the user has to re-earn: without this a
# user who answers by naming the credential gets no durable approval, which is the re-ask
# loop this amendment exists to end. A stamp a live page wrote this turn still counts.
- settled_ids = policy.current_turn_named_credential_ids
+ settled_ids = policy.current_turn_named_credential_ids | policy.origin_recovery_kept_named_credential_ids
# Read at turn end, when what the user settled is final: a card pick or a typed name landing
# after the citation is still them answering this ask by choosing a different credential.
carry_stamp_the_user_answered = (
@@ -1176,6 +1176,9 @@ class CopilotContext(AgentContext):
credential_recovery_token_digest: str | None = field(default=None, repr=False)
credential_recovery_armed: bool = False
credential_pause_used: bool = False
+ # The missing-authenticator ask may follow an answered card once per turn: it asks to fix the
+ # credential the user already chose, not to choose again.
+ credential_totp_update_asked: bool = False
# A tool ask the user did not answer with a credential spends the one-card budget on a guess.
# A run that then hits a real login wall has evidence the guess did not, so it gets the budget
# back once.
@@ -1254,6 +1257,9 @@ class CopilotContext(AgentContext):
# The browser session the last run actually executed in. On the fresh-session replay path this
# is not ctx.browser_session_id, which stays pointed at the debug/scout browser.
last_run_blocks_browser_session_id: str | None = None
+ # Why the chat's last recorded run could not be bound, when it could not. Distinct from having
+ # no run at all, which the target resolver states itself.
+ last_run_binding_unavailable_reason: str | None = None
# In-turn run-outcome trace derived from assignments to ``last_run_outcome``
# (the same source that powers run_outcome SSE frames). Append-only across
# per-run pointer resets (``last_run_outcome = None``) and workflow edits.
@@ -1388,13 +1394,9 @@ class CopilotContext(AgentContext):
return True
if self.last_test_ok is not None:
return True
- for run_id in (
- self.last_run_blocks_workflow_run_id,
- self.last_successful_run_blocks_workflow_run_id,
- ):
- if run_id is not None and run_id.strip():
- return True
- return False
+ # Runs this turn dispatched, not ``last_run_blocks_workflow_run_id``: that one can hold a
+ # run inherited from an earlier turn, which is not an attempt by this one.
+ return bool(self.dispatched_run_ids_this_turn)
def genuine_attempt_parity_fields(self) -> dict[str, bool | int | str | None]:
return {
@@ -1405,5 +1407,6 @@ class CopilotContext(AgentContext):
"last_test_ok": self.last_test_ok,
"last_run_blocks_workflow_run_id": self.last_run_blocks_workflow_run_id,
"last_successful_run_blocks_workflow_run_id": self.last_successful_run_blocks_workflow_run_id,
+ "dispatched_run_count_this_turn": len(self.dispatched_run_ids_this_turn),
"ctx_last_workflow_present": self.last_workflow is not None,
}
diff --git a/skyvern/forge/sdk/copilot/credential_pause.py b/skyvern/forge/sdk/copilot/credential_pause.py
index 9aa894c6f..68c4c4bd1 100644
--- a/skyvern/forge/sdk/copilot/credential_pause.py
+++ b/skyvern/forge/sdk/copilot/credential_pause.py
@@ -25,6 +25,7 @@ import json
import re
import secrets
import time
+from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from http import HTTPStatus
@@ -49,6 +50,8 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (
if TYPE_CHECKING:
from agents.result import RunResultStreaming
+ from skyvern.forge.sdk.copilot.context import CopilotContext
+
# Importing the routes package at module scope pulls in workflow_copilot.py ->
# agent.py -> enforcement.py, which imports this module -> circular import.
from skyvern.forge.sdk.core.event_source_stream import EventSourceStream
@@ -309,7 +312,7 @@ async def resolve_credential_pause(
await cache.set(active_key, _encode_active_pause(record.resume_token, record.expires_at, consumed=True), ex=ttl)
await cache.set(
credential_response_cache_key(organization_id, workflow_copilot_chat_id, turn_id),
- encode_credential_response(action, credential_id),
+ encode_credential_response(action, credential_id, record.resume_token),
ex=ttl,
)
@@ -320,11 +323,13 @@ class CredentialPauseResolution:
credential: Credential | None = None
-def encode_credential_response(action: Literal["connected", "skip"], credential_id: str | None) -> str:
- return json.dumps({"action": action, "credential_id": credential_id})
+def encode_credential_response(
+ action: Literal["connected", "skip"], credential_id: str | None, resume_token: str
+) -> str:
+ return json.dumps({"action": action, "credential_id": credential_id, "resume_token": resume_token})
-def _decode_credential_response(raw: Any) -> tuple[str, str | None] | None:
+def _decode_credential_response(raw: Any) -> tuple[str, str | None, str | None] | None:
try:
data = json.loads(raw)
except (TypeError, ValueError):
@@ -332,7 +337,12 @@ def _decode_credential_response(raw: Any) -> tuple[str, str | None] | None:
if not isinstance(data, dict) or data.get("action") not in ("connected", "skip"):
return None
credential_id = data.get("credential_id")
- return data["action"], credential_id if isinstance(credential_id, str) else None
+ resume_token = data.get("resume_token")
+ return (
+ data["action"],
+ credential_id if isinstance(credential_id, str) else None,
+ resume_token if isinstance(resume_token, str) else None,
+ )
def credential_pause_reason(ctx: Any) -> str | None:
@@ -369,7 +379,9 @@ def credential_pause_reason(ctx: Any) -> str | None:
return None
-def credential_pause_transport_ready(ctx: Any, copilot_config: CopilotConfig | None) -> bool:
+def credential_pause_transport_ready(
+ ctx: CopilotContext, copilot_config: CopilotConfig | None, *, allow_second_ask: bool = False
+) -> bool:
"""Whether a card can be shown at all this turn, independent of what is asking for one.
Excludes the async-only checks (stream disconnect).
@@ -377,8 +389,8 @@ def credential_pause_transport_ready(ctx: Any, copilot_config: CopilotConfig | N
return (
copilot_config is not None
and copilot_config.credential_pause_enabled
- and getattr(ctx, "client_supports_credential_pause", False)
- and not getattr(ctx, "credential_pause_used", False)
+ and ctx.client_supports_credential_pause
+ and (allow_second_ask or not ctx.credential_pause_used)
# A same-process-only cache (LocalCache) can't coordinate the poller with a
# /credential-response POST that may land on a different worker -- gate on a
# cache that's explicitly known to be shared (Redis) rather than merely non-None.
@@ -472,7 +484,7 @@ _SKIP_RESUME_TEXT = (
async def _try_resolve_credential_response(
- response_key: str, organization_id: str
+ response_key: str, organization_id: str, resume_token: str
) -> CredentialPauseResolution | None | Literal["pending"]:
cache = app.CACHE
raw = await cache.get(response_key)
@@ -481,7 +493,10 @@ async def _try_resolve_credential_response(
decoded = _decode_credential_response(raw)
if decoded is None:
return "pending"
- action, credential_id = decoded
+ action, credential_id, answered_token = decoded
+ # The response key is per turn, so a card only takes an answer carrying its own token.
+ if answered_token != resume_token:
+ return "pending"
if action == "skip":
return CredentialPauseResolution(action="skip")
if not credential_id:
@@ -494,14 +509,15 @@ async def _try_resolve_credential_response(
async def _wait_for_credential_response(
response_key: str,
- ctx: Any,
+ ctx: CopilotContext,
stream: EventSourceStream,
timeout_seconds: int,
+ resume_token: str,
) -> CredentialPauseResolution | None:
recovery_enabled = _credential_recovery_enabled(ctx)
# Check once before the sleep loop so a card response posted in the brief
# window before the first poll doesn't cost a full extra poll interval.
- first = await _try_resolve_credential_response(response_key, ctx.organization_id)
+ first = await _try_resolve_credential_response(response_key, ctx.organization_id, resume_token)
if first != "pending":
return first
@@ -511,7 +527,7 @@ async def _wait_for_credential_response(
# Resolve before checking disconnect: an already-posted response must win
# over a disconnect that happened after the POST (e.g. connect-then-refresh),
# not get discarded as a timeout.
- resolved = await _try_resolve_credential_response(response_key, ctx.organization_id)
+ resolved = await _try_resolve_credential_response(response_key, ctx.organization_id, resume_token)
if resolved != "pending":
return resolved
if not recovery_enabled and await stream.is_disconnected():
@@ -520,13 +536,16 @@ async def _wait_for_credential_response(
async def _run_credential_pause(
- ctx: Any,
+ ctx: CopilotContext,
message: str,
stream: EventSourceStream,
copilot_config: CopilotConfig,
*,
reason: str,
login_page_urls: list[str],
+ missing_totp_credential_id: str | None = None,
+ admit_connected: Callable[[Credential], Awaitable[bool]] | None = None,
+ allow_second_ask: bool = False,
) -> CredentialPauseResolution | None:
"""Send the credential card and wait for the user's decision.
@@ -535,32 +554,43 @@ async def _run_credential_pause(
turn, no shared cache, unrecoverable client disconnect, or timeout).
Recovery-capable clients restore the same active card through chat history.
"""
- if not credential_pause_transport_ready(ctx, copilot_config):
+ update_ask = missing_totp_credential_id is not None
+ if not credential_pause_transport_ready(ctx, copilot_config, allow_second_ask=update_ask or allow_second_ask):
return None
- # Latch before async checks so a declined transport cannot trigger another
- # pause. Recovery-capable clients can retrieve the card after disconnect.
- ctx.credential_pause_used = True
+ # Latch before async checks so a declined transport cannot trigger another pause. Only the pick ask
+ # spends credential_pause_used; request_credential_pause latches the update ask.
+ if not update_ask:
+ ctx.credential_pause_used = True
+
+ def settle(outcome: str) -> None:
+ # An update card asks to fix a credential already chosen, so the turn keeps its pick card's state.
+ if not update_ask:
+ ctx.credential_pause_outcome = outcome
+
cache = getattr(app, "CACHE", None)
if cache is None:
- ctx.credential_pause_outcome = "declined"
+ settle("declined")
return None
recovery_enabled = _credential_recovery_enabled(ctx)
if not recovery_enabled and await stream.is_disconnected():
- ctx.credential_pause_outcome = "declined"
+ settle("declined")
return None
- policy = getattr(ctx, "request_policy", None)
- # The FE credential card fetches the full org list itself; these ride the frame as `credential_refs`
- # and seed the picker's "Suggested" group (pinned first), so the user still sees the full list.
- if isinstance(policy, RequestPolicy):
- # Bind an answer to the URLs on this card, never an earlier unanswered ask.
- policy.credential_ask_login_page_urls = list(login_page_urls)
- credential_refs = list(policy.credential_refs) if isinstance(policy, RequestPolicy) else []
+ policy = ctx.request_policy
+ if missing_totp_credential_id is not None:
+ credential_refs = [missing_totp_credential_id]
+ else:
+ # The FE credential card fetches the full org list itself; these ride the frame as `credential_refs`
+ # and seed the picker's "Suggested" group (pinned first), so the user still sees the full list.
+ if isinstance(policy, RequestPolicy):
+ # Bind an answer to the URLs on this card, never an earlier unanswered ask.
+ policy.credential_ask_login_page_urls = list(login_page_urls)
+ credential_refs = list(policy.credential_refs) if isinstance(policy, RequestPolicy) else []
timeout_seconds = copilot_config.credential_pause_timeout_seconds
now = datetime.now(timezone.utc)
organization_id = ctx.organization_id
- chat_id = getattr(ctx, "workflow_copilot_chat_id", None) or ""
- turn_id = getattr(ctx, "turn_id", None) or ""
+ chat_id = ctx.workflow_copilot_chat_id or ""
+ turn_id = ctx.turn_id or ""
resume_token = _new_resume_token()
expires_at = now + timedelta(seconds=timeout_seconds)
# Establish the active-pause record before the frame carries the token: the
@@ -603,7 +633,7 @@ async def _run_credential_pause(
# given up -- will never read. Rescue it if it raced in.
lock_key = _credential_pause_lock_key(organization_id, chat_id, turn_id)
async with cache.get_lock(lock_key):
- raced_in = await _try_resolve_credential_response(response_key, organization_id)
+ raced_in = await _try_resolve_credential_response(response_key, organization_id, resume_token)
if isinstance(raced_in, CredentialPauseResolution):
return raced_in
await cache.set(
@@ -619,12 +649,14 @@ async def _run_credential_pause(
# Legacy clients cannot restore a dropped frame, so preserve their
# immediate decline when disconnect races the send.
await _invalidate_active_pause_record()
- ctx.credential_pause_outcome = "declined"
+ settle("declined")
return None
try:
with pause_human_input(ctx, "credential"):
- resolution = await _wait_for_credential_response(response_key, ctx, stream, timeout_seconds)
+ resolution = await _wait_for_credential_response(
+ response_key, ctx, stream, timeout_seconds, resume_token=resume_token
+ )
except BaseException:
# Covers CancelledError (a direct BaseException subclass, not Exception)
# alongside any unexpected failure in the wait loop itself -- the frame's
@@ -637,20 +669,31 @@ async def _run_credential_pause(
if resolution is None:
resolution = await _invalidate_active_pause_record()
if resolution is None:
- ctx.credential_pause_outcome = "timeout"
+ settle("timeout")
return None
if resolution.action == "skip":
- ctx.credential_pause_outcome = "skipped"
- # A missing_credential_run_failure pause means the diagnosed run left
- # last_test_ok=False; without clearing it, the resumed reply is intercepted
- # by the generic failed-test nudge instead of honoring the skip decision.
- ctx.last_test_ok = None
+ settle("skipped")
+ if not update_ask:
+ # A missing_credential_run_failure pause means the diagnosed run left
+ # last_test_ok=False; without clearing it, the resumed reply is intercepted
+ # by the generic failed-test nudge instead of honoring the skip decision.
+ ctx.last_test_ok = None
return resolution
credential = resolution.credential
if credential is None:
- ctx.credential_pause_outcome = "timeout"
+ settle("timeout")
return None
+ if update_ask:
+ # The update card grants no authority: the credential keeps its origin and the request policy is
+ # unchanged. It has no picker, so an answer naming another credential is not this update.
+ if credential.credential_id != missing_totp_credential_id:
+ LOG.warning("copilot_credential_update_answer_names_another_credential")
+ return None
+ return resolution
+ if admit_connected is not None and not await admit_connected(credential):
+ ctx.credential_pause_outcome = "not_admitted"
+ return resolution
if isinstance(policy, RequestPolicy):
_apply_connected_credential_to_policy(ctx, policy, credential)
ctx.credential_pause_outcome = "connected"
@@ -675,27 +718,37 @@ def release_credential_pause_gate(ctx: Any) -> None:
async def request_credential_pause(
- ctx: Any,
+ ctx: CopilotContext,
*,
login_page_url: str,
message: str,
stream: EventSourceStream,
copilot_config: CopilotConfig,
+ missing_totp_credential_id: str | None = None,
+ admit_connected: Callable[[Credential], Awaitable[bool]] | None = None,
+ allow_second_ask: bool = False,
) -> CredentialPauseResolution | None:
"""Raise the card from the model's own ``request_credential`` call and wait, inline, for the
answer, so tool calls the model issued alongside it can await ``credential_pause_settled``."""
arm_credential_pause_gate(ctx)
ctx.credential_ask_in_flight = True
+ update_ask = missing_totp_credential_id is not None
+ if update_ask:
+ ctx.credential_totp_update_asked = True
try:
resolution = await _run_credential_pause(
ctx,
message,
stream,
copilot_config,
- reason="login_credentials_unresolved",
+ reason="credential_missing_totp" if update_ask else "login_credentials_unresolved",
login_page_urls=[login_page_url],
+ missing_totp_credential_id=missing_totp_credential_id,
+ admit_connected=admit_connected,
+ allow_second_ask=allow_second_ask,
)
- ctx.credential_pause_reaskable_by_run = resolution is None or resolution.action != "connected"
+ if not update_ask:
+ ctx.credential_pause_reaskable_by_run = resolution is None or resolution.action != "connected"
return resolution
finally:
ctx.credential_ask_in_flight = False
@@ -720,7 +773,7 @@ async def await_pending_credential_pause(ctx: Any) -> None:
async def maybe_credential_pause(
- ctx: Any,
+ ctx: CopilotContext,
result: RunResultStreaming,
stream: EventSourceStream,
copilot_config: CopilotConfig,
@@ -731,11 +784,12 @@ async def maybe_credential_pause(
caller finalize normally.
"""
reason = credential_pause_reason(ctx)
- if reason is None:
+ # A refused cross-site fill owns the card: it asks for its own origin, and a declined one is not asked again.
+ if reason is None or ctx.credential_origin_recovery is not None:
return None
- # Exactly True, not merely truthy: ctx is Any here, and a partial stand-in returns a truthy
+ # Exactly True, not merely truthy: a partial stand-in returns a truthy
# object for any attribute, which would hand the budget back on every turn.
- if getattr(ctx, "credential_pause_reaskable_by_run", False) is True:
+ if ctx.credential_pause_reaskable_by_run is True:
# The spent card was a guess the user never answered; this ask has a run behind it. Hand the
# budget back once, so an unanswered guess cannot silently cost the turn its real card.
ctx.credential_pause_reaskable_by_run = False
@@ -746,7 +800,7 @@ async def maybe_credential_pause(
from skyvern.forge.sdk.copilot.enforcement import _parse_normalized_final_response
parsed = _parse_normalized_final_response(result)
- policy = getattr(ctx, "request_policy", None)
+ policy = ctx.request_policy
resolution = await _run_credential_pause(
ctx,
str((parsed or {}).get("user_response") or ""),
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index d88b5a6f6..5bfe328de 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -54,6 +54,7 @@ from skyvern.forge.sdk.copilot.runtime import (
bound_call_browser_session,
browser_evidence_commit_lock,
browser_page_custody_lock,
+ browser_session_recovery,
close_browser_session_quietly,
current_call_browser_session_override,
ensure_browser_session,
@@ -87,6 +88,7 @@ from skyvern.forge.sdk.copilot.browser_target import (
BROWSER_TARGET_PARAM,
BROWSER_TARGET_PARAM_NAME,
BrowserSessionBinding,
+ last_run_facts,
resolve_browser_session_binding,
)
@@ -135,6 +137,7 @@ class _BrowserCallOutcome:
evidence_drain_complete: bool | None = None
cancelled: bool = False
protocol_error_detail: str | None = None
+ last_run_facts: dict[str, str] = field(default_factory=dict)
_raw_result_payload: dict[str, Any] = field(default_factory=dict, repr=False)
def raw_result(self) -> dict[str, Any]:
@@ -352,6 +355,8 @@ def _scrub_browser_call_outcome(ctx: AgentContext, outcome: _BrowserCallOutcome)
scrubbed = outcome.with_raw_result(
scrub_model_facing_tool_result(ctx, outcome.raw_result(), tool_name=outcome.raw_tool_name)
)
+ if outcome.error_kind == "protocol":
+ scrubbed = replace(scrubbed, last_run_facts=last_run_facts(ctx, outcome.source_browser_session_id))
if outcome.protocol_error_detail is None:
return scrubbed
detail_result = scrub_model_facing_tool_result(ctx, {"ok": False, "error": outcome.protocol_error_detail})
@@ -402,6 +407,16 @@ def _project_browser_call_outcome(
disposition=outcome.session_loss_disposition,
deadline_expired=outcome.session_loss_deadline_expired,
)
+ # A cancelled or timed-out call projects no continuity block of its own, and that is the shape
+ # the other browser matters most on, so the carrier is made rather than skipped.
+ if outcome.last_run_facts and result.get("ok") is not True:
+ data = result.setdefault("data", {})
+ if isinstance(data, dict):
+ continuity = data.get("browser_call_continuity") or data.get("browser_session_continuity")
+ if not isinstance(continuity, dict):
+ continuity = {"source": "direct_mcp", "failed_tool": display_tool_name}
+ data["browser_call_continuity"] = continuity
+ continuity.update(outcome.last_run_facts)
return result
@@ -568,16 +583,6 @@ async def _browser_session_continuity_lock(organization_id: str, lost_session_id
_LOCAL_CONTINUITY_LOCKS.pop(local_key, None)
-@asynccontextmanager
-async def _context_browser_session_recovery_lock(ctx: AgentContext) -> AsyncIterator[None]:
- lock = getattr(ctx, "browser_session_recovery_lock", None)
- if lock is None:
- yield
- return
- async with lock:
- yield
-
-
def _decode_continuity_outcome(raw: object) -> _BrowserSessionContinuityOutcome | None:
if isinstance(raw, bytes):
raw = raw.decode(errors="replace")
@@ -1017,6 +1022,24 @@ async def _handle_browser_session_loss(
)
return "failed"
+ # Promotion of retained browser-code source holds this same context lock through persistence.
+ # Recovery must not retire the browser or advance its generation while that promotion is in flight.
+ async with browser_session_recovery(ctx):
+ return await _handle_browser_session_loss_under_context_lock(
+ ctx,
+ tool_name=tool_name,
+ call_path=call_path,
+ lost_session_id=lost_session_id,
+ )
+
+
+async def _handle_browser_session_loss_under_context_lock(
+ ctx: AgentContext,
+ *,
+ tool_name: str,
+ call_path: Literal["model", "internal"],
+ lost_session_id: str,
+) -> Literal["reestablished", "failed"]:
local_replacements = getattr(ctx, "browser_session_replacements", {})
if lost_session_id in local_replacements:
return "reestablished" if local_replacements[lost_session_id] is not None else "failed"
@@ -1024,7 +1047,7 @@ async def _handle_browser_session_loss(
async with _browser_session_continuity_lock(ctx.organization_id, lost_session_id):
recorded = await _get_continuity_outcome(ctx.organization_id, lost_session_id)
if recorded is not None:
- _apply_continuity_outcome(ctx, recorded, tool_name=tool_name, call_path=call_path)
+ await _apply_continuity_outcome(ctx, recorded, tool_name=tool_name, call_path=call_path)
return recorded.disposition
root_session_id = await _get_continuity_root(ctx.organization_id, lost_session_id)
@@ -1040,7 +1063,7 @@ async def _handle_browser_session_loss(
deadline_expired=deadline_expired,
)
await close_browser_session_quietly(ctx.organization_id, lost_session_id)
- retire_browser_session_id(ctx, lost_session_id)
+ await retire_browser_session_id(ctx, lost_session_id)
if root_session_id is not None:
outcome = _BrowserSessionContinuityOutcome(
@@ -1060,7 +1083,7 @@ async def _handle_browser_session_loss(
replacement_session_id = ctx.browser_session_id if recovery_error is None else None
if recovery_error is not None and ctx.browser_session_id is not None:
await close_browser_session_quietly(ctx.organization_id, ctx.browser_session_id)
- retire_browser_session_id(ctx, ctx.browser_session_id)
+ await retire_browser_session_id(ctx, ctx.browser_session_id)
outcome = _BrowserSessionContinuityOutcome(
lost_session_id=lost_session_id,
root_session_id=lost_session_id,
@@ -1070,7 +1093,7 @@ async def _handle_browser_session_loss(
)
await _store_continuity_outcome(ctx.organization_id, outcome)
- _apply_continuity_outcome(ctx, outcome, tool_name=tool_name, call_path=call_path)
+ await _apply_continuity_outcome(ctx, outcome, tool_name=tool_name, call_path=call_path)
_emit_continuity_event(
ctx,
tool_name=tool_name,
@@ -1144,32 +1167,33 @@ def _emit_continuity_event(
)
-def _apply_continuity_outcome(
+async def _apply_continuity_outcome(
ctx: AgentContext,
outcome: _BrowserSessionContinuityOutcome,
*,
tool_name: str,
call_path: Literal["model", "internal"],
) -> None:
- ctx.browser_session_id = outcome.replacement_session_id
- replacements = getattr(ctx, "browser_session_replacements", None)
- if not isinstance(replacements, dict):
- replacements = {}
- ctx.browser_session_replacements = replacements
- replacements[outcome.lost_session_id] = outcome.replacement_session_id
- ctx.browser_session_continuity_generation = getattr(ctx, "browser_session_continuity_generation", 0) + 1
- ctx.browser_session_continuity_disposition = outcome.disposition
- ctx.browser_session_continuity_deadline_expired = outcome.deadline_expired
- if outcome.disposition == "failed":
- stash_blocker_signal(
- ctx,
- _browser_session_loss_blocker_signal(
- tool_name=tool_name,
- call_path=call_path,
- lost_session_id=outcome.lost_session_id,
- deadline_expired=outcome.deadline_expired,
- ),
- )
+ async with browser_session_recovery(ctx):
+ ctx.browser_session_id = outcome.replacement_session_id
+ replacements = getattr(ctx, "browser_session_replacements", None)
+ if not isinstance(replacements, dict):
+ replacements = {}
+ ctx.browser_session_replacements = replacements
+ replacements[outcome.lost_session_id] = outcome.replacement_session_id
+ ctx.browser_session_continuity_generation = getattr(ctx, "browser_session_continuity_generation", 0) + 1
+ ctx.browser_session_continuity_disposition = outcome.disposition
+ ctx.browser_session_continuity_deadline_expired = outcome.deadline_expired
+ if outcome.disposition == "failed":
+ stash_blocker_signal(
+ ctx,
+ _browser_session_loss_blocker_signal(
+ tool_name=tool_name,
+ call_path=call_path,
+ lost_session_id=outcome.lost_session_id,
+ deadline_expired=outcome.deadline_expired,
+ ),
+ )
async def _prepare_browser_session_for_dispatch(
@@ -1186,7 +1210,7 @@ async def _prepare_browser_session_for_dispatch(
# precondition. The dispatch is the oracle for the targeted session; a dead one lands in
# _handle_browser_session_loss, which refuses the call without disturbing the chat.
return None, None, None
- async with _context_browser_session_recovery_lock(ctx):
+ async with browser_session_recovery(ctx):
if getattr(ctx, "browser_session_continuity_generation", 0) != observed_generation:
disposition: Literal["reestablished", "failed"] = (
"reestablished"
@@ -1210,7 +1234,7 @@ async def _prepare_browser_session_for_dispatch(
async with _browser_session_continuity_lock(ctx.organization_id, prior_session_id):
recorded = await _get_continuity_outcome(ctx.organization_id, prior_session_id)
if recorded is not None:
- _apply_continuity_outcome(ctx, recorded, tool_name=tool_name, call_path=call_path)
+ await _apply_continuity_outcome(ctx, recorded, tool_name=tool_name, call_path=call_path)
return (
None,
_browser_session_loss_result(
@@ -1445,7 +1469,7 @@ class SkyvernOverlayMCPServer(MCPServer):
try:
browser_state = await resolve_browser_state_for_context(ctx)
if browser_state is None:
- retire_browser_session_id(ctx, examined_session_id)
+ await retire_browser_session_id(ctx, examined_session_id)
raise RuntimeError("Evidence-candidate navigation guard requires a browser context")
async with service_worker_blocked_context(
browser_state,
diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.py
index b64f31dbc..6f51bcfb5 100644
--- a/skyvern/forge/sdk/copilot/narration.py
+++ b/skyvern/forge/sdk/copilot/narration.py
@@ -107,6 +107,7 @@ _TOOL_ACTIVITY_DISPLAY_LABELS = {
"get_block_schema": "Checking workflow block options",
"get_workflow_knowledge": "Looking up workflow guidance",
"list_integrations": "Checking connected integrations",
+ "get_organization_usage_quota": "Checking account usage",
"inspect_current_workflow": "Inspecting workflow",
"discover_workflow_entrypoint": "Finding the entry page",
"search_web": "Searching the web",
@@ -736,6 +737,7 @@ _USER_FACING_TOOL_LABELS: dict[str, str] = {
"console_messages": "checking the browser console",
"list_credentials": "checking saved credentials",
"list_integrations": "checking connected integrations",
+ "get_organization_usage_quota": "checking account usage",
"get_block_schema": "looking up workflow block options",
"get_workflow_knowledge": "looking up workflow guidance",
"validate_block": "checking workflow block configuration",
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 3557f1207..a5120798e 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -2109,6 +2109,7 @@ _USER_FACING_EMPTY_SUCCESS_TOOLS: frozenset[str] = frozenset(
"evaluate",
"select_option",
"list_credentials",
+ "get_organization_usage_quota",
"request_credential",
# The server-authored display label already names the operation and its
# target block; a bare "OK" summary would render instead of it.
diff --git a/skyvern/forge/sdk/copilot/repair_origin_run.py b/skyvern/forge/sdk/copilot/repair_origin_run.py
index c4f6a3761..284d24045 100644
--- a/skyvern/forge/sdk/copilot/repair_origin_run.py
+++ b/skyvern/forge/sdk/copilot/repair_origin_run.py
@@ -34,6 +34,18 @@ class RepairOriginRefusal(StrEnum):
FOREIGN_ORGANIZATION = "foreign_organization"
WORKFLOW_MISMATCH = "workflow_mismatch"
NO_RECORDED_BROWSER = "no_recorded_browser"
+ LOOKUP_FAILED = "lookup_failed"
+
+
+# What a tool asked for ``last_run`` is told when the binding was refused. NOT_REQUESTED is absent
+# on purpose: no run to bind at all is the resolver's own sentence, not a failure to explain.
+_REFUSAL_SENTENCES: dict[RepairOriginRefusal, str] = {
+ RepairOriginRefusal.RUN_NOT_FOUND: "The last run this chat recorded is no longer readable.",
+ RepairOriginRefusal.FOREIGN_ORGANIZATION: "The last run this chat recorded belongs to another organization.",
+ RepairOriginRefusal.WORKFLOW_MISMATCH: "The last run this chat recorded belongs to another workflow.",
+ RepairOriginRefusal.NO_RECORDED_BROWSER: "The last run this chat recorded did not record a browser session.",
+ RepairOriginRefusal.LOOKUP_FAILED: "The last run this chat recorded could not be looked up.",
+}
class RepairTurnContext(Protocol):
@@ -51,6 +63,7 @@ class RepairTurnContext(Protocol):
last_run_blocks_workflow_run_id: str | None
last_run_blocks_browser_session_id: str | None
+ last_run_binding_unavailable_reason: str | None
@dataclass(frozen=True, slots=True)
@@ -116,14 +129,23 @@ async def seed_repair_origin_run(ctx: RepairTurnContext, *, workflow_run_id: str
A test run inside the turn overwrites this the ordinary way, so a turn that re-runs is looking
at what it just did rather than at what it inherited.
"""
- binding = await resolve_repair_origin_binding(
- workflow_run_id=workflow_run_id,
- organization_id=ctx.organization_id,
- workflow_permanent_id=ctx.workflow_permanent_id,
- )
+ try:
+ binding = await resolve_repair_origin_binding(
+ workflow_run_id=workflow_run_id,
+ organization_id=ctx.organization_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ )
+ except Exception:
+ # An inherited fact is worth less than the turn: an unreadable run leaves the binding unset
+ # so the turn reports an unavailable target instead of failing before it starts.
+ LOG.warning("copilot_repair_origin_lookup_failed", requested_workflow_run_id=workflow_run_id, exc_info=True)
+ binding = _refused(RepairOriginRefusal.LOOKUP_FAILED)
if binding.usable:
ctx.last_run_blocks_workflow_run_id = binding.workflow_run_id
ctx.last_run_blocks_browser_session_id = binding.browser_session_id
+ ctx.last_run_binding_unavailable_reason = (
+ _REFUSAL_SENTENCES.get(binding.refusal) if binding.refusal is not None else None
+ )
LOG.info(
"copilot_repair_origin_binding",
requested_workflow_run_id=workflow_run_id,
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 80dc0bcdc..0ecc40860 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -952,6 +952,9 @@ class RequestPolicy:
# cred_ id — as distinct from approvals carried in from earlier turns. Naming a credential
# answers which one to use, which is what lets the login page answer where it may be typed.
current_turn_named_credential_ids: set[str] = field(default_factory=set)
+ # A credential the user named before a refused cross-site fill connected a provider login in its place.
+ # Kept apart so the fill seam's which-credential check still sees only the provider login as named.
+ origin_recovery_kept_named_credential_ids: set[str] = field(default_factory=set)
# Explicit user approvals hydrated from the existing trusted structured chat context.
prior_approved_credential_ids: set[str] = field(default_factory=set)
# Sites the user themselves provided anywhere in this chat, one URL per origin. A credential may
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 79c3df85d..efd9b6c17 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypeAlias, TypedDic
from urllib.parse import urlsplit
import structlog
+from playwright._impl._errors import TargetClosedError as PlaywrightTargetClosedError
from skyvern.cli.core.api_key_hash import hash_api_key_for_cache
from skyvern.cli.core.client import (
@@ -59,10 +60,12 @@ from skyvern.forge.sdk.schemas.credentials import Credential
from skyvern.library.skyvern_browser import SkyvernBrowser
from skyvern.schemas.browser_session_close import BrowserSessionCloseReason
from skyvern.schemas.proxy_location import ProxyLocationInput
+from skyvern.webeye.browser_engine import is_any_engine_error
from skyvern.webeye.browser_errors import (
BrowserCdpAcquisitionError,
BrowserCdpConnectionError,
BrowserTargetClosedError,
+ is_target_closed_message,
)
from skyvern.webeye.browser_retirement import BrowserOperationRejected, BrowserRetirement, BrowserRetirementReason
from skyvern.webeye.browser_state import BrowserState
@@ -92,6 +95,17 @@ LOG = structlog.get_logger()
# Where a planned frontier run starts its browser from; only a non-``unanchored`` start proves the
# run began in a composition state the workflow itself established.
FrontierStartProvenance = Literal["initial", "replayed", "resumed", "unanchored"]
+CredentialOriginRecoveryState = Literal["pending", "asked", "declined"]
+CredentialOriginDeclineStatus = Literal[
+ "unavailable", "already_asked", "error", "unanswered", "skipped", "connected_unresolved", "connected_other_site"
+]
+
+
+@dataclass(frozen=True)
+class CredentialOriginRecovery:
+ origin: str
+ state: CredentialOriginRecoveryState
+ refused_credential_id: str
def _immutable_redaction_value(value: Any) -> Any:
@@ -140,6 +154,9 @@ _DRIVER_RELEASES_IN_FLIGHT: dict[str, asyncio.Event] = {}
# Bumped per session when a release starts, so a lookup can tell one began and finished while it
# was out. Never pruned: one int per session id this process has ever released.
_DRIVER_RELEASE_EPOCHS: dict[str, int] = {}
+# A positive closed report that landed after its caller gave up, keyed by session to the release epoch
+# it was determined under. ponytail: pod-local, so a determination finished on another pod is lost.
+_ABANDONED_CLOSED_FACTS: dict[str, int] = {}
# How long a superseded run's owner gets to drop the lease. The worker releases only after its own
# cooperative cancel check, so a cleared runnable_id is the evidence its browser work stopped.
_SUPERSEDE_RELEASE_WAIT_SECONDS = 15.0
@@ -435,6 +452,8 @@ class AgentContext:
default_factory=dict
)
browser_session_recovery_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ browser_session_recovery_owner: asyncio.Task[Any] | None = field(default=None, init=False, repr=False)
+ browser_session_recovery_depth: int = field(default=0, init=False, repr=False)
browser_session_replacements: dict[str, str | None] = field(default_factory=dict)
# Calls capture this before waiting for the recovery lock. A continuity recovery increments it
# under that lock so every sibling queued against stale page state is suppressed.
@@ -563,6 +582,7 @@ class AgentContext:
last_good_workflow_yaml: str | None = None
last_run_blocks_workflow_run_id: str | None = None
last_run_blocks_browser_session_id: str | None = None
+ last_run_binding_unavailable_reason: str | None = None
last_artifact_health_blocker_reason: str | None = None
last_artifact_health_blocker_labels: list[str] = field(default_factory=list)
last_artifact_health_failure_classes: list[str] = field(default_factory=list)
@@ -744,6 +764,11 @@ class AgentContext:
# render the current tool result from structured product text.
latest_tool_blocker_signal: CopilotToolBlockerSignal | None = None
tool_blocker_signals: list[CopilotToolBlockerSignal] = field(default_factory=list)
+ # The origin a credential fill was refused on, and how far the ask for a login there has got.
+ # It steers the model and the card; it withdraws no tool.
+ credential_origin_recovery: CredentialOriginRecovery | None = None
+ # Recovery origins that already had their card this turn; each gets the one-card budget back once.
+ credential_origin_recovery_carded: set[str] = field(default_factory=set)
def mcp_to_copilot(mcp_result: dict[str, Any]) -> dict[str, Any]:
@@ -1087,6 +1112,32 @@ async def resolve_browser_state_for_context(
return browser_state
+def _exception_causes(exc: BaseException) -> list[BaseException]:
+ causes: list[BaseException] = []
+ cause = exc.__cause__
+ while cause is not None and cause not in causes:
+ causes.append(cause)
+ cause = cause.__cause__
+ return causes
+
+
+def _is_native_target_closed(exc: BaseException) -> bool:
+ if isinstance(exc, PlaywrightTargetClosedError):
+ return True
+ return is_any_engine_error(exc) and is_target_closed_message(str(exc))
+
+
+def is_positive_browser_closed_fact(exc: BrowserTargetClosedError) -> bool:
+ """Only a measurement counts as death. The manager reports closed with no cause when a completed
+ connect's first roundtrip fails, and a native target-closed cause is the protocol saying the target
+ is gone. A failed connect wraps whatever the transport raised as the cause, and the copilot dials a
+ relay, so a refused or dropped connection says nothing about the browser behind it."""
+ causes = _exception_causes(exc)
+ if not causes:
+ return True
+ return any(_is_native_target_closed(cause) for cause in causes)
+
+
def _abandonable_browser_state_resolve(session_id: str, organization_id: str) -> asyncio.Task[BrowserState | None]:
"""A fresh determination per caller, owned by the module rather than by the awaiting task."""
task = asyncio.ensure_future(
@@ -1133,26 +1184,52 @@ async def resolve_persistent_browser_state(
try:
browser_state = await asyncio.shield(resolve)
except asyncio.CancelledError:
- _release_driver_attached_after_abandonment(resolve, session_id, organization_id)
+ _settle_abandoned_browser_state_resolve(resolve, session_id, organization_id, epoch_before_lookup)
raise
+ except Exception as exc:
+ positive = isinstance(exc, BrowserTargetClosedError) and is_positive_browser_closed_fact(exc)
+ # The manager answers closed once, then drops the handle: a closed report an earlier, abandoned
+ # lookup received is the only positive fact this ambiguous failure can carry.
+ if not _take_abandoned_closed_fact(session_id, epoch_before_lookup) and not positive:
+ raise
+ LOG.info(
+ "Persistent browser reported closed; treating the session as unreachable",
+ session_id=session_id,
+ organization_id=organization_id,
+ error_type=type(exc).__name__,
+ cause_types=[type(cause).__name__ for cause in _exception_causes(exc)],
+ )
+ browser_state = None
+ else:
+ _ABANDONED_CLOSED_FACTS.pop(session_id, None)
# A release that began while this lookup was out may have retired the generation it
# returned; the caller records synchronously after this returns, so re-issuing is enough.
if _DRIVER_RELEASE_EPOCHS.get(session_id, 0) == epoch_before_lookup:
return browser_state
-def _release_driver_attached_after_abandonment(
- resolve: asyncio.Task[BrowserState | None], session_id: str, organization_id: str
+def _take_abandoned_closed_fact(session_id: str, epoch: int) -> bool:
+ return _ABANDONED_CLOSED_FACTS.pop(session_id, None) == epoch
+
+
+def _settle_abandoned_browser_state_resolve(
+ resolve: asyncio.Task[BrowserState | None], session_id: str, organization_id: str, epoch: int
) -> None:
- """A caller cancelled mid-resolve never records what the shielded lookup went on to attach, so
- without this the driver it leaves in the pod's cache has no owner left to release it."""
+ """A caller cancelled mid-resolve never sees what the shielded lookup went on to find: without this
+ the driver it attached has no owner to release it, and a positive closed report is lost."""
def _release(finished: asyncio.Task[BrowserState | None]) -> None:
- if finished.cancelled() or finished.exception() is not None:
+ if finished.cancelled():
+ return
+ exc = finished.exception()
+ if exc is not None:
+ if isinstance(exc, BrowserTargetClosedError) and is_positive_browser_closed_fact(exc):
+ _ABANDONED_CLOSED_FACTS[session_id] = epoch
return
browser_state = finished.result()
if browser_state is None:
return
+ _ABANDONED_CLOSED_FACTS.pop(session_id, None)
_hold_attached_browser_driver(session_id, browser_state, new_holder=True)
start_browser_driver_release(organization_id, AttachedBrowserDriver(session_id, browser_state))
@@ -1296,11 +1373,43 @@ async def release_browser_driver_quietly(
)
-def retire_browser_session_id(ctx: AgentContext, examined_session_id: str | None) -> None:
- """Retire an id that a completed resolve found unusable, unless a concurrent call already
- replaced it — nulling a live replacement would discard the session this exists to protect."""
- if ctx.browser_session_id == examined_session_id:
- ctx.browser_session_id = None
+@asynccontextmanager
+async def browser_session_recovery(ctx: AgentContext) -> AsyncIterator[None]:
+ """Serialize every interactive browser-session mutation with source promotion.
+
+ Recovery transactions call lower mutation helpers recursively, so ownership is reentrant for
+ the current task while sibling tasks still wait on the one context lock.
+ """
+ task = asyncio.current_task()
+ if task is None:
+ raise RuntimeError("Browser session recovery requires an asyncio task")
+ lock = ctx.browser_session_recovery_lock
+ if ctx.browser_session_recovery_owner is task:
+ ctx.browser_session_recovery_depth += 1
+ try:
+ yield
+ finally:
+ ctx.browser_session_recovery_depth -= 1
+ return
+ async with lock:
+ ctx.browser_session_recovery_owner = task
+ ctx.browser_session_recovery_depth = 1
+ try:
+ yield
+ finally:
+ ctx.browser_session_recovery_depth = 0
+ ctx.browser_session_recovery_owner = None
+
+
+async def retire_browser_session_id(ctx: AgentContext, examined_session_id: str | None) -> None:
+ """Retire an unusable id at the browser-session mutation spine.
+
+ Compare-and-swap protects a concurrent replacement; the recovery scope protects source
+ promotion from any session mutation while exact validated bytes are being persisted.
+ """
+ async with browser_session_recovery(ctx):
+ if ctx.browser_session_id == examined_session_id:
+ ctx.browser_session_id = None
@asynccontextmanager
@@ -1375,7 +1484,7 @@ async def _mcp_browser_context_impl(
# structurally cannot get, so this is where a dead id gets retired. An unavailable
# connectivity signal is not that evidence, so the call fails but the id survives.
if retiring:
- retire_browser_session_id(ctx, browser_session_id)
+ await retire_browser_session_id(ctx, browser_session_id)
raise CopilotBrowserSessionUnavailable(browser_session_id)
raise CopilotBrowserLivenessUndetermined()
@@ -1581,7 +1690,7 @@ async def _drop_browser_session_id_at_its_fixed_deadline(ctx: AgentContext) -> N
)
# Stop using it, do not close it: the studio browser pane streams this same session, and it is
# going to be torn down on its own deadline within the minute either way.
- retire_browser_session_id(ctx, session_id)
+ await retire_browser_session_id(ctx, session_id)
def _build_test_connect_failure_result(failure: BuildTestConnectFailure) -> dict[str, Any]:
@@ -1711,7 +1820,7 @@ async def _provision_browser_session(ctx: AgentContext) -> BuildTestConnectFailu
except asyncio.CancelledError:
if session is not None:
await close_browser_session_quietly(ctx.organization_id, session.persistent_browser_session_id)
- retire_browser_session_id(ctx, installed_session_id)
+ await retire_browser_session_id(ctx, installed_session_id)
raise
except BrowserSessionCreditAdmissionRefusal:
return BuildTestConnectFailure(
@@ -1729,7 +1838,7 @@ async def _provision_browser_session(ctx: AgentContext) -> BuildTestConnectFailu
if session is not None:
await close_browser_session_quietly(ctx.organization_id, session.persistent_browser_session_id)
# Only clear an id this call installed; a sibling's session is not ours to drop.
- retire_browser_session_id(ctx, installed_session_id)
+ await retire_browser_session_id(ctx, installed_session_id)
# Detail stays in the log above (exc_info=True). The returned string
# flows back through the tool/agent path and could end up in
# LLM-visible or user-visible output, so strip raw exception text
@@ -1742,13 +1851,15 @@ async def _provision_browser_session(ctx: AgentContext) -> BuildTestConnectFailu
async def ensure_browser_session(ctx: AgentContext) -> dict[str, Any] | None:
- failure = await _provision_browser_session(ctx)
- return None if failure is None else _browser_session_acquisition_failure_result(failure)
+ async with browser_session_recovery(ctx):
+ failure = await _provision_browser_session(ctx)
+ return None if failure is None else _browser_session_acquisition_failure_result(failure)
async def ensure_build_test_browser_session(ctx: AgentContext) -> dict[str, Any] | None:
- failure = await _provision_browser_session(ctx)
- return None if failure is None else _build_test_connect_failure_result(failure)
+ async with browser_session_recovery(ctx):
+ failure = await _provision_browser_session(ctx)
+ return None if failure is None else _build_test_connect_failure_result(failure)
async def verify_browser_session_by_attaching(ctx: AgentContext) -> dict[str, Any] | None:
@@ -1766,7 +1877,7 @@ async def verify_browser_session_by_attaching(ctx: AgentContext) -> dict[str, An
await _attach_current_browser_generation(ctx)
return None
except CopilotBrowserSessionUnavailable:
- retire_browser_session_id(ctx, examined_session_id)
+ await retire_browser_session_id(ctx, examined_session_id)
return await ensure_browser_session(ctx)
except asyncio.CancelledError:
raise
@@ -1924,12 +2035,16 @@ async def verify_build_test_browser_session_by_attaching(
try:
await _attach_current_browser_generation(ctx)
except CopilotBrowserSessionUnavailable:
- retire_browser_session_id(ctx, examined_session_id)
+ await retire_browser_session_id(ctx, examined_session_id)
return _build_test_connect_failure_result(
BuildTestConnectFailure(state="already_closed", browser_session_id=examined_session_id)
)
- except BrowserTargetClosedError:
- retire_browser_session_id(ctx, examined_session_id)
+ except BrowserTargetClosedError as exc:
+ if not is_positive_browser_closed_fact(exc):
+ return _build_test_connect_failure_result(
+ BuildTestConnectFailure(state="cdp_connect_failed", browser_session_id=examined_session_id)
+ )
+ await retire_browser_session_id(ctx, examined_session_id)
return _build_test_connect_failure_result(
BuildTestConnectFailure(state="already_closed", browser_session_id=examined_session_id)
)
diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.py
index f73fcf218..0b4e0079b 100644
--- a/skyvern/forge/sdk/copilot/streaming_adapter.py
+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py
@@ -461,6 +461,7 @@ async def stream_to_sse(
code_diffs=code_diffs,
detail=detail,
workflow_run_id=_tool_result_workflow_run_id(tool_name, parsed),
+ executed_source_reference=_tool_result_executed_source_reference(tool_name, parsed),
timestamp=tool_result_ts,
)
)
@@ -569,6 +570,13 @@ def _tool_result_workflow_run_id(tool_name: str, parsed: dict[str, Any]) -> str
return run_id if isinstance(run_id, str) else None
+def _tool_result_executed_source_reference(tool_name: str, parsed: dict[str, Any]) -> str | None:
+ if tool_name != "run_browser_code":
+ return None
+ reference = parsed.get("executed_source_reference")
+ return reference if isinstance(reference, str) else None
+
+
async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: CopilotContext) -> None:
"""Emit the TOOL_RESULT frame for the goal-satisfying tool.
@@ -620,6 +628,7 @@ async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: Copil
parsed, tool_name=pending.tool_name, blocker_signal=blocker_signals, success=success
),
workflow_run_id=_tool_result_workflow_run_id(pending.tool_name, parsed),
+ executed_source_reference=_tool_result_executed_source_reference(pending.tool_name, parsed),
timestamp=flush_ts,
)
)
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 1759e1909..1f3f27b0e 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import asyncio
import json
import time
+from contextlib import nullcontext
+from dataclasses import asdict
from typing import Any
import structlog
@@ -44,6 +46,7 @@ from skyvern.forge.sdk.copilot.pending_operation import pending_operation
from skyvern.forge.sdk.copilot.runtime import (
SENSITIVE_ORIGIN_PAGE_ERROR,
bound_call_browser_session,
+ browser_session_recovery,
resolve_browser_state_for_context,
sensitive_origin_page_facts_withheld,
)
@@ -69,6 +72,7 @@ from skyvern.forge.sdk.copilot.workflow_yaml import (
add_block_to_workflow,
apply_block_edit,
delete_block_from_workflow,
+ stored_block_code,
stored_workflow_yaml,
)
@@ -96,7 +100,10 @@ from .blockers import _analyze_run_blocks as _analyze_run_blocks
from .blockers import _run_blocks_structured_blocker_message as _run_blocks_structured_blocker_message
from .blockers import _trusted_post_drain_status as _trusted_post_drain_status
from .browser_code import TOOL_NAME as BROWSER_CODE_TOOL_NAME
-from .browser_code import run_browser_code_tool
+from .browser_code import (
+ resolve_executed_browser_code_source,
+ run_browser_code_tool,
+)
from .completion import _build_run_evidence_snapshot as _build_run_evidence_snapshot
from .completion import _completion_verification_handler as _completion_verification_handler
from .completion import _is_outcome_evidence_candidate as _is_outcome_evidence_candidate
@@ -463,12 +470,13 @@ async def edit_block_tool(
async def edit_block_and_run_tool(
ctx: RunContextWrapper,
label: str,
- expected_code: str,
- replacement_code: str,
+ expected_code: str | None = None,
+ replacement_code: str | None = None,
+ executed_source_reference: str | None = None,
block_labels: list[str] | None = None,
parameters: dict[str, Any] | None = None,
) -> str:
- """Apply one anchored code edit and immediately test the affected frontier.
+ """Apply one exact code edit and immediately test the affected frontier.
Use this for a repair to an existing code block. ``label`` must name exactly one existing block,
and ``expected_code`` must occur exactly once in its current stored code — that is
@@ -478,6 +486,10 @@ async def edit_block_and_run_tool(
draft through the normal author-time safety boundary, then runs ``block_labels`` (or just
``label`` when omitted).
+ To promote code you already ran, pass ``executed_source_reference`` from a prior ``run_browser_code``
+ cell instead of ``expected_code`` and ``replacement_code``: that cell's complete source replaces the
+ block's code byte-for-byte. Pass exactly one of the two edit routes.
+
This is one model-invoked edit and one run. It does not choose an edit, create a block, retry, or
decide whether the result achieved the user's goal. Its response is the same sanitized run/debug
evidence returned by ``run_blocks_and_collect_debug``; a failed run still leaves the edited draft
@@ -491,22 +503,22 @@ async def edit_block_and_run_tool(
copilot_ctx = ctx.context
await await_pending_credential_pause(copilot_ctx)
copilot_ctx.completion_verification_result = None
- handler_start = time.monotonic()
+ # Cleared before any validation return, as update_and_run_blocks does, so a credential skip left by an
+ # earlier call is not reported as the reason this edit failed.
+ copilot_ctx.last_run_skipped_unbound_credentials = False
requested_labels = list(block_labels) if block_labels else [label]
runtime_parameters = parameters or {}
+ reference_route = executed_source_reference is not None
+ anchored_route = expected_code is not None or replacement_code is not None
arguments = {
"label": label,
"block_labels": requested_labels,
"parameters": runtime_parameters,
"has_code_edit": True,
+ "edit_source": "executed_source_reference" if reference_route else "anchored_replacement",
}
- skip_run_after_update = _update_and_run_requires_skipped_run(copilot_ctx, "edit_block_and_run")
- copilot_ctx.last_run_skipped_unbound_credentials = False
- if label not in requested_labels:
- result = {
- "ok": False,
- "error": f"block_labels must include the edited block {label!r} so this call tests the persisted repair.",
- }
+
+ def fail_before_run(result: dict[str, Any]) -> str:
_carry_unresolved_failure_into_result(copilot_ctx, result, "edit_block_and_run")
record_tool_step_result_for_ctx(copilot_ctx, "edit_block_and_run", arguments, result)
finalize_build_test_result(
@@ -516,38 +528,107 @@ async def edit_block_and_run_tool(
diagnosis_shadow_eligible=False,
)
return json.dumps(sanitize_tool_result_for_llm("edit_block_and_run", result))
+
+ if reference_route == anchored_route or (anchored_route and (expected_code is None or replacement_code is None)):
+ return fail_before_run(
+ {
+ "ok": False,
+ "error": (
+ "Pass exactly one edit source: executed_source_reference, or both expected_code and "
+ "replacement_code."
+ ),
+ "error_code": "invalid_edit_source",
+ }
+ )
+ if label not in requested_labels:
+ return fail_before_run(
+ {
+ "ok": False,
+ "error": (
+ f"block_labels must include the edited block {label!r} so this call tests the persisted repair."
+ ),
+ }
+ )
authority_error = _authority_tool_error(copilot_ctx, "edit_block_and_run")
if authority_error:
return _diagnosis_repair_tool_error(copilot_ctx, "edit_block_and_run", authority_error)
+ if executed_source_reference is not None:
+ resolution = resolve_executed_browser_code_source(copilot_ctx, executed_source_reference)
+ if resolution.status != "valid":
+ return fail_before_run(
+ {
+ "ok": False,
+ "error": (
+ f"The executed source reference is {resolution.status}. Run the complete candidate again "
+ "in this turn and browser session, then use its new reference."
+ ),
+ "error_code": "invalid_executed_source_reference",
+ "reference_status": resolution.status,
+ }
+ )
+
+ handler_start = time.monotonic()
+ skip_run_after_update = _update_and_run_requires_skipped_run(copilot_ctx, "edit_block_and_run")
_clear_pending_browser_interaction_observation(copilot_ctx)
+
try:
- workflow_yaml = apply_block_edit(
- _stored_workflow_yaml(copilot_ctx),
- label,
- expected_code=expected_code,
- replacement_code=replacement_code,
- )
+ if executed_source_reference is not None:
+ async with browser_session_recovery(copilot_ctx):
+ resolution = resolve_executed_browser_code_source(copilot_ctx, executed_source_reference)
+ if resolution.status != "valid" or resolution.source is None:
+ return fail_before_run(
+ {
+ "ok": False,
+ "error": (
+ f"The executed source reference became {resolution.status} before persistence. "
+ "Run the complete candidate again and use its new reference."
+ ),
+ "error_code": "invalid_executed_source_reference",
+ "reference_status": resolution.status,
+ }
+ )
+ stored_yaml = _stored_workflow_yaml(copilot_ctx)
+ current_code = stored_block_code(stored_yaml, label, allow_empty=True)
+ if current_code is None:
+ raise BlockEditError(f"Block {label!r} has no code to replace.")
+ workflow_yaml = apply_block_edit(
+ stored_yaml,
+ label,
+ expected_code=current_code,
+ replacement_code=resolution.source,
+ )
+ prior_definition = await _get_prior_workflow_definition(copilot_ctx)
+ with copilot_span("edit_block_and_run.update", data={"yaml_length": len(workflow_yaml)}):
+ update_result = await _update_workflow(
+ {
+ "workflow_yaml": workflow_yaml,
+ "_preserve_code_block_associations": True,
+ "_expected_exact_code_by_label": {label: resolution.source},
+ },
+ copilot_ctx,
+ allow_missing_credentials=skip_run_after_update,
+ originating_call_id=_originating_call_id(ctx),
+ )
+ _record_workflow_update_result(copilot_ctx, update_result, prior_definition)
+ else:
+ workflow_yaml = apply_block_edit(
+ _stored_workflow_yaml(copilot_ctx),
+ label,
+ expected_code=expected_code,
+ replacement_code=replacement_code,
+ )
+ prior_definition = await _get_prior_workflow_definition(copilot_ctx)
+ with copilot_span("edit_block_and_run.update", data={"yaml_length": len(workflow_yaml)}):
+ update_result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "_preserve_code_block_associations": True},
+ copilot_ctx,
+ allow_missing_credentials=skip_run_after_update,
+ originating_call_id=_originating_call_id(ctx),
+ )
+ _record_workflow_update_result(copilot_ctx, update_result, prior_definition)
except BlockEditError as exc:
- result = {"ok": False, "error": str(exc)}
- _carry_unresolved_failure_into_result(copilot_ctx, result, "edit_block_and_run")
- record_tool_step_result_for_ctx(copilot_ctx, "edit_block_and_run", arguments, result)
- finalize_build_test_result(
- copilot_ctx,
- source_tool="edit_block_and_run",
- result=result,
- )
- return json.dumps(sanitize_tool_result_for_llm("edit_block_and_run", result))
-
- prior_definition = await _get_prior_workflow_definition(copilot_ctx)
- with copilot_span("edit_block_and_run.update", data={"yaml_length": len(workflow_yaml)}):
- update_result = await _update_workflow(
- {"workflow_yaml": workflow_yaml, "_preserve_code_block_associations": True},
- copilot_ctx,
- allow_missing_credentials=skip_run_after_update,
- originating_call_id=_originating_call_id(ctx),
- )
- _record_workflow_update_result(copilot_ctx, update_result, prior_definition)
+ return fail_before_run({"ok": False, "error": str(exc)})
if not update_result.get("ok"):
_carry_unresolved_failure_into_result(copilot_ctx, update_result, "edit_block_and_run")
record_tool_step_result_for_ctx(copilot_ctx, "edit_block_and_run", arguments, update_result)
@@ -817,7 +898,9 @@ async def list_credentials_tool(
@function_tool(failure_error_function=copilot_tool_failure, name_override="request_credential")
-async def request_credential_tool(ctx: RunContextWrapper, login_page_url: str, reason: str) -> str:
+async def request_credential_tool(
+ ctx: RunContextWrapper, login_page_url: str, reason: str, credential_id: str | None = None
+) -> str:
"""Ask the user, in chat, to add or pick a saved credential for a sign-in page.
Use this instead of a prose question when a login still needs selection or setup, including
@@ -825,19 +908,21 @@ async def request_credential_tool(ctx: RunContextWrapper, login_page_url: str, r
workflow's binding, or an unambiguous website match without asking again when it can fill.
`login_page_url` is the absolute HTTP(S) sign-in URL shown on the card; selecting a credential
authorizes it for that site. `reason` is one sentence explaining why the login is needed.
+ Pass `credential_id` when that selected credential reached a verification-code step it has no
+ authenticator for, so the card asks the user to add one to it instead of picking a login.
The call waits for the user's answer and comes back `connected` with the credential
to bind, `skipped`, `unanswered`, or `unavailable` — follow the `next` or `fallback` it
- carries. One ask per turn.
+ carries. Each turn allows one ask to pick a login and one ask to add an authenticator.
"""
copilot_ctx = ctx.context
- arguments = {"login_page_url": login_page_url, "reason": reason}
+ arguments = {"login_page_url": login_page_url, "reason": reason, "credential_id": credential_id}
result: dict[str, Any] = {}
try:
authority_error = _authority_tool_error(copilot_ctx, "request_credential")
if authority_error:
result = {"ok": False, "error": authority_error}
else:
- result = await _request_credential(login_page_url, reason, copilot_ctx)
+ result = await _request_credential(login_page_url, reason, copilot_ctx, credential_id)
finally:
# A card on screen right now owns the gate; this call must not open it for one it never
# raised. Every other exit has to release, including a repeat ask in a later response.
@@ -936,6 +1021,32 @@ async def list_integrations_tool(ctx: RunContextWrapper) -> str:
return json.dumps(sanitized)
+@function_tool(failure_error_function=copilot_tool_failure, name_override="get_organization_usage_quota")
+async def get_organization_usage_quota_tool(ctx: RunContextWrapper) -> str:
+ """Read this organization's account usage when the user asks about usage, credits, quota, plan
+ or billing state: plan tier, current billing period, included credits, credits consumed,
+ credits remaining, top-up credits and overage status.
+
+ A null field means the account does not record it - report it as unavailable and point at
+ `billing_page_path`, never as zero.
+ """
+ copilot_ctx = ctx.context
+ arguments: dict[str, Any] = {}
+ authority_error = _authority_tool_error(copilot_ctx, "get_organization_usage_quota")
+ if authority_error:
+ result: dict[str, Any] = {"ok": False, "error": authority_error}
+ record_tool_step_result_for_ctx(copilot_ctx, "get_organization_usage_quota", arguments, result)
+ return json.dumps(result)
+
+ usage = await app.AGENT_FUNCTION.get_organization_usage_quota(
+ organization_id=copilot_ctx.organization_id,
+ )
+ result = {"ok": True, "data": asdict(usage)}
+ record_tool_step_result_for_ctx(copilot_ctx, "get_organization_usage_quota", arguments, result)
+ sanitized = sanitize_tool_result_for_llm("get_organization_usage_quota", result)
+ return json.dumps(sanitized)
+
+
@function_tool(
failure_error_function=copilot_tool_failure,
name_override="run_blocks_and_collect_debug",
@@ -1091,6 +1202,41 @@ async def get_run_results_tool(
return json.dumps(sanitized)
+def _promote_executed_sources(
+ copilot_ctx: CopilotContext, update_params: dict[str, Any], references: dict[str, str] | None
+) -> dict[str, Any] | None:
+ """Write each referenced cell's exact source into its block of the submitted YAML, or return the refusal."""
+ if not references:
+ return None
+ promoted: dict[str, str] = {}
+ workflow_yaml = update_params["workflow_yaml"]
+ for label, reference in references.items():
+ resolution = resolve_executed_browser_code_source(copilot_ctx, reference)
+ if resolution.status != "valid" or resolution.source is None:
+ return {
+ "ok": False,
+ "error": (
+ f"The executed source reference for block {label!r} is {resolution.status}. Run the complete "
+ "candidate again in this turn and browser session, then use its new reference."
+ ),
+ "error_code": "invalid_executed_source_reference",
+ "reference_status": resolution.status,
+ }
+ current_code = stored_block_code(workflow_yaml, label, allow_empty=True)
+ try:
+ if current_code is None:
+ raise BlockEditError(f"Block {label!r} is not a code block in workflow_yaml; give it an empty `code`.")
+ workflow_yaml = apply_block_edit(
+ workflow_yaml, label, expected_code=current_code, replacement_code=resolution.source
+ )
+ except BlockEditError as exc:
+ return {"ok": False, "error": str(exc)}
+ promoted[label] = resolution.source
+ update_params["workflow_yaml"] = workflow_yaml
+ update_params["_expected_exact_code_by_label"] = promoted
+ return None
+
+
@function_tool(
failure_error_function=copilot_tool_failure,
name_override="update_and_run_blocks",
@@ -1105,8 +1251,12 @@ async def update_and_run_blocks_tool(
block_observation_refs: list[BlockObservationRef] | None = None,
code_artifact_metadata: list[CodeArtifactMetadata] | None = None,
parameters: dict[str, Any] | None = None,
+ executed_source_references: dict[str, str] | None = None,
) -> Any:
"""Update the workflow YAML and immediately run the specified blocks in one step.
+ To save code you already ran with ``run_browser_code`` as a new block, map the block's label to that
+ cell's ``executed_source_reference`` in ``executed_source_references`` and leave the block's ``code``
+ empty: the cell's exact source becomes the block's code, so what gets tested is what you ran.
This persists the workflow and remotely executes the selected frontier, waiting for it to
finish, so it is materially higher latency than a bounded page read. It is the surface for
testing durable behaviour, and for reaching a state that only execution can establish --
@@ -1174,6 +1324,7 @@ async def update_and_run_blocks_tool(
"block_observation_refs": normalized_block_observation_refs,
"code_artifact_metadata": serialized_code_artifact_metadata,
"parameters": parameters or {},
+ "executed_source_labels": sorted(executed_source_references or {}),
}
skip_run_after_update = _update_and_run_requires_skipped_run(copilot_ctx, "update_and_run_blocks")
# Cleared unconditionally up front and only set True at the actual skip
@@ -1193,22 +1344,30 @@ async def update_and_run_blocks_tool(
prior_definition = await _get_prior_workflow_definition(copilot_ctx)
# Step 1: Update the workflow
- with copilot_span("update_workflow", data={"yaml_length": len(workflow_yaml)}):
- update_result = await _update_workflow(
- {
- "workflow_yaml": workflow_yaml,
- "block_observation_refs": normalized_block_observation_refs,
- "raw_block_observation_refs": block_observation_refs,
- "code_artifact_metadata": serialized_code_artifact_metadata,
- "raw_code_artifact_metadata": code_artifact_metadata,
- "block_labels": block_labels,
- "parameters": parameters or {},
- },
- copilot_ctx,
- allow_missing_credentials=skip_run_after_update,
- originating_call_id=_originating_call_id(ctx),
- )
- _record_workflow_update_result(copilot_ctx, update_result, prior_definition)
+ update_params: dict[str, Any] = {
+ "workflow_yaml": workflow_yaml,
+ "block_observation_refs": normalized_block_observation_refs,
+ "raw_block_observation_refs": block_observation_refs,
+ "code_artifact_metadata": serialized_code_artifact_metadata,
+ "raw_code_artifact_metadata": code_artifact_metadata,
+ "block_labels": block_labels,
+ "parameters": parameters or {},
+ }
+ # Held across the write like edit_block_and_run's promotion: a reference is only valid for the
+ # browser continuity it was minted in, and recovery must not change that between resolve and save.
+ async with browser_session_recovery(copilot_ctx) if executed_source_references else nullcontext():
+ promotion_error = _promote_executed_sources(copilot_ctx, update_params, executed_source_references)
+ if promotion_error is None:
+ with copilot_span("update_workflow", data={"yaml_length": len(update_params["workflow_yaml"])}):
+ update_result = await _update_workflow(
+ update_params,
+ copilot_ctx,
+ allow_missing_credentials=skip_run_after_update,
+ originating_call_id=_originating_call_id(ctx),
+ )
+ _record_workflow_update_result(copilot_ctx, update_result, prior_definition)
+ else:
+ update_result = promotion_error
if not update_result.get("ok"):
_carry_unresolved_failure_into_result(copilot_ctx, update_result, "update_and_run_blocks")
@@ -1606,6 +1765,8 @@ async def fill_credential_field_tool(
`candidate_login_credentials`, reuse an existing user or saved-workflow choice if present;
otherwise call `request_credential` for the sign-in URL and pass the selected `credential_id`.
`field` is one of `username`, `password`, `totp`.
+ If a `totp` fill reports the credential has no authenticator, call `request_credential` with that
+ `credential_id` so the user can add one.
`submit_selector` is optional and submits in the SAME call: pass the CSS
selector of the form's submit control and this tool clicks it once the fill
@@ -1736,6 +1897,7 @@ NATIVE_TOOLS = [
delete_block_tool,
list_credentials_tool,
list_integrations_tool,
+ get_organization_usage_quota_tool,
run_blocks_tool,
test_workflow_from_blank_browser_tool,
get_run_results_tool,
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
index c1eab8fa8..3b7ee7a65 100644
--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py
+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
@@ -137,9 +137,9 @@ _COPILOT_BLOCK_TYPE_POLICIES: dict[str, CopilotBlockPolicy] = {
_CODE_ONLY,
"page attachment of a declared file_url input",
(
- "Attach a declared file_url workflow parameter with "
- "await attach_authorized_file(page, <file_parameter>, <observed_selector>); exporting run files "
- "to external storage has no code-only route yet."
+ "Attach a declared file_url parameter or a claimed download with "
+ "await attach_authorized_file(page, <file_or_download>, <observed_selector>); exporting run files "
+ "has no code-only route yet."
),
),
}
@@ -332,7 +332,7 @@ def _code_only_browser_schema_guidance() -> list[str]:
_secret_credential_guidance(),
"The Code runtime provides await solve_captcha(page) for a platform-managed verification challenge observed while scouting; this is an available capability, not a required step for every login.",
"The Code runtime provides await clear_browser_data(page) when a site needs a clean session before it will sign in: it drops every cookie in the run's browser and all stored data for every origin it has a page or frame open on, and returns nothing. Read page.url first and navigate back to it afterwards. Browser settings pages (chrome://...) cannot be navigated to; this helper is the way to clear state. A workflow parameter named clear_browser_data shadows the helper in both executors. Before calling the helper in that case, rename the parameter to an unused name, preserve its value/default, and update its block bindings, code/template references, and caller-supplied run input keys.",
- "For file attachment: bind the file as a workflow parameter with workflow_parameter_type file_url, then call await attach_authorized_file(page, <file_parameter>, <observed_selector>). The parameter is a handle, not a path: pass it only to that helper. Attaching puts the file's contents in the page, where page scripts and page.evaluate can read them, so attach it only to the page that should receive it. It accepts only that run's materialized file, uploads at most 10 MB, and returns filename and size.",
+ "For file attachment: bind the file as a workflow parameter with workflow_parameter_type file_url, then call await attach_authorized_file(page, <file_parameter>, <observed_selector>). The parameter is a handle, not a path: pass it only to that helper. Attaching puts the file's contents in the page, where page scripts and page.evaluate can read them, so attach it only to the page that should receive it. It accepts only that run's materialized file, uploads at most 10 MB, and returns filename and size. To upload a file this block downloads, claim it with async with page.expect_download() as info: and pass await info.value to the same helper, never its path.",
]
diff --git a/skyvern/forge/sdk/copilot/tools/browser_code.py b/skyvern/forge/sdk/copilot/tools/browser_code.py
index 2257eb7f7..fef8c7c63 100644
--- a/skyvern/forge/sdk/copilot/tools/browser_code.py
+++ b/skyvern/forge/sdk/copilot/tools/browser_code.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import ast
import asyncio
+import hashlib
import json
import math
import uuid
@@ -24,11 +25,14 @@ from skyvern.forge.sdk.copilot.browser_code_contract import (
BrowserCodeOperation,
BrowserCodeSession,
BrowserCodeSessionUnavailableError,
+ ExecutedBrowserCodeSource,
+ ExecutedBrowserCodeSourceResolution,
)
from skyvern.forge.sdk.copilot.browser_target import (
BROWSER_TARGET_PARAM,
BROWSER_TARGET_PARAM_NAME,
BrowserSessionBinding,
+ last_run_facts,
resolve_browser_session_binding,
)
from skyvern.forge.sdk.copilot.enforcement import HARD_BACKSTOP_ALLOWANCE_SECONDS, TOTAL_TIMEOUT_SECONDS
@@ -50,6 +54,7 @@ from skyvern.forge.sdk.copilot.runtime import (
bound_call_browser_session,
browser_evidence_commit_lock,
browser_page_custody_lock,
+ browser_session_recovery,
clear_sensitive_origin_page_taint,
effective_browser_session_id,
mcp_browser_context,
@@ -58,6 +63,7 @@ from skyvern.forge.sdk.copilot.runtime import (
sensitive_origin_page_has_active_run,
sensitive_origin_page_is_tainted,
)
+from skyvern.webeye.browser_errors import BrowserAutomationError
from .guardrails import _authority_tool_error
from .scouting import _mark_pending_browser_interaction_observation, _record_scouted_interaction
@@ -82,8 +88,9 @@ stopped on needs 'last_run'; acting there changes that page and any submit it tr
Top-level `await` works. Variables, functions, and classes defined in one call stay available to later
run_browser_code calls in this chat turn. They are gone when the turn ends or when a result reports
-`session_restarted` or `session_ended`. The value of a final bare expression is returned as `value`;
-`print` output is returned as `stdout`.
+`session_restarted` or `session_ended`. Set `fresh_namespace` to true to run a complete candidate without
+globals or functions from earlier calls while keeping the current browser. The value of a final bare
+expression is returned as `value`; `print` output is returned as `stdout`.
Browser API (async, Playwright-shaped):
- `page` is the current tab. Locators: `page.locator(css)`, `page.get_by_role(role, name=...)`,
@@ -109,6 +116,8 @@ Browser API (async, Playwright-shaped):
Files belong to this chat turn.
- Saved credentials are not filled from here. Call `fill_credential_field` between calls to this tool,
with the same `target`; every call starts on the tab that tool acts on.
+- workbench-only, not valid in a saved block: `tabs`, `switch_tab`, `click_and_wait_for_popup`,
+ `click_and_download`, and `files`.
Not available: imports, names starting with `_`, event listeners (`page.on`, `expect_*`), cookies,
request interception, and new browser contexts. Using one returns an error that says so.
@@ -117,7 +126,13 @@ Every result lists the browser operations the call sent, in order. A failed call
the failing line, and the operations that already ran; nothing is retried. A call that exceeds
`timeout_seconds` (default 60, at most 300) or is cancelled stops the interpreter; when an operation
reached the browser without a reply, the result names it and the page must be read again before
-acting on its state.
+acting on its state. Every executed cell also returns an opaque `executed_source_reference` for the
+exact submitted bytes and observed outcome. Save a cell you ran as a block by passing its reference
+instead of retyping the code: `update_and_run_blocks` takes `executed_source_references` for a new
+block, and `edit_block_and_run` takes `executed_source_reference` for an existing one. A reference
+does not mean the code is correct, and the saved workflow run remains the final test. A top-level `return` ends the cell with
+that value, exactly as it ends a saved CodeBlock, so a complete candidate can be written the way the
+block should read and promoted unchanged.
Limits: code up to 20,000 characters; `value` up to 32,000 characters of JSON and `stdout` up to 16 KB,
cut beyond that, so return or print a summary; the first 50 operations are listed; a chat turn holds at
@@ -133,12 +148,104 @@ TOOL_SCHEMA: dict[str, Any] = {
"maximum": MAX_TIMEOUT_SECONDS,
"description": "Wall-clock limit for this call, in seconds.",
},
+ "fresh_namespace": {
+ "type": "boolean",
+ "description": "Start a new Python namespace for this complete candidate; the current browser remains.",
+ },
BROWSER_TARGET_PARAM_NAME: BROWSER_TARGET_PARAM,
},
"required": ["code"],
"additionalProperties": False,
}
+_EXECUTED_SOURCE_REFERENCE_PREFIX = "browser_code_source"
+
+
+def _source_owner_fingerprint(copilot_ctx: AgentContext) -> str:
+ owner = f"{copilot_ctx.organization_id}\0{copilot_ctx.workflow_permanent_id}"
+ return hashlib.sha256(owner.encode()).hexdigest()
+
+
+def retain_executed_browser_code_source(
+ copilot_ctx: AgentContext,
+ source: str,
+ cell: BrowserCodeCellResult,
+ *,
+ browser_session_id: str | None,
+ browser_session_generation: int,
+ last_run_workflow_run_id: str | None = None,
+) -> str:
+ host = copilot_ctx.browser_code_host
+ owner_fingerprint = _source_owner_fingerprint(copilot_ctx)
+ reference = ":".join(
+ (
+ _EXECUTED_SOURCE_REFERENCE_PREFIX,
+ owner_fingerprint,
+ host.source_turn_token,
+ str(browser_session_generation),
+ uuid.uuid4().hex,
+ )
+ )
+ host.executed_sources[reference] = ExecutedBrowserCodeSource(
+ source=source,
+ execution_ok=cell.ok,
+ execution_error_code=cell.error_code,
+ owner_fingerprint=owner_fingerprint,
+ turn_token=host.source_turn_token,
+ browser_session_id=browser_session_id,
+ browser_session_generation=browser_session_generation,
+ last_run_workflow_run_id=last_run_workflow_run_id,
+ )
+ return reference
+
+
+def resolve_executed_browser_code_source(
+ copilot_ctx: AgentContext, reference: str
+) -> ExecutedBrowserCodeSourceResolution:
+ parts = reference.split(":")
+ if len(parts) != 5 or parts[0] != _EXECUTED_SOURCE_REFERENCE_PREFIX:
+ return ExecutedBrowserCodeSourceResolution(status="missing")
+ _, owner_fingerprint, turn_token, generation, _nonce = parts
+ host = copilot_ctx.browser_code_host
+ if owner_fingerprint != _source_owner_fingerprint(copilot_ctx):
+ return ExecutedBrowserCodeSourceResolution(status="wrong_owner")
+ if turn_token != host.source_turn_token:
+ return ExecutedBrowserCodeSourceResolution(status="wrong_turn")
+ if reference in host.expired_source_references:
+ return ExecutedBrowserCodeSourceResolution(status="expired")
+ retained = host.executed_sources.get(reference)
+ if retained is None:
+ return ExecutedBrowserCodeSourceResolution(status="missing")
+ if retained.owner_fingerprint != owner_fingerprint:
+ return ExecutedBrowserCodeSourceResolution(status="wrong_owner")
+ if retained.turn_token != turn_token:
+ return ExecutedBrowserCodeSourceResolution(status="wrong_turn")
+ if retained.last_run_workflow_run_id is not None:
+ # A last-run cell is pinned to that run's browser, not the chat's, so it is checked against the
+ # run it was pinned to; the chat's continuity generation does not apply to it.
+ if copilot_ctx.last_run_blocks_workflow_run_id != retained.last_run_workflow_run_id:
+ return ExecutedBrowserCodeSourceResolution(status="wrong_session")
+ expected_generation = 0
+ expected_session_id = copilot_ctx.last_run_blocks_browser_session_id
+ else:
+ expected_generation = copilot_ctx.browser_session_continuity_generation
+ expected_session_id = effective_browser_session_id(copilot_ctx)
+ if generation != str(expected_generation) or retained.browser_session_generation != expected_generation:
+ return ExecutedBrowserCodeSourceResolution(status="wrong_generation")
+ if retained.browser_session_id != expected_session_id:
+ return ExecutedBrowserCodeSourceResolution(status="wrong_session")
+ return ExecutedBrowserCodeSourceResolution(
+ status="valid",
+ source=retained.source,
+ execution_ok=retained.execution_ok,
+ execution_error_code=retained.execution_error_code,
+ )
+
+
+def expire_executed_browser_code_sources(host: BrowserCodeHost) -> None:
+ host.expired_source_references.update(host.executed_sources)
+ host.executed_sources.clear()
+
SENSITIVE_ORIGIN_RECOVERY_HINT = (
' On this surface that navigation is a cell containing only `await page.goto("<url>")`; it returns the'
@@ -258,18 +365,23 @@ def _take_interruption_note(host: BrowserCodeHost) -> dict[str, Any]:
async def _discard_session(host: BrowserCodeHost) -> None:
- session, host.session = host.session, None
+ session = host.session
if session is None:
return
LOG.info("Copilot browser code session closing", browser_code_session_id=session.session_id)
try:
await session.close()
+ except asyncio.CancelledError:
+ # Keep the session reachable so turn-final cleanup can retry an interrupted close.
+ raise
except Exception:
LOG.warning(
"Failed to close the copilot browser code session",
browser_code_session_id=session.session_id,
exc_info=True,
)
+ if host.session is session:
+ host.session = None
async def _session_for_page(
@@ -383,12 +495,36 @@ def _record_outcome(
async def run_browser_code(
- copilot_ctx: AgentContext, code: object, timeout_seconds: object = None, target: object = None
+ copilot_ctx: AgentContext,
+ code: object,
+ timeout_seconds: object = None,
+ fresh_namespace: bool = False,
+ target: object = None,
) -> dict[str, Any]:
- arguments: dict[str, Any] = {"code": code, "timeout_seconds": timeout_seconds, BROWSER_TARGET_PARAM_NAME: target}
+ arguments: dict[str, Any] = {
+ "code": code,
+ "timeout_seconds": timeout_seconds,
+ "fresh_namespace": fresh_namespace,
+ BROWSER_TARGET_PARAM_NAME: target,
+ }
def finish(result: dict[str, Any]) -> dict[str, Any]:
- scrubbed = scrub_model_facing_tool_result(copilot_ctx, result)
+ source_reference = result.get("executed_source_reference")
+ retained_reference = (
+ source_reference
+ if isinstance(source_reference, str) and source_reference in copilot_ctx.browser_code_host.executed_sources
+ else None
+ )
+ result_to_scrub = (
+ {key: value for key, value in result.items() if key != "executed_source_reference"}
+ if retained_reference is not None
+ else result
+ )
+ scrubbed = scrub_model_facing_tool_result(copilot_ctx, result_to_scrub)
+ if retained_reference is not None:
+ # This server-generated capability is not derived from credential data. Scrubbing a coincidental
+ # secret substring would corrupt the lookup key and make exact-source promotion impossible.
+ scrubbed["executed_source_reference"] = retained_reference
record_tool_step_result_for_ctx(copilot_ctx, TOOL_NAME, arguments, scrubbed)
return scrubbed
@@ -399,6 +535,8 @@ async def run_browser_code(
return finish({"ok": False, "error": "code must be non-empty Python source."})
if len(code) > MAX_CODE_CHARS:
return finish({"ok": False, "error": f"code is limited to {MAX_CODE_CHARS} characters."})
+ if not isinstance(fresh_namespace, bool):
+ return finish({"ok": False, "error": "fresh_namespace must be true or false."})
timeout = _timeout_seconds(timeout_seconds)
if timeout is None:
return finish(
@@ -410,7 +548,7 @@ async def run_browser_code(
# The binding scopes everything below: preparation, the lease, the page lookup and the
# interpreter all read the targeted browser rather than the chat's.
with bound_call_browser_session(binding.session_id_override):
- return await _run_bound_cell(copilot_ctx, code, timeout, finish, binding)
+ return await _run_bound_cell(copilot_ctx, code, timeout, finish, binding, fresh_namespace)
async def _run_bound_cell(
@@ -419,7 +557,9 @@ async def _run_bound_cell(
timeout: float,
finish: Callable[[dict[str, Any]], dict[str, Any]],
binding: BrowserSessionBinding,
+ fresh_namespace: bool,
) -> dict[str, Any]:
+ call_browser_session_id = binding.session_id_for(copilot_ctx)
err, continuity_result, _disposition = await _prepare_browser_session_for_dispatch(
copilot_ctx,
tool_name=TOOL_NAME,
@@ -428,7 +568,7 @@ async def _run_bound_cell(
)
session_failure = err if err is not None else continuity_result
if session_failure is not None:
- return finish(session_failure)
+ return finish({**session_failure, **last_run_facts(copilot_ctx, call_browser_session_id)})
host = copilot_ctx.browser_code_host
# The same three, in the same order, as the direct credential fill takes. No cell fills a credential
# any more, but that tool types into this browser between calls, and these are what stop a cell
@@ -438,8 +578,10 @@ async def _run_bound_cell(
copilot_ctx.credential_fill_lock,
browser_page_custody_lock(copilot_ctx),
browser_evidence_commit_lock(copilot_ctx),
+ browser_session_recovery(copilot_ctx),
):
notes = _take_interruption_note(host)
+ session_to_reset = host.session if fresh_namespace else None
run_id = copilot_ctx.last_run_blocks_workflow_run_id
recovering = False
if sensitive_origin_page_facts_withheld(copilot_ctx, run_id):
@@ -460,10 +602,12 @@ async def _run_bound_cell(
# another browser does not follow it, so a debug re-establishment must not rebind that cell's
# interpreter; a real tab change there is still caught by the page identity check.
generation = copilot_ctx.browser_session_continuity_generation if binding.session_id_override is None else 0
+ entered_browser = False
try:
# The lease is held for the whole cell so a browser retirement cancels it the way it cancels a
# direct tool, instead of letting the cell act on a closing browser for up to its timeout.
async with mcp_browser_context(copilot_ctx, session_id_override=binding.session_id_override):
+ entered_browser = True
current_page, _browser_context = await get_page(session_id=browser_session_id)
session = await _session_for_page(
copilot_ctx,
@@ -472,6 +616,23 @@ async def _run_bound_cell(
generation=generation,
notes=notes,
)
+ # Replacing the browser opens a new interpreter in _session_for_page. It already has
+ # a fresh namespace, so only reset the exact session that existed when this call began.
+ if session_to_reset is not None and session is session_to_reset:
+ try:
+ await session.reset_namespace()
+ except asyncio.CancelledError:
+ host.interrupted = True
+ # Reset dispatches no browser operation. Reusing the prior cell's last operation here
+ # would report that already-completed effect as part of this cancelled call.
+ host.interrupted_operation = None
+ await asyncio.shield(_discard_session(host))
+ raise
+ except BrowserCodeSessionUnavailableError:
+ await _discard_session(host)
+ raise
+ if fresh_namespace:
+ notes["fresh_namespace"] = "this call started a new interpreter; earlier Python values are absent"
# A page this turn visited a sensitive origin on stays tainted after its facts stop
# being withheld. Scrubbing works on values, and pixels are not values, so a cell that
# can screenshot it can carry the page out of here a chunk at a time.
@@ -491,12 +652,50 @@ async def _run_bound_cell(
copilot_ctx, exc, tool_name=TOOL_NAME, call_path="model"
)
return finish(
- _browser_session_loss_result(
- dict(notes),
- disposition=disposition,
- deadline_expired=copilot_ctx.browser_session_continuity_deadline_expired,
- )
+ {
+ **_browser_session_loss_result(
+ dict(notes),
+ disposition=disposition,
+ deadline_expired=copilot_ctx.browser_session_continuity_deadline_expired,
+ ),
+ **last_run_facts(copilot_ctx, call_browser_session_id),
+ }
+ )
+ except Exception as exc:
+ if entered_browser:
+ raise
+ # Only a classified error's message has been through CDP-endpoint redaction; an
+ # unclassified one is named by type, and its text stays in the log.
+ detail = (str(exc).rstrip(".") if isinstance(exc, BrowserAutomationError) else "") or type(exc).__name__
+ LOG.warning(
+ "Browser-code cell could not enter its browser",
+ browser_session_id=call_browser_session_id,
+ error_type=type(exc).__name__,
+ error=str(exc),
)
+ return finish(
+ {
+ "ok": False,
+ "error": (
+ f"{TOOL_NAME} could not reach its browser: {detail}. "
+ "The cell was never sent to the browser, so it had no effect."
+ ),
+ "browser_session_id": call_browser_session_id,
+ **binding.provenance(),
+ **notes,
+ **last_run_facts(copilot_ctx, call_browser_session_id),
+ }
+ )
+ source_reference = retain_executed_browser_code_source(
+ copilot_ctx,
+ code,
+ cell,
+ browser_session_id=browser_session_id,
+ browser_session_generation=generation,
+ last_run_workflow_run_id=(
+ copilot_ctx.last_run_blocks_workflow_run_id if binding.session_id_override is not None else None
+ ),
+ )
if cell.interpreter_restarted:
# The host this call holds is unchanged, so a restart on the far side is invisible here
# unless it is said. Claiming a continuity the interpreter cannot honour is the failure.
@@ -537,6 +736,7 @@ async def _run_bound_cell(
"ok": False,
"error": SENSITIVE_ORIGIN_PAGE_ERROR + SENSITIVE_ORIGIN_RECOVERY_HINT,
"operations_sent": operations_sent,
+ "executed_source_reference": source_reference,
**notes,
}
)
@@ -544,13 +744,19 @@ async def _run_bound_cell(
# On the replace surface no other tool navigates, so without this a finished run's taint
# denies pixels on this browser for the rest of the chat.
clear_sensitive_origin_page_taint(copilot_ctx)
- result = finish({**_cell_payload(cell), **notes, **binding.provenance()})
+ result = finish(
+ {**_cell_payload(cell), "executed_source_reference": source_reference, **notes, **binding.provenance()}
+ )
_record_outcome(copilot_ctx, cell, result, browser_session_id=browser_session_id, generation=generation)
return result
async def close_browser_code_session(copilot_ctx: AgentContext) -> None:
- await _discard_session(copilot_ctx.browser_code_host)
+ host = copilot_ctx.browser_code_host
+ try:
+ await _discard_session(host)
+ finally:
+ expire_executed_browser_code_sources(host)
async def _run_browser_code_invoke(ctx: RunContextWrapper, arguments: str) -> str:
@@ -561,7 +767,11 @@ async def _run_browser_code_invoke(ctx: RunContextWrapper, arguments: str) -> st
if not isinstance(parsed, dict):
parsed = {}
result = await run_browser_code(
- ctx.context, parsed.get("code"), parsed.get("timeout_seconds"), parsed.get(BROWSER_TARGET_PARAM_NAME)
+ ctx.context,
+ parsed.get("code"),
+ parsed.get("timeout_seconds"),
+ parsed.get("fresh_namespace", False),
+ parsed.get(BROWSER_TARGET_PARAM_NAME),
)
return json.dumps(result, default=str)
diff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.py
index 02b94a06f..bac88a358 100644
--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py
+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py
@@ -6,17 +6,27 @@ from collections.abc import Awaitable, Callable
from copy import deepcopy
from dataclasses import dataclass
from dataclasses import field as dataclass_field
-from typing import TYPE_CHECKING, Any
+from dataclasses import replace
+from functools import partial
+from typing import TYPE_CHECKING, Any, Literal
+from urllib.parse import urlsplit, urlunsplit
import structlog
from skyvern.cli.core.session_manager import get_page
from skyvern.forge import app
from skyvern.forge.sdk.browser_action_policy import canonicalize_origin
-from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
+from skyvern.forge.sdk.copilot.blocker_signal import (
+ CREDENTIAL_ORIGIN_RECOVERY_DECLINED_REASON_CODE,
+ CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE,
+ CopilotToolBlockerSignal,
+ clear_tool_blocker_signals_for_reason_codes,
+)
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.credential_fill_fields import CREDENTIAL_FILL_FIELDS
from skyvern.forge.sdk.copilot.credential_pause import (
+ CredentialPauseResolution,
credential_pause_transport_ready,
defang_card_text,
request_credential_pause,
@@ -35,6 +45,8 @@ from skyvern.forge.sdk.copilot.request_policy import (
from skyvern.forge.sdk.copilot.runtime import (
SENSITIVE_ORIGIN_PAGE_ERROR,
AgentContext,
+ CredentialOriginDeclineStatus,
+ CredentialOriginRecovery,
ScoutedSelectorCandidate,
browser_evidence_commit_lock,
browser_page_custody_lock,
@@ -49,9 +61,10 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
scrub_secrets_from_text,
)
from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_credential_origins
-from skyvern.forge.sdk.credential_site_policy import same_site
+from skyvern.forge.sdk.credential_site_policy import same_release_scope, same_site
from skyvern.forge.sdk.schemas.credentials import (
Credential,
+ CredentialItem,
CredentialType,
CredentialVaultType,
PasswordCredential,
@@ -60,6 +73,7 @@ from skyvern.forge.sdk.schemas.credentials import (
from skyvern.forge.sdk.services.credentials import generate_totp_code, normalize_totp_config
from skyvern.webeye.utils.dom import is_post_dispatch_click_timeout
+from ._shared import _emit_tool_blocker_signal
from .banned_blocks import _copilot_block_authoring_policy
from .credentials import _missing_credential_reference_tool_error
from .guardrails import _authority_tool_error
@@ -194,7 +208,9 @@ def _within_grant(current_url: str | None, grant: _CredentialFillOriginGrant) ->
class _CredentialFillOriginMismatchError(Exception):
- pass
+ def __init__(self, target_url: str | None) -> None:
+ super().__init__()
+ self.target_url = target_url
def _credential_fill_origin_mismatch_error() -> str:
@@ -204,6 +220,91 @@ def _credential_fill_origin_mismatch_error() -> str:
)
+def _credential_origin_declined_text(origin: str) -> str:
+ return (
+ f"No login authorized for {origin} was connected, and the saved login will not be released on that site. "
+ f"Tell the user the sign-in on {origin} needs its own saved login."
+ )
+
+
+def _credential_origin_recovery_error(recovery: CredentialOriginRecovery) -> str:
+ if recovery.state == "declined":
+ return _credential_origin_declined_text(recovery.origin)
+ return (
+ f"The sign-in continues on {recovery.origin}, which the selected credential is not authorized for. "
+ f"Connect a login for {recovery.origin} through request_credential."
+ )
+
+
+def _start_credential_origin_recovery(copilot_ctx: AgentContext, origin: str, credential_id: str) -> dict[str, Any]:
+ current = copilot_ctx.credential_origin_recovery
+ if current is not None and (current.state != "pending" or current.origin != origin):
+ return {"ok": False, "error": _credential_origin_recovery_error(current)}
+ copilot_ctx.credential_origin_recovery = current or CredentialOriginRecovery(origin, "pending", credential_id)
+ steering = _emit_tool_blocker_signal(
+ copilot_ctx,
+ CopilotToolBlockerSignal(
+ blocker_kind="authority_denied",
+ blocked_tool="fill_credential_field",
+ internal_reason_code=CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE,
+ agent_steering_text=(
+ f"Nothing was filled: this credential is not authorized for {origin}, where this sign-in field is. "
+ f"Call request_credential with the sign-in page URL on {origin} so the user can connect a login "
+ "for that site before testing the workflow."
+ ),
+ user_facing_reason=f"The sign-in continues on {origin}, which this saved login is not authorized for.",
+ recovery_hint="ask_user_clarifying",
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ extra={"observed_origin": origin},
+ ),
+ )
+ return {
+ "ok": False,
+ "error": steering,
+ "recovery": {"observed_origin": origin, "next_action": "request_credential"},
+ }
+
+
+def _decline_credential_origin_recovery(
+ copilot_ctx: AgentContext, recovery: CredentialOriginRecovery, status: CredentialOriginDeclineStatus
+) -> dict[str, Any]:
+ origin = recovery.origin
+ copilot_ctx.credential_origin_recovery = replace(recovery, state="declined")
+ clear_tool_blocker_signals_for_reason_codes(
+ copilot_ctx, frozenset({CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE})
+ )
+ declined = CopilotToolBlockerSignal(
+ blocker_kind="authority_denied",
+ blocked_tool="request_credential",
+ internal_reason_code=CREDENTIAL_ORIGIN_RECOVERY_DECLINED_REASON_CODE,
+ agent_steering_text=_credential_origin_declined_text(origin),
+ user_facing_reason=(
+ f"The sign-in continues on {origin}, and no saved login authorized for that site was connected. "
+ f"Add a login for {origin} and ask me again."
+ ),
+ recovery_hint="report_blocker_to_user",
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ extra={"observed_origin": origin},
+ )
+ _emit_tool_blocker_signal(copilot_ctx, declined)
+ return {"ok": True, "status": status, "next": _credential_origin_declined_text(origin)}
+
+
+async def _credential_evidence_admits_origin(
+ copilot_ctx: AgentContext, recovery: CredentialOriginRecovery, credential: Credential
+) -> bool:
+ """Whether the credential itself places it on the recovery origin, and nowhere else."""
+ if credential.credential_id == recovery.refused_credential_id:
+ return False
+ vault_sites = await _read_vault_named_sites(copilot_ctx, credential.credential_id)
+ if vault_sites is None:
+ return False
+ evidence = ([credential.tested_url] if credential.tested_url else []) + vault_sites
+ return bool(evidence) and all(same_release_scope(url, recovery.origin) for url in evidence)
+
+
def _credential_submit_origin_mismatch_notice() -> str:
return (
"The field was filled, but the browser left this credential's login origin before the submit "
@@ -269,7 +370,7 @@ def _credential_fill_release_guard(grant: _CredentialFillOriginGrant) -> Callabl
def guard(target_url: str | None) -> None:
if not _within_grant(target_url, grant):
- raise _CredentialFillOriginMismatchError
+ raise _CredentialFillOriginMismatchError(target_url)
return guard
@@ -306,12 +407,11 @@ def _resolved_credential_intended_url(policy: RequestPolicy, credential_id: str)
async def _vault_named_sites(copilot_ctx: AgentContext, credential_id: str) -> list[str]:
- """The sites this credential's own vault entry names, as the user saved them.
+ return await _read_vault_named_sites(copilot_ctx, credential_id) or []
- Read straight from the vault rather than the DB row, so a credential nobody has run the test flow
- against still knows where it belongs. Only Bitwarden items carry these; the other vaults store no
- URL for an item, so their credentials fall through to the request-grounded route below.
- """
+
+async def _read_vault_named_sites(copilot_ctx: AgentContext, credential_id: str) -> list[str] | None:
+ """Sites the credential's own vault entry names (only Bitwarden items carry any), or None when the read failed."""
cached = copilot_ctx.vault_login_uris_by_credential_id.get(credential_id)
if cached is not None:
return cached
@@ -328,7 +428,7 @@ async def _vault_named_sites(copilot_ctx: AgentContext, credential_id: str) -> l
# Not cached: a vault read that failed once says nothing about where the credential belongs,
# and caching the empty answer would refuse every later fill this turn for a transient fault.
LOG.info("copilot could not read the vault entry's sites", credential_id=credential_id, exc_info=True)
- return []
+ return None
copilot_ctx.vault_login_uris_by_credential_id[credential_id] = uris
return uris
@@ -385,46 +485,182 @@ _CREDENTIAL_CARD_FALLBACK = (
)
-async def _request_credential(login_page_url: str, reason: str, copilot_ctx: CopilotContext) -> dict[str, Any]:
+def _missing_totp_card_fallback(credential_name: str) -> str:
+ return (
+ f"Ask the user in prose to edit the saved credential {defang_card_text(credential_name)} on the "
+ "Credentials page and add its authenticator (2FA), then say when it is done. Never ask for the "
+ "authenticator secret or a code in chat."
+ )
+
+
+def _password_totp_method(credential: PasswordCredential) -> Literal["authenticator", "out_of_band", "none"]:
+ if credential.totp:
+ return "authenticator"
+ # A saved OTP identifier means the code is delivered out-of-band; only runtime polling has the
+ # run/task context needed to resolve it.
+ if credential.totp_identifier or credential.totp_type in {TotpType.EMAIL, TotpType.TEXT}:
+ return "out_of_band"
+ return "none"
+
+
+async def _missing_totp_ask_target(
+ copilot_ctx: CopilotContext, credential_id: str
+) -> tuple[str | None, dict[str, Any] | None]:
+ """The credential's saved name when it has no one-time-code method at all, else the tool result."""
+ authority_error = _credential_fill_authority_error(copilot_ctx, credential_id)
+ if authority_error:
+ return None, {"ok": False, "error": authority_error}
+ credential_item, load_error = await _load_vault_credential_item(copilot_ctx, credential_id)
+ if credential_item is None:
+ return None, {"ok": False, "error": load_error}
+ credential = credential_item.credential
+ if not isinstance(credential, PasswordCredential):
+ return None, {"ok": False, "error": f"Credential `{credential_id}` is not a username/password credential."}
+ method = _password_totp_method(credential)
+ if method == "authenticator":
+ return None, {
+ "ok": True,
+ "status": "has_code_method",
+ "method": "authenticator",
+ "next": (
+ f"Fill the code with `fill_credential_field` field=totp for `{credential_id}`, passing the "
+ "same `target` that reached the verification step."
+ ),
+ }
+ if method == "out_of_band":
+ return None, {
+ "ok": True,
+ "status": "has_code_method",
+ "method": "email_or_text",
+ "next": _runtime_otp_steering_error(credential_id),
+ }
+ return credential_item.name, None
+
+
+def _log_credential_card_unavailable(copilot_ctx: CopilotContext, config: CopilotConfig | None) -> None:
+ LOG.info(
+ "copilot_credential_card_unavailable",
+ flag_enabled=config is not None and config.credential_pause_enabled,
+ client_supports=copilot_ctx.client_supports_credential_pause,
+ shared_cache=getattr(getattr(app, "CACHE", None), "is_shared", False),
+ )
+
+
+async def _request_credential(
+ login_page_url: str, reason: str, copilot_ctx: CopilotContext, credential_id: str | None = None
+) -> dict[str, Any]:
policy = copilot_ctx.request_policy
if not isinstance(policy, RequestPolicy) or policy.raw_secret_detected:
return {"ok": False, "error": "Credential selection is unavailable on a raw-secret or ungrounded turn."}
- if not is_resolved_page_url(login_page_url) or canonicalize_origin(login_page_url) is None:
+ ask_origin = canonicalize_origin(login_page_url)
+ if not is_resolved_page_url(login_page_url) or ask_origin is None:
return {"ok": False, "error": "Provide the absolute HTTP(S) sign-in page URL for the credential card."}
- if copilot_ctx.credential_pause_used:
- return {
+ recovery_open = copilot_ctx.credential_origin_recovery
+ # The authenticator update card grants no origin, so it has its own latch and never spends the recovery's.
+ recovery = (
+ recovery_open
+ if not credential_id
+ and recovery_open is not None
+ and recovery_open.state == "pending"
+ and ask_origin.canonical == recovery_open.origin
+ else None
+ )
+ # The spent card, if any, asked for a different site; this ask has a refused fill behind it.
+ handback = recovery is not None and recovery.origin not in copilot_ctx.credential_origin_recovery_carded
+
+ missing_totp_name: str | None = None
+ if credential_id:
+ missing_totp_name, early_result = await _missing_totp_ask_target(copilot_ctx, credential_id)
+ if early_result is not None:
+ return early_result
+ update_ask = missing_totp_name is not None
+
+ # The update ask awaits the vault above, so a card raised meanwhile by a parallel call must still win.
+ already_asked = copilot_ctx.credential_ask_in_flight or (
+ copilot_ctx.credential_totp_update_asked if update_ask else copilot_ctx.credential_pause_used and not handback
+ )
+ if already_asked and (recovery is None or copilot_ctx.credential_ask_in_flight):
+ already: dict[str, Any] = {
"ok": True,
"status": "already_asked",
- "outcome": copilot_ctx.credential_pause_outcome or "unanswered",
"next": "Continue without re-asking this turn.",
}
+ # The outcome belongs to the pick card; the update card keeps none.
+ if missing_totp_name is None:
+ already["outcome"] = copilot_ctx.credential_pause_outcome or "unanswered"
+ return already
config = copilot_ctx.copilot_config
- if config is None or not credential_pause_transport_ready(copilot_ctx, config):
- LOG.info(
- "copilot_credential_card_unavailable",
- flag_enabled=config is not None and config.credential_pause_enabled,
- client_supports=copilot_ctx.client_supports_credential_pause,
- shared_cache=getattr(getattr(app, "CACHE", None), "is_shared", False),
- )
+ if config is None or not credential_pause_transport_ready(
+ copilot_ctx, config, allow_second_ask=update_ask or handback
+ ):
+ if recovery is not None and not handback:
+ return _decline_credential_origin_recovery(copilot_ctx, recovery, "already_asked")
+ _log_credential_card_unavailable(copilot_ctx, config)
+ if recovery is not None:
+ return _decline_credential_origin_recovery(copilot_ctx, recovery, "unavailable")
return {
"ok": True,
"status": "unavailable",
"detail": "The in-chat credential card cannot be shown on this turn.",
- "fallback": _CREDENTIAL_CARD_FALLBACK,
+ "fallback": (
+ _missing_totp_card_fallback(missing_totp_name)
+ if missing_totp_name is not None
+ else _CREDENTIAL_CARD_FALLBACK
+ ),
}
- policy.credential_ask_login_page_urls = [login_page_url]
- resolution = await request_credential_pause(
- copilot_ctx,
- login_page_url=login_page_url,
- message=defang_card_text(reason),
- stream=copilot_ctx.stream,
- copilot_config=config,
- )
+ admit_connected = None
+ if recovery is not None:
+ login_page_url = urlunsplit(urlsplit(login_page_url)._replace(query="", fragment=""))
+ copilot_ctx.credential_origin_recovery = replace(recovery, state="asked")
+ copilot_ctx.credential_origin_recovery_carded.add(recovery.origin)
+ admit_connected = partial(_credential_evidence_admits_origin, copilot_ctx, recovery)
+ named_before_ask = set(policy.current_turn_named_credential_ids)
+ if missing_totp_name is None:
+ policy.credential_ask_login_page_urls = [login_page_url]
+ try:
+ resolution = await request_credential_pause(
+ copilot_ctx,
+ login_page_url=login_page_url,
+ message=defang_card_text(reason),
+ stream=copilot_ctx.stream,
+ copilot_config=config,
+ missing_totp_credential_id=credential_id if missing_totp_name is not None else None,
+ admit_connected=admit_connected,
+ allow_second_ask=handback,
+ )
+ except BaseException:
+ if recovery is not None:
+ _decline_credential_origin_recovery(copilot_ctx, recovery, "error")
+ raise
credential = resolution.credential if resolution is not None else None
- if resolution is None or (resolution.action == "connected" and credential is None):
+ if missing_totp_name is not None:
+ return await _missing_totp_ask_outcome(copilot_ctx, credential, missing_totp_name, answered=resolution)
+ if recovery is not None:
+ bound_origin = (
+ canonicalize_origin(policy.live_page_admitted_urls.get(credential.credential_id))
+ if credential is not None and copilot_ctx.credential_pause_outcome == "connected"
+ else None
+ )
+ if bound_origin is None or bound_origin.canonical != recovery.origin:
+ status: CredentialOriginDeclineStatus
+ if resolution is None:
+ status = "unanswered"
+ elif resolution.action == "skip":
+ status = "skipped"
+ elif credential is None:
+ status = "connected_unresolved"
+ else:
+ status = "connected_other_site"
+ return _decline_credential_origin_recovery(copilot_ctx, recovery, status)
+ copilot_ctx.credential_origin_recovery = None
+ policy.origin_recovery_kept_named_credential_ids |= named_before_ask & {recovery.refused_credential_id}
+ clear_tool_blocker_signals_for_reason_codes(
+ copilot_ctx, frozenset({CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE})
+ )
+ if resolution is None:
return {
"ok": True,
"status": "unanswered",
@@ -434,6 +670,15 @@ async def _request_credential(login_page_url: str, reason: str, copilot_ctx: Cop
"parameter placeholder in the draft and do not ask again this turn."
),
}
+ if resolution.action == "connected" and credential is None:
+ return {
+ "ok": True,
+ "status": "connected_unresolved",
+ "next": (
+ "The credential the user connected could not be loaded. Continue without it: keep the credential "
+ "parameter placeholder in the draft and do not ask again this turn."
+ ),
+ }
if credential is None:
return {
"ok": True,
@@ -455,6 +700,40 @@ async def _request_credential(login_page_url: str, reason: str, copilot_ctx: Cop
}
+async def _missing_totp_ask_outcome(
+ copilot_ctx: CopilotContext,
+ credential: Credential | None,
+ credential_name: str,
+ *,
+ answered: CredentialPauseResolution | None,
+) -> dict[str, Any]:
+ """Report the update card from the saved record, never from the answer alone: a save can leave 2FA unset."""
+ not_added_next = (
+ f"{defang_card_text(credential_name)} still has no authenticator. Keep it as the workflow's credential "
+ "and do not ask again this turn; say the verification step needs an authenticator on that credential "
+ "before a run can pass it."
+ )
+ if credential is None:
+ return {"ok": True, "status": "unanswered" if answered is None else "skipped", "next": not_added_next}
+ still_missing_name, rechecked = await _missing_totp_ask_target(copilot_ctx, credential.credential_id)
+ if rechecked is None:
+ return {
+ "ok": True,
+ "status": "saved_without_authenticator",
+ "credential_id": credential.credential_id,
+ "credential_name": still_missing_name,
+ "next": not_added_next,
+ }
+ if rechecked.get("status") != "has_code_method":
+ return rechecked
+ return {
+ **rechecked,
+ "status": "authenticator_added",
+ "credential_id": credential.credential_id,
+ "credential_name": credential.name,
+ }
+
+
def _request_settled_credential(policy: RequestPolicy, credential_id: str) -> bool:
"""A user selection settles identity; a saved binding alone remains scoped to its saved origin."""
if policy.current_turn_named_credential_ids == {credential_id}:
@@ -580,12 +859,9 @@ async def _credential_fill_origin_grant(
return None, admission.steer or authority_error
-async def _resolve_credential_fill_value(
- copilot_ctx: AgentContext,
- credential_id: str,
- field: str,
-) -> tuple[str | None, str, str | None]:
- """Resolve (secret_value, credential_name, error) for one credential field, server-side only."""
+async def _load_vault_credential_item(
+ copilot_ctx: AgentContext, credential_id: str
+) -> tuple[CredentialItem | None, str]:
try:
db_credential = await app.DATABASE.credentials.get_credential(
credential_id, organization_id=copilot_ctx.organization_id
@@ -597,16 +873,16 @@ async def _resolve_credential_fill_value(
organization_id=copilot_ctx.organization_id,
exc_info=True,
)
- return None, "", f"Could not read credential `{credential_id}`. Ask the user to verify it exists."
+ return None, f"Could not read credential `{credential_id}`. Ask the user to verify it exists."
if db_credential is None:
- return None, "", _missing_credential_reference_tool_error([credential_id])
+ return None, _missing_credential_reference_tool_error([credential_id])
vault_type = db_credential.vault_type or CredentialVaultType.BITWARDEN
credential_service = app.CREDENTIAL_VAULT_SERVICES.get(vault_type)
if credential_service is None:
- return None, "", f"The credential vault for `{credential_id}` is not configured on this deployment."
+ return None, f"The credential vault for `{credential_id}` is not configured on this deployment."
try:
- credential_item = await credential_service.get_credential_item(db_credential)
+ return await credential_service.get_credential_item(db_credential), ""
except Exception as exc:
LOG.warning(
"fill_credential_field could not fetch the credential from the vault",
@@ -614,7 +890,50 @@ async def _resolve_credential_fill_value(
vault_type=str(vault_type),
exc_info=True,
)
- return None, "", f"Could not fetch credential `{credential_id}` from the vault: {type(exc).__name__}."
+ return None, f"Could not fetch credential `{credential_id}` from the vault: {type(exc).__name__}."
+
+
+MISSING_AUTHENTICATOR = "missing_authenticator"
+
+
+@dataclass(frozen=True)
+class MissingAuthenticator:
+ """The resolver's non-prose failure: the credential has no one-time-code method at all."""
+
+
+def _missing_authenticator_fill_error(
+ copilot_ctx: AgentContext, credential_id: str, credential_name: str
+) -> dict[str, Any]:
+ already_asked = isinstance(copilot_ctx, CopilotContext) and copilot_ctx.credential_totp_update_asked
+ if already_asked:
+ next_step = (
+ "The user was already asked this turn to add an authenticator to this credential. Do not call "
+ "`request_credential` again; say the verification step needs an authenticator on it."
+ )
+ else:
+ next_step = (
+ f"Call `request_credential` with credential_id `{credential_id}` so the user can add its "
+ "authenticator, then retry this fill with the same `target`."
+ )
+ return {
+ "ok": False,
+ "status": MISSING_AUTHENTICATOR,
+ "error": "The saved credential has no authenticator (2FA) method.",
+ "next": next_step,
+ "update_ask": "already_asked" if already_asked else "available",
+ "data": {"credential_id": credential_id, "credential_name": credential_name, "credential_field": "totp"},
+ }
+
+
+async def _resolve_credential_fill_value(
+ copilot_ctx: AgentContext,
+ credential_id: str,
+ field: str,
+) -> tuple[str | None, str, str | MissingAuthenticator | None]:
+ """Resolve (secret_value, credential_name, error) for one credential field, server-side only."""
+ credential_item, load_error = await _load_vault_credential_item(copilot_ctx, credential_id)
+ if credential_item is None:
+ return None, "", load_error
credential = credential_item.credential
if not isinstance(credential, PasswordCredential):
return None, "", f"Credential `{credential_id}` is not a username/password credential."
@@ -625,12 +944,11 @@ async def _resolve_credential_fill_value(
value = credential.password
register_secret_scrub_value(copilot_ctx, value)
else:
+ method = _password_totp_method(credential)
+ if method == "out_of_band":
+ return None, credential_item.name, _runtime_otp_steering_error(credential_id)
if not credential.totp:
- # A saved OTP identifier means the code is delivered out-of-band;
- # only runtime polling has the run/task context needed to resolve it.
- if credential.totp_identifier or credential.totp_type in {TotpType.EMAIL, TotpType.TEXT}:
- return None, credential_item.name, _runtime_otp_steering_error(credential_id)
- return None, "", f"Credential `{credential_id}` has no TOTP secret configured."
+ return None, credential_item.name, MissingAuthenticator()
try:
value = generate_totp_code(
await _normalize_totp_config_for_organization(
@@ -932,6 +1250,8 @@ async def _fill_credential_field_impl_serial(
# between the generation and this line touches the network. From here only the fill's own readback
# and the reads the submit needs to re-check its origin and target may sit before the click.
mint_started = time.monotonic()
+ if isinstance(resolve_error, MissingAuthenticator):
+ return finish(_missing_authenticator_fill_error(copilot_ctx, credential_id, credential_name))
if resolve_error or value is None:
error_result: dict[str, Any] = {
"ok": False,
@@ -958,8 +1278,11 @@ async def _fill_credential_field_impl_serial(
)
readback = await _read_filled_field_value(page, selector)
fill_outcome = _scout_readback_outcome(readback, value)
- except _CredentialFillOriginMismatchError:
- return finish({"ok": False, "error": _credential_fill_origin_mismatch_error()})
+ except _CredentialFillOriginMismatchError as mismatch:
+ observed = canonicalize_origin(mismatch.target_url)
+ if observed is None or same_release_scope(mismatch.target_url, origin_grant.intended_url):
+ return finish({"ok": False, "error": _credential_fill_origin_mismatch_error()})
+ return finish(_start_credential_origin_recovery(copilot_ctx, observed.canonical, credential_id))
except Exception as exc:
error_text = scrub_secrets_from_text(copilot_ctx, _scrub_secret_from_text(str(exc), value))
LOG.info(
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 4968609d3..d5ae1589d 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -159,6 +159,7 @@ from skyvern.forge.sdk.copilot.runtime import (
RegisteredArtifactEntry,
RegisteredArtifactEvidence,
browser_page_custody_lock,
+ browser_session_recovery,
ensure_build_test_browser_session,
record_attached_browser_driver,
record_sensitive_origin_run_taint,
@@ -2797,13 +2798,16 @@ def _credit_composition_verified_labels(
async def acquire_build_test_browser_session(ctx: CopilotContext, *, fresh: bool) -> dict[str, Any] | None:
"""The single initial-acquisition seam used by every build-test run."""
- if fresh:
- return await ensure_build_test_browser_session(ctx)
- return await verify_build_test_browser_session_by_attaching(
- ctx,
- copilot_chat_id=ctx.workflow_copilot_chat_id,
- copilot_turn_id=ctx.turn_id,
- )
+ # Executed-source promotion holds this lock through persistence. Build-test acquisition can retire a
+ # fixed-deadline browser, so it must not replace that source's session while the write is in flight.
+ async with browser_session_recovery(ctx):
+ if fresh:
+ return await ensure_build_test_browser_session(ctx)
+ return await verify_build_test_browser_session_by_attaching(
+ ctx,
+ copilot_chat_id=ctx.workflow_copilot_chat_id,
+ copilot_turn_id=ctx.turn_id,
+ )
def _with_build_test_acquisition_context(
@@ -3992,7 +3996,8 @@ async def _run_blocks_and_collect_debug(
# Skip the rebind when the run used a browser other than the chat's, so the chat's stays
# the context session for the rest of the turn.
if not run_detached_from_chat and run and run.browser_session_id:
- ctx.browser_session_id = run.browser_session_id
+ async with browser_session_recovery(ctx):
+ ctx.browser_session_id = run.browser_session_id
blocks = await _chronological_run_block_rows(workflow_run.workflow_run_id, ctx.organization_id)
_reconcile_narrative_block_attempts(ctx, blocks)
@@ -4224,11 +4229,9 @@ async def _get_run_results(
) -> dict[str, Any]:
workflow_run_id = params.get("workflow_run_id")
if not workflow_run_id:
- same_turn_run_id = getattr(ctx, "last_successful_run_blocks_workflow_run_id", None)
- if not isinstance(same_turn_run_id, str) or not same_turn_run_id:
- same_turn_run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)
- if isinstance(same_turn_run_id, str) and same_turn_run_id:
- workflow_run_id = same_turn_run_id
+ recorded_run_id = ctx.last_successful_run_blocks_workflow_run_id or ctx.last_run_blocks_workflow_run_id
+ if recorded_run_id:
+ workflow_run_id = recorded_run_id
if not workflow_run_id:
# Include every final state so the agent can inspect failures via the
@@ -4843,6 +4846,8 @@ def _record_run_blocks_result(
copilot_ctx.last_run_blocks_browser_session_id = (
run_browser_session_id if isinstance(run_browser_session_id, str) and run_browser_session_id else None
)
+ # The refusal sentence described the run these pointers used to name.
+ copilot_ctx.last_run_binding_unavailable_reason = None
copilot_ctx.last_successful_run_blocks_workflow_run_id = run_id if run_ok and isinstance(run_id, str) else None
# Watchdog cancels normally count as ok=False; only a coincident total
# timeout softens to ``None`` to keep the unvalidated WIP rescue open.
@@ -5261,7 +5266,11 @@ def _record_build_test_outcome(
def _stash_recorded_run_outcome(copilot_ctx: CopilotContext, outcome: RecordedRunOutcome) -> RecordedRunOutcome:
if outcome.workflow_run_id is None:
- outcome = replace(outcome, workflow_run_id=copilot_ctx.last_run_blocks_workflow_run_id)
+ # Only a run this turn dispatched. The last-run pointer can hold a run inherited from an
+ # earlier turn, and stamping it here would attribute this turn's outcome to that run.
+ last_run_id = copilot_ctx.last_run_blocks_workflow_run_id
+ if last_run_id is not None and last_run_id in copilot_ctx.dispatched_run_ids_this_turn:
+ outcome = replace(outcome, workflow_run_id=last_run_id)
copilot_ctx.last_run_outcome = outcome
for workflow_run_block_id in copilot_ctx.last_run_blocks_block_ids:
attempt = copilot_ctx.narrative_block_attempts.get(workflow_run_block_id)
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index f72fd822e..2096b7561 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -4127,12 +4127,16 @@ async def _update_workflow(
result["data"] = block.data
return result
- def _tool_error(error: str, *, user_facing_summary: str | None = None) -> dict[str, Any]:
+ def _tool_error(
+ error: str, *, user_facing_summary: str | None = None, error_code: str | None = None
+ ) -> dict[str, Any]:
# The submission cannot become a Workflow, so there is no authored artifact to refuse:
# report it honestly without a block identity, a turn halt, or a churn increment.
result: dict[str, Any] = {"ok": False, "error": error}
if user_facing_summary is not None:
result["user_facing_summary"] = user_facing_summary
+ if error_code is not None:
+ result["error_code"] = error_code
return result
authority_error = _authority_tool_error(ctx, "update_workflow")
@@ -4343,6 +4347,23 @@ async def _update_workflow(
submitted_definition.update(inherited_settings)
workflow_yaml = dump_workflow_yaml(submitted_definition)
params["workflow_yaml"] = workflow_yaml
+ expected_exact_code_by_label = params.get("_expected_exact_code_by_label")
+ if isinstance(expected_exact_code_by_label, dict):
+ transformed_blocks_by_label = _workflow_yaml_code_blocks_by_label(workflow_yaml)
+ changed_labels = [
+ label
+ for label, expected_source in expected_exact_code_by_label.items()
+ if not isinstance(label, str)
+ or not isinstance(expected_source, str)
+ or transformed_blocks_by_label.get(label, {}).get("code") != expected_source
+ ]
+ if changed_labels:
+ return _tool_error(
+ "The executed source changed at the workflow persistence boundary, so it was not saved or run. "
+ "Run the complete candidate again without embedding a live credential value, then promote its "
+ "new source reference.",
+ error_code="executed_source_changed_before_persistence",
+ )
prior_workflow = await _get_prior_workflow(ctx)
workflow = await _process_workflow_yaml(
workflow_id=ctx.workflow_id,
diff --git a/skyvern/forge/sdk/copilot/workflow_yaml.py b/skyvern/forge/sdk/copilot/workflow_yaml.py
index 04f144682..00b2b9c01 100644
--- a/skyvern/forge/sdk/copilot/workflow_yaml.py
+++ b/skyvern/forge/sdk/copilot/workflow_yaml.py
@@ -901,7 +901,9 @@ def _render_code_scalar_replacement(stored_yaml: str, scalar: ScalarNode, code:
source_style = "|" if scalar.style == ">" and "\n" in code.rstrip("\n") else scalar.style
replacement = _render_code_scalar(code, content_indent=content_indent, source_style=source_style)
header_preserved = False
- if scalar.style in {"|", ">"} and source_style == scalar.style and code:
+ # An empty block scalar has no trailing newline to compare, so its clip header would add one to the
+ # replacement; only a scalar with content can vouch for the header it carries.
+ if scalar.style in {"|", ">"} and source_style == scalar.style and code and scalar.value:
current_trailing_newlines = len(scalar.value) - len(scalar.value.rstrip("\n"))
replacement_trailing_newlines = len(code) - len(code.rstrip("\n"))
current_first_nonempty = next((line for line in scalar.value.splitlines() if line), "")
@@ -1130,8 +1132,12 @@ def stored_workflow_yaml(copilot_ctx: Any) -> str:
return stored if isinstance(stored, str) else ""
-def stored_block_code(stored_yaml: str, label: str) -> str | None:
- """The code ``apply_block_edit`` would anchor an edit to ``label`` against, if any."""
+def stored_block_code(stored_yaml: str, label: str, *, allow_empty: bool = False) -> str | None:
+ """The code ``apply_block_edit`` would anchor an edit to ``label`` against, if any.
+
+ ``allow_empty`` lets callers that replace a complete scalar distinguish a valid empty CodeBlock
+ placeholder from a missing label or non-string code field.
+ """
if not label or not stored_yaml.strip():
return None
try:
@@ -1145,7 +1151,7 @@ def stored_block_code(stored_yaml: str, label: str) -> str | None:
except BlockEditError:
return None
code = block.get("code")
- return code if isinstance(code, str) and code.strip() else None
+ return code if isinstance(code, str) and (allow_empty or code.strip()) else None
def apply_block_edit(
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index bbed8a373..70b5915b0 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -63,24 +63,23 @@ def redact_multi_field_totp_element_data(element_data: dict[str, Any]) -> dict[s
def action_for_multi_field_totp_persistence(action: Action) -> Action:
- """Return a safe copy of a multi-box OTP action for database persistence."""
+ """Return a copy of a multi-box OTP action carrying only the seed-free timing metadata.
+
+ The digit typed into the box stays on the row: the one-time code is a record the customer has to
+ be able to read back, and only the seed that mints codes is a secret. The allowlist below is what
+ keeps a `totp_secret` out of `totp_timing_info`.
+ """
timing_info = action.totp_timing_info
if not timing_info or not timing_info.get("is_totp_sequence"):
return action
updates: dict[str, Any] = {
- "text": "*",
- "reasoning": "Entered a one-time code digit.",
"totp_timing_info": {
key: timing_info[key]
for key in ("is_totp_sequence", "action_index", "box_element_ids", "code_source")
if key in timing_info
},
}
- if action.intention is not None:
- updates["intention"] = "*"
- if action.response is not None:
- updates["response"] = "*"
if action.skyvern_element_data is not None:
updates["skyvern_element_data"] = redact_multi_field_totp_element_data(action.skyvern_element_data)
if action.input_or_select_context is not None:
@@ -507,6 +506,65 @@ class SkyvernContext:
# task/run/persistent-session scope.
download_popup_claims: dict[str, list[Page]] = field(default_factory=dict)
+ # Capture survives action return, but stops before the next action can create unrelated Pages.
+ download_popup_context_listeners: dict[str, list[tuple[Any, Callable[[Any], None]]]] = field(default_factory=dict)
+
+ # Reservations outlive capture until durable credit, intentional adoption, or terminal cleanup.
+ download_popup_late_candidates: dict[str, list[Page]] = field(default_factory=dict)
+
+ # A dispatched-then-failed action's reservations are not released inline (the browser effect may
+ # still credit a download after the action seam returns). The pre-action snapshot is stashed here
+ # and the release is deferred to the next durable-credit seam, applied only if no credit arrived.
+ pending_download_reservation_release: dict[str, tuple[tuple[Page, ...], tuple[Page, ...]]] = field(
+ default_factory=dict
+ )
+
+ # Monotonic time the bounded dead-blank recovery grace STARTED for each exact popup Page, keyed
+ # task_id -> id(page). Anchored first-wins at the first eligible blank-page recovery observation (NOT
+ # at claim creation): the handler's own post-click wait already spent its separate budget, so recovery
+ # must still grant ~one full grace for a late/silent final file. Event-recorded and finally-swept
+ # claims get identical recovery-grace semantics; a later recovery call consumes the remaining budget
+ # and never restarts it; sibling pages have independent deadlines. id(page) is a safe key because the
+ # claim/late-candidate registries strong-reference every keyed Page (no GC-then-reuse while claimed);
+ # the entry is dropped the moment the page leaves BOTH registries, so a stale anchor can never outlive
+ # its page or resurrect after credit.
+ download_popup_recovery_grace_started_at: dict[str, dict[int, float]] = field(default_factory=dict)
+
+ # Snapshot of the download files present when each exact popup Page's claim was FIRST created,
+ # keyed task_id -> id(page) -> baseline paths. Dead-blank recovery observation compares a claimed
+ # page against ITS OWN baseline, so a file that landed for an earlier action or a sibling page
+ # before this page's claim is never miscredited to it (a non-complete block reuses one stale
+ # block-level baseline across recursive steps). Strict subordinate of the two Page registries with
+ # the same lifecycle as the creation anchor above; never feeds the authoritative block-level
+ # credit/finalization baseline.
+ download_popup_claim_baseline: dict[str, dict[int, tuple[str, ...]]] = field(default_factory=dict)
+
+ # Exact popup Pages (keyed task_id -> {id(page)}) whose claim baseline was built with a persistent
+ # browser-session listing (the download-action path). Dead-blank recovery only unions session files
+ # into ITS observation for these pages: a claim WITHOUT a session baseline (the v4 false-click path,
+ # which must never do a remote listing) cannot be credited by session-only files, because it has no
+ # session reference to tell a genuinely new file from one an earlier action already produced. Strict
+ # subordinate of the two Page registries with the same lifecycle as the baseline snapshot above.
+ download_popup_claim_session_observed: dict[str, set[int]] = field(default_factory=dict)
+
+ # AUGMENTED session baseline per exact popup Page (task_id -> {id(page): {paths}}). Unlike the
+ # first-wins baseline snapshot above, later session observations are UNIONED in: the event-recorded
+ # popup claim anchors the stale pre-action session snapshot, but the action-finally resnapshot re-records
+ # the same page and augments it, so a session download from an earlier action that settled between the
+ # pre-action fetch and this popup's mint is baselined out and cannot be miscredited. Augmentation only
+ # ever makes the baseline MORE conservative; a still-pending own download is absent from the later
+ # snapshot, so it can still credit during the grace. Local facts stay first-wins in the snapshot above.
+ download_popup_claim_session_baseline: dict[str, dict[int, set[str]]] = field(default_factory=dict)
+
+ # Exact popup Pages (task_id -> {id(page)}) claimed together in a MULTI-popup action-finally delta
+ # sweep -- the only place a batch of same-action siblings is discovered at one instant. For these,
+ # a new completed file that appears during ONE sibling's dead-blank grace cannot be causally
+ # attributed to it rather than a sibling (no file->page mapping exists), so a non-complete recovery
+ # must not early-credit-and-close it on that file while its own download may still be in flight; it
+ # waits its full grace instead. Strict subordinate of the two Page registries, same lifecycle as the
+ # baseline snapshots above. A lone delta popup and the sync/false-click recorders are never marked.
+ download_popup_claim_delta_siblings: dict[str, set[int]] = field(default_factory=dict)
+
# Tasks whose terminal cleanup has already run its download half -- settle, save, and artifact
# outcome recording -- so a recovery path can tell "never recorded" from "recorded" without
# inferring it from the task row. Keyed per task rather than per stack frame because cleanup is
@@ -736,10 +794,124 @@ class SkyvernContext:
return False
return True
- def record_download_popup_claim(self, task_id: str, page: Page) -> None:
+ def record_download_popup_claim(
+ self,
+ task_id: str,
+ page: Page,
+ baseline_files: Iterable[str] | None = None,
+ session_observed: bool = False,
+ session_baseline_files: Iterable[str] | None = None,
+ ) -> None:
claims = self.download_popup_claims.setdefault(task_id, [])
if all(existing is not page for existing in claims):
claims.append(page)
+ self._anchor_download_popup_claim_baseline(task_id, page, baseline_files)
+ self._augment_download_popup_claim_session_baseline(task_id, page, session_baseline_files)
+ if session_observed:
+ self.download_popup_claim_session_observed.setdefault(task_id, builtins.set()).add(id(page))
+
+ def anchor_download_popup_recovery_grace(self, task_id: str, page: Page, now: float) -> None:
+ # First-wins: anchor the recovery-observation grace to the FIRST eligible blank-page recovery
+ # observation of this exact Page. A later recovery call (or re-entry/cancellation) reuses this
+ # anchor and consumes the remaining budget rather than restarting it; siblings are independent.
+ self.download_popup_recovery_grace_started_at.setdefault(task_id, {}).setdefault(id(page), now)
+
+ def _anchor_download_popup_claim_baseline(
+ self, task_id: str, page: Page, baseline_files: Iterable[str] | None
+ ) -> None:
+ # setdefault -> anchor to the FIRST creation snapshot, mirroring the creation anchor above. A
+ # None snapshot (a caller without a resolved download dir) records nothing, so recovery falls
+ # back to the block baseline for that page rather than a wrong page-specific one.
+ if baseline_files is None:
+ return
+ self.download_popup_claim_baseline.setdefault(task_id, {}).setdefault(id(page), tuple(baseline_files))
+
+ def _augment_download_popup_claim_session_baseline(
+ self, task_id: str, page: Page, session_baseline_files: Iterable[str] | None
+ ) -> None:
+ # UNION (not setdefault): a later session observation for a re-recorded page can only make the
+ # baseline more conservative, so augment it rather than keep the stale first snapshot.
+ if session_baseline_files is None:
+ return
+ self.download_popup_claim_session_baseline.setdefault(task_id, {}).setdefault(id(page), builtins.set()).update(
+ session_baseline_files
+ )
+
+ def download_popup_claim_baseline_for(self, task_id: str, page: Page) -> tuple[str, ...] | None:
+ """The exact-Page download baseline captured when this page's claim was created, or None when
+ no snapshot was anchored for it."""
+ by_page = self.download_popup_claim_baseline.get(task_id)
+ if not by_page:
+ return None
+ return by_page.get(id(page))
+
+ def download_popup_claim_session_baseline_for(self, task_id: str, page: Page) -> tuple[str, ...] | None:
+ """The augmented per-Page session baseline (every session observation unioned across re-records),
+ or None when none was anchored for it."""
+ by_page = self.download_popup_claim_session_baseline.get(task_id)
+ if not by_page:
+ return None
+ session = by_page.get(id(page))
+ return tuple(session) if session is not None else None
+
+ def download_popup_claim_session_was_observed(self, task_id: str, page: Page) -> bool:
+ """Whether this exact page's claim baseline was built with a browser-session listing. False for a
+ v4 false-click claim (local-only baseline), so recovery must not union session files for it."""
+ return id(page) in self.download_popup_claim_session_observed.get(task_id, builtins.set())
+
+ def mark_download_popup_claim_delta_siblings(self, task_id: str, pages: Iterable[Page]) -> None:
+ """Mark exact popup Pages claimed together in one multi-popup delta sweep as sibling-ambiguous, so
+ recovery cannot causally attribute a new file to one of them over the others."""
+ bucket = self.download_popup_claim_delta_siblings.setdefault(task_id, builtins.set())
+ for page in pages:
+ bucket.add(id(page))
+
+ def download_popup_claim_has_delta_siblings(self, task_id: str, page: Page) -> bool:
+ """Whether this exact page was claimed alongside siblings in one multi-popup delta sweep."""
+ return id(page) in self.download_popup_claim_delta_siblings.get(task_id, builtins.set())
+
+ def remaining_download_popup_grace(self, task_id: str, page: Page, grace: float, now: float) -> float | None:
+ """Remaining grace for ONE exact page: ``grace - (now - started)`` clamped at 0.0 (an aged
+ anchor never waits again). None when this exact page has no recovery-grace anchor yet."""
+ by_page = self.download_popup_recovery_grace_started_at.get(task_id)
+ if not by_page:
+ return None
+ started = by_page.get(id(page))
+ if started is None:
+ return None
+ return max(0.0, grace - (now - started))
+
+ def _drop_claim_deadline_if_unreferenced(self, task_id: str, page: Page) -> None:
+ # The recovery-grace anchor and the baseline snapshot are strict subordinates of the union of the
+ # two Page registries: drop them only once the exact page is gone from BOTH, so a page still live
+ # in the sibling registry keeps them.
+ if self.has_download_popup_claim(task_id, page):
+ return
+ by_page = self.download_popup_recovery_grace_started_at.get(task_id)
+ if by_page:
+ by_page.pop(id(page), None)
+ if not by_page:
+ del self.download_popup_recovery_grace_started_at[task_id]
+ baseline_by_page = self.download_popup_claim_baseline.get(task_id)
+ if baseline_by_page:
+ baseline_by_page.pop(id(page), None)
+ if not baseline_by_page:
+ del self.download_popup_claim_baseline[task_id]
+ session_observed = self.download_popup_claim_session_observed.get(task_id)
+ if session_observed:
+ session_observed.discard(id(page))
+ if not session_observed:
+ del self.download_popup_claim_session_observed[task_id]
+ session_baseline_by_page = self.download_popup_claim_session_baseline.get(task_id)
+ if session_baseline_by_page:
+ session_baseline_by_page.pop(id(page), None)
+ if not session_baseline_by_page:
+ del self.download_popup_claim_session_baseline[task_id]
+ delta_siblings = self.download_popup_claim_delta_siblings.get(task_id)
+ if delta_siblings:
+ delta_siblings.discard(id(page))
+ if not delta_siblings:
+ del self.download_popup_claim_delta_siblings[task_id]
def discard_download_popup_claim(self, task_id: str, page: Page) -> bool:
"""Retire a stale claim once its exact Page is reused as a later action's initiating page.
@@ -756,20 +928,199 @@ class SkyvernContext:
self.download_popup_claims[task_id] = remaining
else:
del self.download_popup_claims[task_id]
+ self._drop_claim_deadline_if_unreferenced(task_id, page)
return True
def has_download_popup_claim(self, task_id: str, page: Page) -> bool:
- """Identity read: is this exact Page still held as a task-scoped download-popup claim."""
- claims = self.download_popup_claims.get(task_id)
- if not claims:
+ return any(existing is page for existing in self.download_popup_claims.get(task_id, [])) or any(
+ existing is page for existing in self.download_popup_late_candidates.get(task_id, [])
+ )
+
+ def arm_download_popup_context_listener(
+ self, task_id: str, browser_context: Any, callback: Callable[[Any], None]
+ ) -> None:
+ listeners = self.download_popup_context_listeners.setdefault(task_id, [])
+ if any(existing_context is browser_context for existing_context, _ in listeners):
+ return
+
+ def capture_if_current(page: Any) -> None:
+ # A queued callback or failed remove_listener must not resurrect an expired reservation.
+ if any(
+ current_callback is capture_if_current
+ for _, current_callback in self.download_popup_context_listeners.get(task_id, [])
+ ):
+ callback(page)
+
+ browser_context.on("page", capture_if_current)
+ listeners.append((browser_context, capture_if_current))
+
+ def stop_download_popup_capture(self, task_id: str) -> None:
+ for browser_context, callback in self.download_popup_context_listeners.pop(task_id, []):
+ try:
+ browser_context.remove_listener("page", callback)
+ except Exception:
+ pass
+
+ def record_download_popup_late_candidate(
+ self,
+ task_id: str,
+ page: Page,
+ baseline_files: Iterable[str] | None = None,
+ session_observed: bool = False,
+ session_baseline_files: Iterable[str] | None = None,
+ ) -> None:
+ candidates = self.download_popup_late_candidates.setdefault(task_id, [])
+ if all(existing is not page for existing in candidates):
+ candidates.append(page)
+ self._anchor_download_popup_claim_baseline(task_id, page, baseline_files)
+ self._augment_download_popup_claim_session_baseline(task_id, page, session_baseline_files)
+ if session_observed:
+ self.download_popup_claim_session_observed.setdefault(task_id, builtins.set()).add(id(page))
+
+ def discard_download_popup_late_candidate(self, task_id: str, page: Page) -> bool:
+ """Retire a late candidate once its exact Page is a deliberately-created/adopted tab. Mirrors
+ ``discard_download_popup_claim``: removes only ``existing is page``, preserves siblings, drops the
+ task key when empty, and returns whether a candidate was removed."""
+ candidates = self.download_popup_late_candidates.get(task_id)
+ if not candidates:
return False
- return any(existing is page for existing in claims)
+ remaining = [existing for existing in candidates if existing is not page]
+ if len(remaining) == len(candidates):
+ return False
+ if remaining:
+ self.download_popup_late_candidates[task_id] = remaining
+ else:
+ del self.download_popup_late_candidates[task_id]
+ self._drop_claim_deadline_if_unreferenced(task_id, page)
+ return True
+
+ def release_download_popup_claim(self, task_id: str, page: Page) -> None:
+ """Release ONE exact Page from both download-popup reservation registries (claim + late-candidate)
+ by identity, dropping its subordinate creation anchor and baseline snapshot. Preserves sibling,
+ task, and context entries and is idempotent. This is the narrow release primitive; call it to
+ release an expired dead-blank recovery claim."""
+ self.discard_download_popup_claim(task_id, page)
+ self.discard_download_popup_late_candidate(task_id, page)
+
+ def retire_intentional_page(self, task_id: str, page: Page) -> None:
+ """Retire a deliberately-created/adopted Page (NEW_TAB, magic link) from BOTH download-popup
+ reservation registries by exact identity. A newly created page joins the context and is recorded by
+ the ``context.on("page")`` owner while still blank; an intentional page must never be closed by a
+ delayed download credit. Same exact-Page release as ``release_download_popup_claim`` -- named for
+ the deliberate-tab-protection intent at NEW_TAB/magic-link sites."""
+ self.release_download_popup_claim(task_id, page)
+
+ def detach_all_download_popup_context_listeners(self) -> None:
+ for task_id in list(self.download_popup_context_listeners):
+ self.stop_download_popup_capture(task_id)
+ self.download_popup_claims.clear()
+ self.download_popup_late_candidates.clear()
+ self.pending_download_reservation_release.clear()
+ self.download_popup_recovery_grace_started_at.clear()
+ self.download_popup_claim_baseline.clear()
+ self.download_popup_claim_session_observed.clear()
+ self.download_popup_claim_session_baseline.clear()
+ self.download_popup_claim_delta_siblings.clear()
+
+ def take_download_popup_late_candidates(self, task_id: str) -> list[Page]:
+ self.stop_download_popup_capture(task_id)
+ taken = self.download_popup_late_candidates.pop(task_id, [])
+ for page in taken:
+ self._drop_claim_deadline_if_unreferenced(task_id, page)
+ return taken
def take_download_popup_claims(self, task_id: str) -> list[Page]:
- return self.download_popup_claims.pop(task_id, [])
+ self.stop_download_popup_capture(task_id)
+ taken = self.download_popup_claims.pop(task_id, [])
+ for page in taken:
+ self._drop_claim_deadline_if_unreferenced(task_id, page)
+ return taken
def clear_download_popup_claims(self, task_id: str) -> None:
+ self.stop_download_popup_capture(task_id)
self.download_popup_claims.pop(task_id, None)
+ self.download_popup_late_candidates.pop(task_id, None)
+ self.pending_download_reservation_release.pop(task_id, None)
+ self.download_popup_recovery_grace_started_at.pop(task_id, None)
+ self.download_popup_claim_baseline.pop(task_id, None)
+ self.download_popup_claim_session_observed.pop(task_id, None)
+ self.download_popup_claim_session_baseline.pop(task_id, None)
+ self.download_popup_claim_delta_siblings.pop(task_id, None)
+
+ def snapshot_download_popup_reservations(self, task_id: str) -> tuple[tuple[Page, ...], tuple[Page, ...]]:
+ return (
+ tuple(self.download_popup_claims.get(task_id, [])),
+ tuple(self.download_popup_late_candidates.get(task_id, [])),
+ )
+
+ def retain_download_popup_reservations(
+ self, task_id: str, snapshot: tuple[tuple[Page, ...], tuple[Page, ...]]
+ ) -> None:
+ self.stop_download_popup_capture(task_id)
+ # Filter current entries so adoption and credit consumption are never undone.
+ for registry, prior_pages in (
+ (self.download_popup_claims, snapshot[0]),
+ (self.download_popup_late_candidates, snapshot[1]),
+ ):
+ remaining = [
+ page for page in registry.get(task_id, []) if any(page is prior_page for prior_page in prior_pages)
+ ]
+ if remaining:
+ registry[task_id] = remaining
+ else:
+ registry.pop(task_id, None)
+ self._prune_claim_deadlines(task_id)
+
+ def _prune_claim_deadlines(self, task_id: str) -> None:
+ # The recovery-grace anchor and the baseline snapshot are strict subordinates of the two Page
+ # registries: prune BOTH against the same live-id set, or a stale baseline (first-wins under
+ # id() reuse) could later attach to a freshly created Page in the miscredit direction.
+ live_ids = {id(p) for p in self.download_popup_claims.get(task_id, [])}
+ live_ids |= {id(p) for p in self.download_popup_late_candidates.get(task_id, [])}
+ for registry in (self.download_popup_recovery_grace_started_at, self.download_popup_claim_baseline):
+ by_page = registry.get(task_id)
+ if not by_page:
+ continue
+ for page_id in [pid for pid in by_page if pid not in live_ids]:
+ by_page.pop(page_id, None)
+ if not by_page:
+ del registry[task_id]
+ session_observed = self.download_popup_claim_session_observed.get(task_id)
+ if session_observed:
+ session_observed.intersection_update(live_ids)
+ if not session_observed:
+ del self.download_popup_claim_session_observed[task_id]
+ session_baseline_by_page = self.download_popup_claim_session_baseline.get(task_id)
+ if session_baseline_by_page:
+ for page_id in [pid for pid in session_baseline_by_page if pid not in live_ids]:
+ session_baseline_by_page.pop(page_id, None)
+ if not session_baseline_by_page:
+ del self.download_popup_claim_session_baseline[task_id]
+ delta_siblings = self.download_popup_claim_delta_siblings.get(task_id)
+ if delta_siblings:
+ delta_siblings.intersection_update(live_ids)
+ if not delta_siblings:
+ del self.download_popup_claim_delta_siblings[task_id]
+
+ def stash_pending_download_reservation_release(
+ self, task_id: str, snapshot: tuple[tuple[Page, ...], tuple[Page, ...]]
+ ) -> None:
+ """Keep the earliest failed dispatch's snapshot for release at the step's no-credit seam.
+ A later dispatched success cancels this instruction, retaining all live reservations for credit or cleanup.
+ """
+ self.pending_download_reservation_release.setdefault(task_id, snapshot)
+
+ def cancel_pending_download_reservation_release(self, task_id: str) -> None:
+ self.pending_download_reservation_release.pop(task_id, None)
+
+ def apply_pending_download_reservation_release(self, task_id: str) -> None:
+ """Release a previously-deferred dispatched-then-failed epoch if the credit seam did not consume
+ it. A no-op when nothing is pending; when credit already emptied the registries, the retain
+ filters to an empty set and is inert."""
+ snapshot = self.pending_download_reservation_release.pop(task_id, None)
+ if snapshot is None:
+ return
+ self.retain_download_popup_reservations(task_id, snapshot)
def mark_cleanup_downloads_recorded(self, task_id: str) -> None:
self.cleanup_downloads_recorded_task_ids.add(task_id)
@@ -920,6 +1271,11 @@ def _cleanup_outgoing_context(context: SkyvernContext | None) -> None:
if context.feature_flag_entries:
context.flush_feature_flags()
context.cleanup_pending_file_chooser()
+ # The download-popup context.on("page") listeners are owned for the lifetime of THIS context. Detaching
+ # them here (reset/replace/_restore) guarantees a task that abandons before clean_up_task cannot leak a
+ # listener on a persistent BrowserContext. scoped() cleans a distinct child context whose buckets are
+ # empty, so this stays a no-op for the still-current task's own listeners.
+ context.detach_all_download_popup_context_listeners()
def _restore(token: Token[SkyvernContext | None]) -> None:
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index fe763197b..7fd1ef789 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -888,6 +888,8 @@ class WorkflowRunModel(Base):
browser_address = Column(String, nullable=True, index=True)
script_run = Column(JSON, nullable=True)
job_id = Column(String, nullable=True, index=True)
+ task_queue = Column(String, nullable=True)
+ target_cluster = Column(String, nullable=True)
depends_on_workflow_run_id = Column(String, nullable=True, index=True)
sequential_key = Column(String, nullable=True)
sequential_credential_id = Column(String, nullable=True)
diff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
index 5f055a293..609d5be13 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
@@ -96,7 +96,6 @@ from skyvern.forge.sdk.workflow.models.parameter import (
WorkflowParameter,
WorkflowParameterType,
)
-from skyvern.utils.action_redaction import redact_action_for_log
from skyvern.webeye.actions.actions import Action
LOG = structlog.get_logger()
@@ -1880,7 +1879,6 @@ class WorkflowParametersRepository(BaseRepository):
async def create_action(self, action: Action) -> Action:
async with self.Session() as session:
raw_action_payload = action.model_dump()
- action_log_payload = redact_action_for_log(action)
new_action = ActionModel(
action_type=action.action_type,
source_action_id=action.source_action_id,
@@ -1893,7 +1891,7 @@ class WorkflowParametersRepository(BaseRepository):
status=action.status,
reasoning=action.reasoning,
intention=action.intention,
- response=action_log_payload.get("response"),
+ response=action.response,
element_id=action.element_id,
skyvern_element_hash=action.skyvern_element_hash,
skyvern_element_data=action.skyvern_element_data,
@@ -1916,7 +1914,6 @@ class WorkflowParametersRepository(BaseRepository):
# uploaded) and its end-of-block batch converge on the same row, so the batch backfills the
# screenshot instead of inserting a duplicate. Isolated from create_action to leave the agent
# write path untouched.
- action_log_payload = redact_action_for_log(action)
values = {
"action_id": action.action_id,
"action_type": action.action_type,
@@ -1930,7 +1927,7 @@ class WorkflowParametersRepository(BaseRepository):
"status": action.status,
"reasoning": action.reasoning,
"intention": action.intention,
- "response": action_log_payload.get("response"),
+ "response": action.response,
"element_id": action.element_id,
"skyvern_element_hash": action.skyvern_element_hash,
"skyvern_element_data": action.skyvern_element_data,
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index 6cb469629..0dadce5c4 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -454,6 +454,21 @@ class WorkflowRunsRepository(BaseRepository):
)
return (await session.scalars(query)).first()
+ @db_operation("update_workflow_run_routing")
+ async def update_workflow_run_routing(self, workflow_run_id: str, task_queue: str, target_cluster: str) -> None:
+ """Record the latest selected destination without refreshing lifecycle or reaper clocks."""
+ async with self.Session() as session:
+ await session.execute(
+ update(WorkflowRunModel)
+ .where(WorkflowRunModel.workflow_run_id == workflow_run_id)
+ .values(
+ task_queue=task_queue,
+ target_cluster=target_cluster,
+ modified_at=WorkflowRunModel.modified_at,
+ )
+ )
+ await session.commit()
+
@db_operation("update_workflow_run")
async def update_workflow_run(
self,
diff --git a/skyvern/forge/sdk/executor/background_task_executor.py b/skyvern/forge/sdk/executor/background_task_executor.py
index 0cf59f16f..7b97e2fe6 100644
--- a/skyvern/forge/sdk/executor/background_task_executor.py
+++ b/skyvern/forge/sdk/executor/background_task_executor.py
@@ -65,7 +65,25 @@ async def _run_with_own_context(
"""
parent = skyvern_context.current()
if parent is not None:
- skyvern_context.set(replace(parent))
+ # The download-popup lifecycle registries are context-owned and destructively torn down at
+ # context cleanup (detach listeners, clear claims/reservations). A shallow replace() would
+ # alias them, so a reset/cleanup on either run would wipe the other live run's ownership state.
+ # A background run is a distinct run whose task ids never carry the parent's reservations, so
+ # give it independent EMPTY registries -- never copy entries; ownership must not cross runs.
+ skyvern_context.set(
+ replace(
+ parent,
+ download_popup_claims={},
+ download_popup_context_listeners={},
+ download_popup_late_candidates={},
+ pending_download_reservation_release={},
+ download_popup_recovery_grace_started_at={},
+ download_popup_claim_baseline={},
+ download_popup_claim_session_observed={},
+ download_popup_claim_session_baseline={},
+ download_popup_claim_delta_siblings={},
+ )
+ )
await func(*args, **kwargs)
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index a93974b58..e4ce152b1 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -659,6 +659,13 @@ class WorkflowCopilotToolResultUpdate(BaseModel):
"passed or failed; None for non-run tools."
),
)
+ executed_source_reference: str | None = Field(
+ None,
+ description=(
+ "Opaque reference to the exact source executed by a run_browser_code result. "
+ "Present for that tool only so a later promotion can be tied to the executed cell."
+ ),
+ )
timestamp: datetime | None = Field(
None,
description="Server timestamp for this event; the same clock read is persisted on the matching activity entry.",
@@ -826,6 +833,7 @@ class WorkflowCopilotCredentialRequiredUpdate(BaseModel):
"missing_credential_run_failure",
"credential_deferred_draft",
"login_credentials_unresolved",
+ "credential_missing_totp",
] = Field(..., description="Typed signal that triggered the pause")
message: str = Field(..., description="The agent's explanatory text at the moment of pausing")
login_page_urls: list[str] = Field(default_factory=list, description="Candidate login page URLs, if known")
diff --git a/skyvern/forge/sdk/workflow/code_block_authorized_files.py b/skyvern/forge/sdk/workflow/code_block_authorized_files.py
index 1c654f285..c67dbd72f 100644
--- a/skyvern/forge/sdk/workflow/code_block_authorized_files.py
+++ b/skyvern/forge/sdk/workflow/code_block_authorized_files.py
@@ -6,17 +6,52 @@ import asyncio
import hashlib
import mimetypes
import os
+import re
+import shutil
import stat
+import tempfile
from collections.abc import Awaitable, Callable, Mapping
+from contextlib import suppress
from dataclasses import dataclass
from functools import partial
from pathlib import Path, PurePath
-from typing import Protocol
+from types import SimpleNamespace
+from typing import Any, Protocol, cast
+
+import structlog
+from playwright.async_api import BrowserContext
+
+from skyvern.constants import SAVE_DOWNLOADED_FILES_TIMEOUT
+from skyvern.forge import app
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.core.hashing import diagnostic_fingerprint
+from skyvern.forge.sdk.schemas.files import FileInfo
+from skyvern.webeye.browser_factory import resolve_artifact_path
+from skyvern.webeye.browser_object_predicates import DownloadLike, is_download_like
+from skyvern.webeye.cdp_download_interceptor import (
+ is_monitoring_browser_downloads_for_context,
+ monitor_saved_download_name,
+ normalize_download_filename,
+ settle_browser_downloads_for_context,
+)
AUTHORIZED_FILE_UNAVAILABLE_ERROR = (
"The declared file input could not be materialized. Check that the file_url is available and retry."
)
AUTHORIZED_FILE_CHANGED_ERROR = "The authorized file is unavailable or changed. Materialize the file again."
+AUTHORIZED_FILE_SHAPE_ERROR = (
+ "attach_authorized_file accepts only a materialized file_url parameter or a download this run claimed."
+)
+
+LOG = structlog.get_logger()
+
+DownloadEvidenceProbe = Callable[[], Awaitable[tuple[list[FileInfo] | None, set[str]]]]
+RegisteredDownloadIdentity = tuple[str | None, str | None]
+_REGISTERED_DOWNLOAD_POLL_SECONDS = 2.0
+# Each probe re-runs download registration, so one probe and the whole wait both stay well inside the 180s
+# settle window.
+_REGISTERED_DOWNLOAD_PROBE_TIMEOUT_SECONDS = 10
+_REGISTERED_DOWNLOAD_WAIT_SECONDS = 30
class AuthorizedFileAccessError(Exception):
@@ -130,24 +165,48 @@ def capture_authorized_file(
max_bytes: int,
filename: str | None = None,
) -> MaterializedAuthorizedFile:
+ run_directory = _run_directory(download_root, workflow_run_id)
+ resolved_path = Path(path)
+
+ def refuse(cause: str, error: BaseException | None = None) -> AuthorizedFileAccessError:
+ LOG.info(
+ "codeblock.authorized_file_capture_refused",
+ cause=cause,
+ error_type=type(error).__name__ if error is not None else None,
+ errno=error.errno if isinstance(error, OSError) else None,
+ run_directory=str(run_directory),
+ candidate_directory=str(resolved_path.parent),
+ candidate_name_fp=diagnostic_fingerprint(resolved_path.name),
+ workflow_run_id=workflow_run_id,
+ )
+ return AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+
+ try:
+ run_directory = run_directory.resolve()
+ resolved_path = resolved_path.resolve()
+ except OSError as error:
+ raise refuse("resolve_failed", error) from None
try:
- run_directory = _run_directory(download_root, workflow_run_id).resolve()
- resolved_path = Path(path).resolve()
relative_path = str(resolved_path.relative_to(run_directory))
+ except ValueError as error:
+ raise refuse("outside_run_directory", error) from None
+ try:
file_fd = _open_beneath_run_directory(download_root, workflow_run_id, relative_path)
- except (OSError, ValueError, AuthorizedFileAccessError):
- raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR) from None
+ except OSError as error:
+ raise refuse("open_failed", error) from None
+ except AuthorizedFileAccessError as error:
+ raise refuse("unsafe_relative_path", error) from None
try:
before = os.fstat(file_fd)
if not stat.S_ISREG(before.st_mode):
- raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ raise refuse("not_regular_file")
# An oversized file stays materialized for code that opens it by path. It is not hashed:
# redemption refuses anything above the ceiling before it compares digests.
digest = ""
if before.st_size <= max_bytes:
digest, _ = _digest_fd(file_fd, collect=False)
if _changed_during_read(before, os.fstat(file_fd)):
- raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ raise refuse("changed_during_read")
return MaterializedAuthorizedFile(
workflow_run_id=workflow_run_id,
organization_id=organization_id,
@@ -215,6 +274,488 @@ def read_authorized_file(
os.close(file_fd)
+def _download_disk_name(download: DownloadLike) -> str:
+ # Chrome writes the suggested name literally, so a real "%20" stays "%20" on disk; escaping "%"
+ # keeps the upload-name sanitizer's URL-decoding out of the disk match.
+ return normalize_download_filename((download.suggested_filename or "").replace("%", "%25"))
+
+
+def _download_name_spellings(download: DownloadLike) -> tuple[str, ...]:
+ """Every name a writer could have saved this download under: Chrome keeps the escaping the site sent,
+ the download monitor decodes it, so two downloads can differ by spelling alone and share one file."""
+ literal = _download_disk_name(download)
+ decoded = monitor_saved_download_name(download.suggested_filename or "")
+ return (literal,) if decoded in {"", literal} else (literal, decoded)
+
+
+class BlockDownloadLog:
+ """Every download a block's pages start, in start order, and which of them have finished.
+
+ Under the run-scoped binding Chrome overwrites a same-name download in place, and the file ends up
+ holding whichever finished last. Two same-name downloads in flight together therefore leave a file no
+ claim can prove is its own; one started after another has finished simply replaces it.
+ """
+
+ def __init__(self, context: Any) -> None:
+ self._context = context
+ self._pages: list[Any] = []
+ self._downloads: list[DownloadLike] = []
+ self._finished: set[int] = set()
+ self._overlapped: set[int] = set()
+ self._completions: list[asyncio.Future[Any]] = []
+ self._closed = False
+ self._original_paths: dict[int, Callable[[], Awaitable[Any]]] = {}
+
+ # Closures, not bound methods: Playwright tags each handler with an attribute, which a bound
+ # method refuses, and removal needs the same object that was registered.
+ def record(download: DownloadLike) -> None:
+ name = _download_disk_name(download)
+ for earlier in self._downloads:
+ if id(earlier) not in self._finished and _download_disk_name(earlier) == name:
+ self._overlapped.update((id(earlier), id(download)))
+ # Taken as the browser emits the object, before authored code can reach it and rebind path().
+ self._original_paths[id(download)] = download.path
+ self._downloads.append(download)
+ with suppress(Exception):
+ completion = asyncio.get_running_loop().create_task(self._until_finished(download))
+ completion.add_done_callback(partial(self._settle, id(download)))
+ self._completions.append(completion)
+
+ def watch(page: Any) -> None:
+ page.on("download", record)
+ self._pages.append(page)
+
+ self._record = record
+ self._watch = watch
+ # A context that cannot be observed leaves the log empty, so every claimed download reads as
+ # superseded and the attach refuses rather than guessing which bytes are its own.
+ with suppress(Exception):
+ context.on("page", watch)
+ for page in list(context.pages):
+ watch(page)
+
+ def started(self, download: DownloadLike) -> bool:
+ """True only for an object the browser itself emitted; authored code can build a lookalike."""
+ return any(started is download for started in self._downloads)
+
+ def path_of(self, download: DownloadLike) -> Callable[[], Awaitable[Any]]:
+ """The path() the browser's object had when it was emitted, not whatever it holds now."""
+ return self._original_paths.get(id(download), download.path)
+
+ async def _until_finished(self, download: DownloadLike) -> None:
+ # failure() alone is not proof: the raw-CDP engine's gives up after a fixed wait and reports no
+ # failure for a transfer still running. Only a reported failure or a delivered path is.
+ while not self._closed:
+ if await download.failure() is not None:
+ return
+ try:
+ if await self.path_of(download)() is not None:
+ return
+ except Exception:
+ # A path() that cannot be read (a remote Playwright browser) still follows a failure()
+ # that waited for completion; only a None from the raw-CDP timeout means still running.
+ return
+ await asyncio.sleep(1)
+ raise asyncio.CancelledError
+
+ def _settle(self, key: int, completion: asyncio.Future[Any]) -> None:
+ if completion.cancelled():
+ return
+ if completion.exception() is None:
+ self._finished.add(key)
+
+ def shares_name(self, download: DownloadLike) -> bool:
+ """True when any other download this block started could have been saved under ``download``'s name.
+
+ The same equivalence the registered rows are matched under: whatever spelling can select a row must
+ also count as a collision here, or a sibling's row could be taken as the claim's own.
+ """
+ names = _download_name_spellings(download)
+ patterns = [_registered_row_pattern(name) for name in names]
+ for other in self._downloads:
+ if other is download:
+ continue
+ other_names = _download_name_spellings(other)
+ if any(pattern.fullmatch(other_name) for pattern in patterns for other_name in other_names):
+ return True
+ if any(_registered_row_pattern(other_name).fullmatch(name) for other_name in other_names for name in names):
+ return True
+ return False
+
+ def superseded(self, download: DownloadLike) -> bool:
+ """True unless ``download`` is the newest same-name download and none overlapped it in flight."""
+ if id(download) in self._overlapped:
+ return True
+ for index, started in enumerate(self._downloads):
+ if started is download:
+ name = _download_disk_name(download)
+ return any(_download_disk_name(later) == name for later in self._downloads[index + 1 :])
+ return True
+
+ def close(self) -> None:
+ self._closed = True
+ # A stalled transfer never resolves failure(), so the flag alone would leave each tracker holding this
+ # log and its context past the block. Cancelling is safe on both engines: Playwright's failure() and
+ # path() are one channel request per call, and the raw-CDP facade shields its shared future itself.
+ for completion in self._completions:
+ completion.cancel()
+ with suppress(Exception):
+ self._context.remove_listener("page", self._watch)
+ for page in self._pages:
+ with suppress(Exception):
+ page.remove_listener("download", self._record)
+
+
+def _settled_browser_context(download: DownloadLike) -> BrowserContext | None:
+ try:
+ return download.page.context
+ except Exception:
+ return None
+
+
+async def _playwright_download_path(path_of: Callable[[], Awaitable[Any]], deadline: float) -> Path | None:
+ # resolve_artifact_path shields path(), so expiry never cancels a future another awaiter shares.
+ remaining = max(0.0, deadline - asyncio.get_running_loop().time())
+ try:
+ path = await resolve_artifact_path(cast(Any, SimpleNamespace(path=path_of)), remaining)
+ except Exception:
+ return None
+ return None if path is None else Path(path)
+
+
+async def _download_failure(download: DownloadLike, deadline: float) -> str | None:
+ try:
+ async with asyncio.timeout_at(deadline):
+ return await download.failure()
+ except Exception as error:
+ return f"failure_unreadable:{type(error).__name__}"
+
+
+def _entry_identity(path: Path) -> tuple[str, int, int, int] | None:
+ try:
+ info = path.lstat()
+ except OSError:
+ return None
+ return (path.name, info.st_ino, info.st_size, info.st_mtime_ns)
+
+
+def run_directory_entry_identities(download_root: str | Path, run_id: str) -> frozenset[tuple[str, int, int, int]]:
+ """Identify every file already in the run directory, so a later read can tell this block's
+ downloads from the ones it inherited.
+
+ Identity, not a timestamp: Linux stamps files from a coarse clock, so a file written just after a
+ fine-grained ``time.time_ns()`` reading can carry an earlier mtime and look older than the block.
+ """
+ identities: set[tuple[str, int, int, int]] = set()
+ # Recursive: a download object's path() can be reassigned in-process, so an inherited file anywhere
+ # under the run directory must be recognisable, not only one at the top level.
+ for directory, _subdirectories, names in os.walk(_run_directory(download_root, run_id)):
+ for name in names:
+ entry = Path(directory) / name
+ try:
+ info = entry.lstat()
+ except OSError:
+ continue
+ identities.add((entry.name, info.st_ino, info.st_size, info.st_mtime_ns))
+ return frozenset(identities)
+
+
+def _collision_pattern(filename: str) -> re.Pattern[str]:
+ name = PurePath(filename)
+ # Some bindings uniquify a collision as "name (1).ext"; the run-scoped one overwrites instead.
+ return re.compile(rf"^{re.escape(name.stem)}( \(\d+\))?{re.escape(name.suffix)}$")
+
+
+def _registered_row_pattern(filename: str) -> re.Pattern[str]:
+ """As ``_collision_pattern``, but a name the site sent without an extension may have been registered
+ with one the monitor derived from the response type. An extra match is ambiguity, which refuses."""
+ name = PurePath(filename)
+ if name.suffix:
+ return _collision_pattern(filename)
+ return re.compile(rf"^{re.escape(name.stem)}( \(\d+\))?(\.[A-Za-z0-9]{{1,16}})?$")
+
+
+def _settled_downloads_in_run_directory(
+ run_directory: Path, filename: str, inherited: frozenset[tuple[str, int, int, int]]
+) -> list[Path]:
+ """Every file this block could have downloaded under ``filename``, newest first.
+
+ A download object carries no identity the worker can match against a file, so more than one
+ candidate is unresolvable rather than a race to settle: the caller refuses instead of guessing.
+ """
+ collision_pattern = _collision_pattern(filename)
+ matches: list[tuple[int, Path]] = []
+ try:
+ entries = list(run_directory.iterdir())
+ except OSError:
+ return []
+ for entry in entries:
+ if not collision_pattern.fullmatch(entry.name):
+ continue
+ try:
+ info = entry.lstat()
+ except OSError:
+ continue
+ if not stat.S_ISREG(info.st_mode):
+ continue
+ if (entry.name, info.st_ino, info.st_size, info.st_mtime_ns) in inherited:
+ continue
+ matches.append((info.st_mtime_ns, entry))
+ return [entry for _, entry in sorted(matches, reverse=True)]
+
+
+@dataclass(frozen=True, slots=True)
+class RegisteredDownloadSource:
+ """The run's registered DOWNLOAD artifacts, and which of them existed before the claim was armed."""
+
+ probe: DownloadEvidenceProbe
+ organization_id: str
+ run_id: str
+ baseline: Mapping[RegisteredDownloadIdentity, str] | None
+
+ async def fetch(self, artifact_id: str) -> bytes | None:
+ artifact = await app.DATABASE.artifacts.get_artifact_by_id(artifact_id, self.organization_id)
+ if artifact is None or artifact.artifact_type != ArtifactType.DOWNLOAD or artifact.run_id != self.run_id:
+ return None
+ return await app.STORAGE.retrieve_artifact(artifact)
+
+
+def _write_private_copy(run_directory: Path, content: bytes) -> Path:
+ # A dot-directory beneath the run directory: containment still holds, and download registration
+ # lists only the run directory's top-level files, so the copy is never registered a second time.
+ run_directory.mkdir(parents=True, exist_ok=True)
+ target = Path(tempfile.mkdtemp(prefix=".authorized-", dir=run_directory)) / "download"
+ file_fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(file_fd, "wb") as handle:
+ handle.write(content)
+ return target
+
+
+async def _materialize_registered_download(
+ download: DownloadLike,
+ registered: RegisteredDownloadSource,
+ *,
+ run_directory: Path,
+ max_bytes: int,
+ deadline: float,
+ decision: dict[str, str | bool | int | None],
+ decide: Callable[[str], None],
+) -> Path:
+ """Copy the one DOWNLOAD artifact this claim registered into the run directory, verified against its checksum."""
+
+ def refuse(outcome: str) -> AuthorizedFileAccessError:
+ decide(outcome)
+ return AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+
+ baseline = registered.baseline
+ if baseline is None:
+ raise refuse("refused_registration_baseline_unreadable")
+ # Matched under every spelling a writer could have used: an extra match is ambiguity, which refuses.
+ collision_patterns = [_registered_row_pattern(name) for name in _download_name_spellings(download)]
+ matches: list[FileInfo] = []
+ unreadable = False
+ probe_timeouts = 0
+ try:
+ async with asyncio.timeout_at(
+ min(deadline, asyncio.get_running_loop().time() + _REGISTERED_DOWNLOAD_WAIT_SECONDS)
+ ):
+ while not matches:
+ try:
+ async with asyncio.timeout(_REGISTERED_DOWNLOAD_PROBE_TIMEOUT_SECONDS):
+ rows, _ = await registered.probe()
+ except TimeoutError:
+ # A read can wait on a download still in flight, so a slow one is a missed poll, not a refusal.
+ probe_timeouts += 1
+ decision["registration_probe_timeouts"] = probe_timeouts
+ rows = []
+ if rows is None:
+ unreadable = True
+ break
+ matches = [
+ row
+ for row in rows
+ if row.filename
+ and (row.filename, row.checksum) not in baseline
+ and any(pattern.fullmatch(row.filename) for pattern in collision_patterns)
+ ]
+ if not matches:
+ await asyncio.sleep(_REGISTERED_DOWNLOAD_POLL_SECONDS)
+ except TimeoutError:
+ pass
+ except Exception as error:
+ decision["registration_error_type"] = type(error).__name__
+ unreadable = True
+ if unreadable:
+ raise refuse("refused_registration_unreadable")
+ decision["registered_candidates"] = len(matches)
+ if len(matches) != 1:
+ raise refuse("refused_no_registered_download" if not matches else "refused_ambiguous_registered_download")
+ row = matches[0]
+ if row.artifact_id is None:
+ raise refuse("refused_registered_download_without_artifact")
+ if not row.checksum:
+ raise refuse("refused_registered_download_without_checksum")
+ # Storage hands back one bytes object, so the row's size is the only ceiling that can be applied before the
+ # whole artifact is in memory. Registration records it for every download; a row without one is refused.
+ if row.file_size is None:
+ raise refuse("refused_registered_download_without_size")
+ if row.file_size > max_bytes:
+ raise refuse("refused_registered_download_too_large")
+ try:
+ async with asyncio.timeout_at(deadline):
+ content = await registered.fetch(row.artifact_id)
+ except Exception as error:
+ decision["registration_error_type"] = type(error).__name__
+ raise refuse("refused_registration_unreadable") from None
+ if content is None:
+ raise refuse("refused_registered_artifact_unavailable")
+ if len(content) > max_bytes:
+ raise refuse("refused_registered_download_too_large")
+ if hashlib.sha256(content).hexdigest() != row.checksum.lower():
+ raise refuse("refused_registered_checksum_mismatch")
+ try:
+ return await asyncio.to_thread(_write_private_copy, run_directory, content)
+ except OSError as error:
+ decision["registration_error_type"] = type(error).__name__
+ raise refuse("refused_registered_copy_failed") from None
+
+
+async def capture_claimed_download(
+ download: DownloadLike,
+ *,
+ download_root: str | Path,
+ download_run_id: str,
+ organization_id: str | None,
+ max_bytes: int,
+ inherited_files: frozenset[tuple[str, int, int, int]],
+ download_log: BlockDownloadLog | None = None,
+ registered: RegisteredDownloadSource | None = None,
+) -> MaterializedAuthorizedFile:
+ """Turn a download this run claimed into the same run-scoped capability a file_url parameter gets."""
+ run_directory = _run_directory(download_root, download_run_id)
+ decision: dict[str, str | bool | int | None] = {
+ "download_run_id": download_run_id,
+ "organization_id": organization_id,
+ "run_directory": str(run_directory),
+ }
+
+ def decide(outcome: str) -> None:
+ LOG.info("codeblock.download_authorize_decision", outcome=outcome, **decision)
+
+ context = _settled_browser_context(download)
+ # One window for settling, path() and failure(), so a stalled transfer cannot hold a runner past it.
+ deadline = asyncio.get_running_loop().time() + SAVE_DOWNLOADED_FILES_TIMEOUT
+ try:
+ async with asyncio.timeout_at(deadline):
+ async with settle_browser_downloads_for_context(context):
+ pass
+ except Exception as error:
+ decision["settle_error_type"] = type(error).__name__
+ decide("refused_settle_failed")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR) from None
+ # The on-disk name is a GUID, or a collision-suffixed copy of the suggested one.
+ filename = normalize_download_filename(download.suggested_filename or "")
+ path_of = download.path if download_log is None else download_log.path_of(download)
+ playwright_path = await _playwright_download_path(path_of, deadline)
+ settled = playwright_path if playwright_path is not None and playwright_path.is_file() else None
+ if settled is not None and _entry_identity(settled) in inherited_files:
+ decide("refused_inherited_file")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ decision["suggested_name_fp"] = diagnostic_fingerprint(filename)
+ decision["playwright_directory"] = None if playwright_path is None else str(playwright_path.parent)
+ decision["playwright_path_is_file"] = settled is not None
+ from_registered_artifact = False
+ if settled is not None:
+ filename = filename or settled.name
+ else:
+ # Under the run-scoped setDownloadBehavior binding Chrome writes the file itself and Playwright's
+ # own path never exists; the monitor-owned binding saves under names no Download can derive.
+ monitoring = is_monitoring_browser_downloads_for_context(context)
+ decision["monitor_owns_binding"] = monitoring
+ decision["registered_source"] = registered is not None
+ if (monitoring and registered is None) or not filename:
+ decide("refused_no_suggested_name" if not filename else "refused_monitor_owned_binding")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ # The monitor denies the browser's own transfer and fetches the file itself, so Playwright reports
+ # every monitor-owned download as cancelled; the registered artifact is that binding's proof of delivery.
+ failure = await _download_failure(download, deadline)
+ decision["browser_failure"] = failure
+ if failure is not None and not (monitoring and failure == "canceled"):
+ decide("refused_browser_reported_failure")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ if download_log is not None and download_log.superseded(download):
+ decide("refused_superseded_same_name_download")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ candidates: list[Path] = []
+ if not monitoring:
+ candidates = await asyncio.to_thread(
+ _settled_downloads_in_run_directory, run_directory, _download_disk_name(download), inherited_files
+ )
+ decision["run_directory_candidates"] = len(candidates)
+ if len(candidates) > 1:
+ decide("refused_ambiguous_run_directory_file")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ if candidates:
+ settled = candidates[0]
+ elif registered is None:
+ decide("refused_no_fresh_run_directory_file")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ else:
+ # Registered rows carry no link to a Download object, so any same-name download in the block, however
+ # early it started, could own the one row the claim finds.
+ if download_log is None:
+ decide("refused_no_download_log")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ if download_log.shares_name(download):
+ decide("refused_same_name_download_in_block")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ from_registered_artifact = True
+ settled = await _materialize_registered_download(
+ download,
+ registered,
+ run_directory=run_directory,
+ max_bytes=max_bytes,
+ deadline=deadline,
+ decision=decision,
+ decide=decide,
+ )
+ decision["located_directory"] = str(settled.parent)
+ # A refused claim discards the copy this capture wrote: the private directory is unreachable once the
+ # token is withheld, and a block can lose the race repeatedly under names that never repeat.
+ private_copy = settled.parent if from_registered_artifact else None
+ try:
+ try:
+ materialized = await asyncio.to_thread(
+ capture_authorized_file,
+ settled,
+ download_root=download_root,
+ workflow_run_id=download_run_id,
+ organization_id=organization_id,
+ max_bytes=max_bytes,
+ filename=filename,
+ )
+ except AuthorizedFileAccessError:
+ decide("refused_capture")
+ raise
+ # Checked again once the bytes are captured: a same-name download that started during the scan could
+ # have overwritten the file first. One that starts later is caught when the captured hash is re-verified.
+ if download_log is not None and download_log.superseded(download):
+ decide("refused_superseded_during_capture")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ # A registered row is matched by collision-equivalent name, which supersession compares exactly, so a
+ # sibling that started while the poll was waiting could own the row this claim just took.
+ if from_registered_artifact and download_log is not None and download_log.shares_name(download):
+ decide("refused_same_name_download_during_capture")
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ except BaseException:
+ if private_copy is not None:
+ with suppress(OSError):
+ await asyncio.to_thread(shutil.rmtree, private_copy)
+ raise
+ decide("authorized_registered_artifact" if from_registered_artifact else "authorized")
+ return materialized
+
+
async def attach_materialized_authorized_file(
locate: Callable[[str], FileInputLocator],
authorized_file: MaterializedAuthorizedFile,
@@ -254,8 +795,11 @@ def bind_inline_attach_authorized_file(
workflow_run_id: str,
organization_id: str | None,
max_bytes: int,
+ download_run_id: str | None = None,
+ download_log: BlockDownloadLog | None = None,
locate: Callable[[str], FileInputLocator] | None = None,
-) -> Callable[[FileInputTarget, str, str], Awaitable[dict[str, str | int]]]:
+ registered_downloads: RegisteredDownloadSource | None = None,
+) -> Callable[[FileInputTarget, str | DownloadLike, str], Awaitable[dict[str, str | int]]]:
authorized_by_path = {
inline_authorized_file_path(item, download_root=download_root): item
for item in materializations.values()
@@ -271,20 +815,56 @@ def bind_inline_attach_authorized_file(
if locate is None and (page_locator := getattr(type(expected_page), "locator", None)) is not None:
locate = partial(page_locator, expected_page)
+ download_key = download_run_id or workflow_run_id
+ inherited_files = run_directory_entry_identities(download_root, download_key)
+ # One capture per claimed download: a block can attach the same download to several inputs, and the
+ # registered-artifact path writes a private copy each time it runs. Identity keeps the list short and
+ # exact; redemption re-verifies the copy on every attach, as it does for a file_url.
+ claimed_captures: list[tuple[DownloadLike, MaterializedAuthorizedFile]] = []
+
async def attach_authorized_file(
page: FileInputTarget,
- file: str,
+ file: str | DownloadLike,
selector: str,
) -> dict[str, str | int]:
if page is not expected_page:
raise AuthorizedFileAccessError("attach_authorized_file requires the current CodeBlock page.")
- authorized_file = authorized_by_path.get(file) if isinstance(file, str) else None
- if authorized_file is None:
- if isinstance(file, str) and file in failed_values:
+ # Capability, not class identity: a raw-CDP download is not a Playwright ``Download``, and the
+ # bytes come from the run's own download directory either way, never from this object.
+ if is_download_like(file):
+ # Authored code hands this object in and can build a lookalike, so the only proof of a claim
+ # is that the browser emitted this exact object. The secure lane never takes one from the sandbox.
+ if download_log is None or not download_log.started(file):
+ LOG.info(
+ "codeblock.download_authorize_decision",
+ outcome="refused_unclaimed_download_object",
+ download_run_id=download_key,
+ organization_id=organization_id,
+ )
raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
- raise AuthorizedFileAccessError(
- "attach_authorized_file accepts only a materialized file_url parameter from this run."
- )
+ run_key = download_key
+ captured = next((item for claimed, item in claimed_captures if claimed is file), None)
+ if captured is None:
+ captured = await capture_claimed_download(
+ file,
+ download_root=download_root,
+ download_run_id=run_key,
+ organization_id=organization_id,
+ max_bytes=max_bytes,
+ inherited_files=inherited_files,
+ download_log=download_log,
+ registered=registered_downloads,
+ )
+ claimed_captures.append((file, captured))
+ authorized_file = captured
+ else:
+ run_key = workflow_run_id
+ resolved = authorized_by_path.get(file) if isinstance(file, str) else None
+ if resolved is None:
+ if isinstance(file, str) and file in failed_values:
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_UNAVAILABLE_ERROR)
+ raise AuthorizedFileAccessError(AUTHORIZED_FILE_SHAPE_ERROR)
+ authorized_file = resolved
if locate is None:
raise AuthorizedFileAccessError("attach_authorized_file requires the current CodeBlock page.")
return await attach_materialized_authorized_file(
@@ -292,7 +872,7 @@ def bind_inline_attach_authorized_file(
authorized_file,
selector,
download_root=download_root,
- workflow_run_id=workflow_run_id,
+ workflow_run_id=run_key,
organization_id=organization_id,
max_bytes=max_bytes,
)
diff --git a/skyvern/forge/sdk/workflow/models/_jinja.py b/skyvern/forge/sdk/workflow/models/_jinja.py
index 2d3daf2f4..233837406 100644
--- a/skyvern/forge/sdk/workflow/models/_jinja.py
+++ b/skyvern/forge/sdk/workflow/models/_jinja.py
@@ -5,10 +5,10 @@ from __future__ import annotations
import io
import json
import tokenize
-from typing import Any, Callable, cast
+from typing import Any, Callable, NoReturn, cast
import structlog
-from jinja2 import ChainableUndefined, StrictUndefined
+from jinja2 import ChainableUndefined, StrictUndefined, Undefined
from jinja2.sandbox import SandboxedEnvironment
from skyvern.config import settings
@@ -152,6 +152,20 @@ jinja_json_finalize_required_binding_env = SandboxedEnvironment(
)
jinja_json_finalize_required_binding_env.filters["json"] = _json_type_filter
+
+def _fail_on_undefined_json(value: object) -> NoReturn:
+ if isinstance(value, Undefined):
+ value._fail_with_undefined_error()
+ raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
+
+
+# `| tojson` serializes with json.dumps, which never calls __str__, so an undefined would surface as a
+# generic TypeError instead of the UndefinedError that names the missing binding.
+jinja_json_finalize_required_binding_env.policies["json.dumps_kwargs"] = {
+ **jinja_json_finalize_required_binding_env.policies["json.dumps_kwargs"],
+ "default": _fail_on_undefined_json,
+}
+
if settings.WORKFLOW_TEMPLATING_STRICTNESS == "strict":
jinja_json_finalize_strict_env = SandboxedEnvironment(undefined=StrictUndefined, finalize=_json_finalize)
else:
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 53fafbb60..79ac4d9f6 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -20,8 +20,10 @@ import shutil
import smtplib
import socket
import ssl
+import sys
import tempfile
import textwrap
+import traceback
import unicodedata
import uuid
import zipfile
@@ -62,7 +64,7 @@ from jinja2.sandbox import SandboxedEnvironment
from jsonschema import Draft202012Validator
from jsonschema.exceptions import ValidationError
from opentelemetry import trace as otel_trace
-from playwright.async_api import BrowserContext, CDPSession, Frame, Page
+from playwright.async_api import BrowserContext, CDPSession, Download, Frame, Page
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator
from sqlalchemy.exc import InterfaceError, OperationalError, SQLAlchemyError
@@ -182,7 +184,11 @@ from skyvern.forge.sdk.workflow.code_block_authorized_files import (
AuthorizedFileAccessError,
AuthorizedFileMaterialization,
AuthorizedFileMaterializationFailure,
+ BlockDownloadLog,
+ DownloadEvidenceProbe,
MaterializedAuthorizedFile,
+ RegisteredDownloadIdentity,
+ RegisteredDownloadSource,
bind_inline_attach_authorized_file,
capture_authorized_file,
inline_authorized_file_path,
@@ -230,6 +236,7 @@ from skyvern.forge.sdk.workflow.models._jinja import (
)
from skyvern.forge.sdk.workflow.models.code_block_recorder import (
CODE_BLOCK_FILENAME,
+ CODE_LINE_OFFSET,
RECORDED_FAILURE_RESPONSE_MAX_CHARS,
RecordingPage,
json_safe_recorder_output,
@@ -1752,13 +1759,18 @@ class Block(BaseModel, abc.ABC):
failure_reason = get_user_facing_exception_message(e)
elif self.block_type in {BlockType.CODE, BlockType.FOR_LOOP, BlockType.WHILE_LOOP}:
failure_label = "CodeBlock" if self.block_type == BlockType.CODE else "Loop block"
+ # No exc_info here: prod renders the __context__ chain and message; the dev renderer also dumps locals.
+ summary = e if isinstance(e, CodeBlockMachineryFailure) else _summarize_machinery_exception(e)
LOG.error(
f"{failure_label} execution failed",
workflow_run_id=workflow_run_id,
block_label=self.label,
block_type=self.block_type,
+ exception_class=summary.operator_class,
+ failing_line=summary.failing_line,
+ stack=summary.stack,
)
- failure_reason = f"{failure_label} execution failed."
+ failure_reason = summary.customer_reason(failure_label)
else:
LOG.exception(
"Block execution failed",
@@ -2859,7 +2871,7 @@ async def _execute_parameter_observing_block_safe(
propagated_error = (
exc.with_traceback(None)
if app.AGENT_FUNCTION.prepare_codeblock_control_flow_exception(exc)
- else RuntimeError()
+ else _summarize_machinery_exception(exc)
)
del self, workflow_run_id, parent_workflow_run_block_id, organization_id, browser_session_id
del current_value, current_index, kwargs, exc
@@ -4681,6 +4693,74 @@ CODE_BLOCK_GENERIC_FAILURE_REASON = "Failed to execute code block."
CODE_BLOCK_FAILURE_REASON_MAX_CHARS = 2000
+MACHINERY_STACK_MAX_FRAMES = 40
+USER_CODE_MODULE_NAME = "skyvern.code_block"
+
+
+class CodeBlockMachineryFailure(RuntimeError):
+ """Replaces an exception escaping CodeBlock.execute, carrying only platform-authored str/int fields."""
+
+ def __init__(
+ self,
+ *,
+ builtin_class: str | None,
+ operator_class: str | None,
+ failing_line: int | None,
+ stack: list[str],
+ ) -> None:
+ super().__init__()
+ self.builtin_class = builtin_class
+ self.operator_class = operator_class
+ self.failing_line = failing_line
+ self.stack = stack
+
+ def customer_reason(self, label: str) -> str:
+ reason = f"{label} failed"
+ if self.builtin_class:
+ reason = f"{reason} with {self.builtin_class}"
+ if label != "CodeBlock":
+ return f"{reason}."
+ reason = f"{reason} inside Skyvern"
+ if self.failing_line is not None:
+ reason = f"{reason} while running line {self.failing_line}"
+ return f"{reason}."
+
+
+def _summarize_machinery_exception(exc: BaseException) -> CodeBlockMachineryFailure:
+ # Reads go through BaseException.__getattribute__ under a blanket except so a hostile hook can
+ # neither inject text nor, by raising before `del exc`, chain the original as __context__.
+ try:
+ if type(exc) is CodeBlockMachineryFailure:
+ return CodeBlockMachineryFailure(
+ builtin_class=exc.builtin_class,
+ operator_class=exc.operator_class,
+ failing_line=exc.failing_line,
+ stack=exc.stack,
+ )
+ cls = type(exc)
+ is_builtin = getattr(builtins, cls.__name__, None) is cls and issubclass(cls, Exception)
+ # Identity-bound in sys.modules under its own name: user code can set __module__ to anything.
+ module = sys.modules.get(cls.__module__)
+ is_platform_class = cls.__module__ != USER_CODE_MODULE_NAME and getattr(module, cls.__name__, None) is cls
+ frames = [
+ f"{CODE_BLOCK_FILENAME}:{max(lineno - CODE_LINE_OFFSET, 1)}"
+ if frame.f_code.co_filename == CODE_BLOCK_FILENAME
+ else f"{frame.f_code.co_filename}:{lineno} in {frame.f_code.co_name}"
+ for frame, lineno in traceback.walk_tb(BaseException.__getattribute__(exc, "__traceback__"))
+ ]
+ if len(frames) > MACHINERY_STACK_MAX_FRAMES:
+ dropped = len(frames) - MACHINERY_STACK_MAX_FRAMES
+ frames = [f"... {dropped} earlier frames", *frames[-MACHINERY_STACK_MAX_FRAMES:]]
+ return CodeBlockMachineryFailure(
+ builtin_class=cls.__name__ if is_builtin else None,
+ operator_class=f"{cls.__module__}.{cls.__name__}" if is_platform_class else None,
+ failing_line=user_code_line_from_exception(exc),
+ stack=frames,
+ )
+ except BaseException:
+ return CodeBlockMachineryFailure(builtin_class=None, operator_class=None, failing_line=None, stack=[])
+
+
def _code_block_failure_action(*, failing_line: int | None, action_order: int, response: str = "") -> Action:
return Action(
action_id=generate_action_id(),
@@ -4753,6 +4833,17 @@ def _bind_code_block_solve_captcha(
return solve_captcha
+def _sheets_read_output_keys(workflow_run_context: WorkflowRunContext) -> set[str]:
+ workflow = workflow_run_context.workflow
+ if workflow is None or workflow.workflow_definition is None:
+ return set()
+ return {
+ block.output_parameter.key
+ for block in get_all_blocks(workflow.workflow_definition.blocks)
+ if block.block_type == BlockType.GOOGLE_SHEETS_READ
+ }
+
+
def _register_code_block_secret(workflow_run_context: WorkflowRunContext, value: str) -> None:
# Every caller registers a one-time code minted at runtime, so it goes through the runtime OTP
# path: that set is what the copilot's origin-run handoff publishes, and a code minted here
@@ -4896,20 +4987,113 @@ _OTP_VERB_BY_TYPE = {
OTPType.MAGIC_LINK: "await <credential>.magic_link(page)",
}
+_OTP_NOUN_BY_TYPE = {
+ OTPType.TOTP: "code",
+ OTPType.MAGIC_LINK: "sign-in link",
+}
+
+
+def _otp_sources_checked(
+ totp_identifier: str,
+ expected_otp_type: OTPType,
+ email_context: otp_email.EmailOTPVerificationContext,
+ raw_context: otp_service.RawOTPVerificationContext,
+) -> str:
+ """Counts only: addresses, credential ids, identifiers and codes must never reach this text."""
+ inbox_facts: list[str] = []
+ # An identifier without an "@" never reaches the inbox search, so no mailbox fact holds for it.
+ inboxes_apply = "@" in totp_identifier
+ connected_everywhere_empty = inboxes_apply
+ if inboxes_apply:
+ for label, source_name in (
+ ("Gmail", otp_email.GmailOTPSource.name),
+ ("Outlook", otp_email.OutlookOTPSource.name),
+ ):
+ source = email_context.per_source.get(source_name)
+ if source is None:
+ inbox_facts.append(f"{label} inboxes not checked")
+ connected_everywhere_empty = False
+ elif source.credential_ids is None:
+ inbox_facts.append(f"{label} inbox list never loaded")
+ connected_everywhere_empty = False
+ elif not source.credential_ids:
+ if source.credential_list_refresh_failed:
+ inbox_facts.append(f"{label} inbox list not refreshed")
+ connected_everywhere_empty = False
+ else:
+ inbox_facts.append(f"no {label} inbox connected")
+ else:
+ connected_everywhere_empty = False
+ connected = set(source.credential_ids)
+ inboxes = len(connected)
+ # Counted here rather than pruned on refresh: the message sets also drive dedupe,
+ # and forgetting a key would re-parse a message the caller already paid for.
+ messages = sum(1 for credential_id, _ in source.seen_message_keys if credential_id in connected)
+ unreadable = sum(1 for credential_id, _ in source.unreadable_message_keys if credential_id in connected)
+ capped = source.messages_evicted
+ shown = f"{messages}+" if capped else str(messages)
+ if messages and unreadable:
+ reached = messages + unreadable
+ # One count carries both: an appended clause would not survive the shortest
+ # consumer, and a bare checked count hides the candidates the parser refused.
+ read_fact = f"{shown} of {reached}{'+' if capped else ''} messages read"
+ elif messages:
+ read_fact = f"{shown} message{'s' if messages != 1 else ''} checked"
+ elif source.failed_credential_ids:
+ read_fact = "search failed"
+ elif unreadable:
+ read_fact = f"{unreadable} message{'s' if unreadable != 1 else ''} could not be read"
+ else:
+ read_fact = "no messages read"
+ plural = "es" if inboxes != 1 else ""
+ # Coverage shares the clause with the read fact, which on its own would hide an inbox
+ # that failed or was still in flight whenever a sibling inbox answered.
+ searched = len(source.completed_credential_ids & connected)
+ coverage = (
+ f"{searched} of {inboxes} {label} inbox{plural} searched"
+ if searched < inboxes
+ else f"{inboxes} {label} inbox{plural} connected"
+ )
+ inbox_facts.append(f"{coverage}, {read_fact}")
+ rows = len(raw_context.seen_row_ids)
+ noun = _OTP_NOUN_BY_TYPE.get(expected_otp_type, "OTP")
+ store_empty = raw_context.store_queried and not rows
+ if connected_everywhere_empty and store_empty:
+ return f"No Gmail or Outlook inbox is connected and no {noun} has been stored."
+ if not raw_context.store_queried and all(fact.endswith("not checked") for fact in inbox_facts):
+ return "No delivery source was checked before the wait ended."
+ if not raw_context.store_queried:
+ row_fact = f"stored {noun}s not checked"
+ elif rows:
+ # "found", not "checked": the reparse budget stops the scan before every row is parsed.
+ row_fact = f"{rows} stored OTP message{'s' if rows != 1 else ''} found"
+ else:
+ row_fact = f"no {noun} has been stored"
+ return f"Sources checked: {'; '.join([*inbox_facts, row_fact])}."
+
def _otp_wait_failure(
+ totp_identifier: str,
expected_otp_type: OTPType,
- observed_otp_types: set[OTPType],
+ email_context: otp_email.EmailOTPVerificationContext,
+ raw_context: otp_service.RawOTPVerificationContext,
budget_seconds: int,
) -> CodeBlockOTPError:
- """Turn a wait that produced nothing into a mismatch report when the other kind of OTP arrived.
+ """Report what the wait observed: a mismatch when the other kind of OTP arrived, otherwise the
+ sources it checked.
- A wrong verb otherwise looks exactly like a mailbox that stayed empty, which leaves the
- authoring retry with nothing to act on.
+ Both exist because a wrong verb and an unreachable mailbox otherwise look exactly like a mailbox
+ that stayed empty, which leaves the authoring retry with nothing to act on.
"""
+ observed_otp_types = email_context.observed_otp_types | raw_context.observed_otp_types
mismatched = sorted(observed for observed in observed_otp_types if observed is not expected_otp_type)
if not mismatched:
- return CodeBlockOTPError(f"OTP was not received within {budget_seconds} seconds.")
+ # Sources first: every downstream cap slices a prefix, and the shortest (120 chars in
+ # copilot turn compaction) starts after a ~45-char platform frame.
+ return CodeBlockOTPError(
+ f"{_otp_sources_checked(totp_identifier, expected_otp_type, email_context, raw_context)} "
+ f"OTP was not received within {budget_seconds} seconds."
+ )
found = ", ".join(observed.value for observed in mismatched)
# .get, not [], so a future OTPType cannot turn this error path into a KeyError.
suggested = _OTP_VERB_BY_TYPE.get(mismatched[0], "the matching verb")
@@ -4968,11 +5152,7 @@ async def _poll_code_block_otp(
timeout=budget_seconds,
)
except asyncio.TimeoutError:
- raise _otp_wait_failure(
- expected_otp_type,
- email_context.observed_otp_types | raw_context.observed_otp_types,
- budget_seconds,
- )
+ raise _otp_wait_failure(totp_identifier, expected_otp_type, email_context, raw_context, budget_seconds)
except (NoTOTPVerificationCodeFound, FailedToGetTOTPVerificationCode):
raise CodeBlockOTPError(f"OTP could not be retrieved for {subject}.")
@@ -5190,9 +5370,6 @@ _DOWNLOAD_CLAIM_CLICK_TIMEOUT_SECONDS = 15
_DOWNLOAD_CLAIM_EVIDENCE_TIMEOUT_SECONDS = 10
_DOWNLOAD_CLAIM_FALLBACK_STEM = "downloaded_file"
-DownloadEvidenceProbe = Callable[[], Awaitable[tuple[list[FileInfo] | None, set[str]]]]
-_DownloadIdentity = tuple[str | None, str | None]
-
def _download_monitor_owns_binding(page: Page | RecordingPage) -> bool:
"""True when the CDP download monitor, not the browser, is delivering this context's downloads.
@@ -5207,7 +5384,7 @@ def _download_monitor_owns_binding(page: Page | RecordingPage) -> bool:
async def _registered_download_identities(
download_evidence: DownloadEvidenceProbe | None,
-) -> dict[_DownloadIdentity, str] | None:
+) -> dict[RegisteredDownloadIdentity, str] | None:
"""Registered downloads keyed by an identity two reads agree on, or ``None`` when registration
could not be read — never proof that nothing arrived. The probe re-runs registration, so it is
bounded here rather than left to spend its own minutes-long budget on a failing claim."""
@@ -5224,9 +5401,32 @@ async def _registered_download_identities(
return {(file_info.filename, file_info.checksum): file_info.filename or "" for file_info in registered}
+async def _registered_download_source(
+ download_evidence: DownloadEvidenceProbe | None,
+ page: Page | RecordingPage,
+ *,
+ download_binding: DownloadBinding | None,
+ organization_id: str | None,
+ download_run_id: str,
+) -> RegisteredDownloadSource | None:
+ """What a claimed download can be resolved from when its bytes never reach this worker's disk."""
+ # Without artifact signing the run-scoped listing carries no artifact ids, so no row could ever resolve.
+ if download_evidence is None or not organization_id or not settings.ARTIFACT_CONTENT_HMAC_KEYRING:
+ return None
+ if download_binding is not DownloadBinding.SESSION_DIR and not _download_monitor_owns_binding(page):
+ return None
+ identities = await _registered_download_identities(download_evidence)
+ return RegisteredDownloadSource(
+ probe=download_evidence,
+ organization_id=organization_id,
+ run_id=download_run_id,
+ baseline=identities,
+ )
+
+
async def _newly_registered_download_name(
download_evidence: DownloadEvidenceProbe | None,
- registered_before_click: dict[_DownloadIdentity, str] | None,
+ registered_before_click: Mapping[RegisteredDownloadIdentity, str] | None,
) -> str | None:
"""The name of a file this click registered, or ``None`` when no new registration can be proven.
@@ -5256,6 +5456,8 @@ async def _code_block_click_and_claim_download_builtin(
action: Callable[[], Awaitable[None]] | None = None,
timeout_seconds: float | None = None,
outcome_recorder: DownloadClaimOutcomeRecorder | None = None,
+ on_claimed: Callable[[Download], None] | None = None,
+ registered_downloads: RegisteredDownloadSource | None = None,
) -> str:
"""Click ``selector`` once and confirm the browser download it fires, returning the sanitized
suggested filename as a summary.
@@ -5287,11 +5489,12 @@ async def _code_block_click_and_claim_download_builtin(
click_error: BaseException | None = None
# Only a binding whose delivery this page cannot observe can reach the grace branch below, so
# the extra registration read is taken for those claims alone.
- registered_before_click = (
- await _registered_download_identities(download_evidence)
- if download_binding is DownloadBinding.SESSION_DIR or _download_monitor_owns_binding(page)
- else None
- )
+ if registered_downloads is not None:
+ registered_before_click = registered_downloads.baseline
+ elif download_binding is DownloadBinding.SESSION_DIR or _download_monitor_owns_binding(page):
+ registered_before_click = await _registered_download_identities(download_evidence)
+ else:
+ registered_before_click = None
# A provider-owned session delivers the bytes on its own connection, so this page may never see
# the event at all (SKY-11371). Wait briefly for one — even when the caller asked for longer,
# since registration evidence, not the event, is that binding's proof of delivery.
@@ -5320,6 +5523,8 @@ async def _code_block_click_and_claim_download_builtin(
click_error = exc
raise
download = await claim.value
+ if on_claimed is not None:
+ on_claimed(download)
except CodeBlockDownloadClaimError:
raise
except Exception as exc:
@@ -5827,7 +6032,7 @@ class CodeBlock(Block):
**safe_builtins(),
# LOAD_BUILD_CLASS and the class body's implicit __module__ binding resolve these here.
"__build_class__": _code_block_build_class,
- "__name__": "skyvern.code_block",
+ "__name__": USER_CODE_MODULE_NAME,
},
"print": print,
"sleep": asyncio.sleep,
@@ -5860,6 +6065,8 @@ class CodeBlock(Block):
download_evidence: DownloadEvidenceProbe | None = None,
download_claim_outcome_recorder: DownloadClaimOutcomeRecorder | None = None,
authorized_file_materializations: Mapping[str, AuthorizedFileMaterialization] | None = None,
+ download_log: BlockDownloadLog | None = None,
+ registered_downloads: RegisteredDownloadSource | None = None,
) -> Callable[[], Awaitable[dict[str, Any]]]:
# SECURITY: validate before exec(). The AST check must run on the raw
# user code so it can block dunder identifiers like __capture_locals.
@@ -5911,7 +6118,10 @@ class CodeBlock(Block):
workflow_run_id=workflow_run_id or "",
organization_id=organization_id,
max_bytes=settings.MAX_UPLOAD_FILE_SIZE,
+ download_run_id=download_run_id,
+ download_log=download_log,
locate=page._pinned_locator() if isinstance(page, RecordingPage) else None,
+ registered_downloads=registered_downloads,
)
safe_vars["search_web"] = _bind_code_block_search_web(page)
safe_vars["page"] = page
@@ -8249,7 +8459,7 @@ async def wrapper({default_args}):
elif app.AGENT_FUNCTION.prepare_codeblock_control_flow_exception(exc):
propagated_error = exc.with_traceback(None)
else:
- propagated_error = RuntimeError()
+ propagated_error = _summarize_machinery_exception(exc)
del self, workflow_run_id, workflow_run_block_id, organization_id, browser_session_id, kwargs, exc
raise propagated_error from None
@@ -8322,178 +8532,211 @@ async def wrapper({default_args}):
organization_id=organization_id,
)
- await self._ensure_run_recording_artifact(
- browser_state=browser_state,
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- organization_id=organization_id,
- browser_session_id=browser_session_id,
- )
+ # As soon as the page is final: every setup await below is long enough for a page-initiated download
+ # to start and register, and a download the log never saw cannot be ruled out as the owner of a row a
+ # later claim finds. Each exit between here and the block's own teardown closes it. A page whose
+ # context cannot be read observes nothing, which the log already treats as refusing every claim.
+ download_log = BlockDownloadLog(getattr(page, "context", None))
+ # Setup can raise before the block's own try takes over closing the log, and a page in a
+ # persistent session outlives the block, so a leaked listener would keep recording on it.
try:
- authored_code = self.render_code_with_reference(workflow_run_context)
- except Exception as e:
- return await self._template_format_failure_result(
- e,
- "Failed to format CodeBlock parameters.",
- workflow_run_context,
- workflow_run_id,
- workflow_run_block_id,
- organization_id,
- can_continue_after_failure=False,
+ await self._ensure_run_recording_artifact(
+ browser_state=browser_state,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
)
- # get all parameters into a dictionary
- parameter_values = {}
- authorized_file_materializations: dict[str, AuthorizedFileMaterialization] = {}
- credential_parameter_keys: set[str] = set()
- credential_release_guard = CredentialReleaseGuard(workflow_run_id=workflow_run_id, block_label=self.label)
- for parameter in self.parameters:
- value = workflow_run_context.get_value(parameter.key)
- if not parameter.parameter_type.is_secret_or_credential() and not (
- # NOTE: skyvern credential is a 'credential_id' workflow parameter type
- parameter.parameter_type == ParameterType.WORKFLOW
- and parameter.workflow_parameter_type is not None
- and parameter.workflow_parameter_type.is_credential_type()
- ):
- if (
- isinstance(parameter, WorkflowParameter)
- and parameter.workflow_parameter_type == WorkflowParameterType.FILE_URL
+ try:
+ authored_code = self.render_code_with_reference(workflow_run_context)
+ except Exception as e:
+ download_log.close()
+ return await self._template_format_failure_result(
+ e,
+ "Failed to format CodeBlock parameters.",
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ can_continue_after_failure=False,
+ )
+
+ # get all parameters into a dictionary
+ parameter_values = {}
+ authorized_file_materializations: dict[str, AuthorizedFileMaterialization] = {}
+ credential_parameter_keys: set[str] = set()
+ credential_release_guard = CredentialReleaseGuard(workflow_run_id=workflow_run_id, block_label=self.label)
+ sheets_read_output_keys = _sheets_read_output_keys(workflow_run_context)
+ sheets_read_parameter_keys: list[str] = []
+ for parameter in self.parameters:
+ value = workflow_run_context.get_value(parameter.key)
+ if not parameter.parameter_type.is_secret_or_credential() and not (
+ # NOTE: skyvern credential is a 'credential_id' workflow parameter type
+ parameter.parameter_type == ParameterType.WORKFLOW
+ and parameter.workflow_parameter_type is not None
+ and parameter.workflow_parameter_type.is_credential_type()
):
- materialization = await self._materialize_file_parameter_path(
- value,
- parameter_key=parameter.key,
- materialized_file_paths=workflow_run_context.materialized_file_paths,
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- )
- if materialization is not None:
- authorized_file_materializations[parameter.key] = materialization
- if isinstance(materialization, MaterializedAuthorizedFile):
- value = inline_authorized_file_path(materialization, download_root=settings.DOWNLOAD_PATH)
- # A materialized input is part of the block's starting state, not a download it made.
- download_dir_before = local_download_dir_file_identities(resolved_download_id)
- parameter_values[parameter.key] = value
- continue
- credential_parameter_keys.add(parameter.key)
- if isinstance(value, dict):
- real_secret_values = {}
- for credential_field, credential_place_holder in value.items():
- # "context" is a skyvern-defined field to reduce LLM hallucination
- if credential_field == "context":
- continue
- secret_value = workflow_run_context.get_original_secret_value_or_none(credential_place_holder)
if (
- secret_value == BitwardenConstants.TOTP
- or secret_value == OnePasswordConstants.TOTP
- or secret_value == AzureVaultConstants.TOTP
+ isinstance(parameter, WorkflowParameter)
+ and parameter.workflow_parameter_type == WorkflowParameterType.FILE_URL
):
- totp_secret_key = workflow_run_context.totp_secret_value_key(credential_place_holder)
- totp_secret = workflow_run_context.get_original_secret_value_or_none(totp_secret_key)
- if totp_secret:
- secret_value = generate_totp_code(totp_secret)
- # The pre-minted .totp string is exposed to user code (legacy path),
- # so register it for masking like any other resolved secret.
- _register_code_block_secret(workflow_run_context, secret_value)
- else:
- LOG.warning(
- "No TOTP secret found, returning the parameter value as is",
- parameter_key=parameter.key,
- )
-
- real_secret_value = secret_value if secret_value is not None else credential_place_holder
- parameter_values[credential_field] = real_secret_value
- real_secret_values[credential_field] = real_secret_value
- credential_namespace = Credential(**real_secret_values)
- credential_namespace.otp = _bind_code_block_otp(parameter.key, organization_id, workflow_run_id)
- credential_namespace.magic_link = _bind_code_block_magic_link(
- parameter.key, organization_id, workflow_run_id
- )
- parameter_values[parameter.key] = credential_namespace
- tested_url = workflow_run_context.credential_tested_urls.get(parameter.key)
- armed_any = False
- if tested_url:
- for credential_field, secret in real_secret_values.items():
- # card_brand and friends are stored as plain values on purpose; arming them
- # would refuse an ordinary off-site field that happens to read "visa".
- if credential_field in NON_SECRET_CREDENTIAL_FIELDS:
+ materialization = await self._materialize_file_parameter_path(
+ value,
+ parameter_key=parameter.key,
+ materialized_file_paths=workflow_run_context.materialized_file_paths,
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if materialization is not None:
+ authorized_file_materializations[parameter.key] = materialization
+ if isinstance(materialization, MaterializedAuthorizedFile):
+ value = inline_authorized_file_path(materialization, download_root=settings.DOWNLOAD_PATH)
+ # A materialized input is part of the block's starting state, not a download it made.
+ download_dir_before = local_download_dir_file_identities(resolved_download_id)
+ if (
+ isinstance(parameter, OutputParameter)
+ and parameter.key in sheets_read_output_keys
+ and isinstance(value, dict)
+ and "cells" in value
+ ):
+ sheets_read_parameter_keys.append(parameter.key)
+ parameter_values[parameter.key] = value
+ continue
+ credential_parameter_keys.add(parameter.key)
+ if isinstance(value, dict):
+ real_secret_values = {}
+ for credential_field, credential_place_holder in value.items():
+ # "context" is a skyvern-defined field to reduce LLM hallucination
+ if credential_field == "context":
continue
- armed_any |= credential_release_guard.arm(secret, tested_url, parameter.key)
- if not armed_any:
- # Coverage is only measurable if the unarmed case says so: a credential with no
- # tested_url has no release scope, so its secrets are unguarded on this path.
- LOG.info(
- "codeblock_credential_release_unarmed",
- parameter_key=parameter.key,
- reason="credential has no usable tested_url",
- workflow_run_id=workflow_run_id,
- block_label=self.label,
+ secret_value = workflow_run_context.get_original_secret_value_or_none(credential_place_holder)
+ if (
+ secret_value == BitwardenConstants.TOTP
+ or secret_value == OnePasswordConstants.TOTP
+ or secret_value == AzureVaultConstants.TOTP
+ ):
+ totp_secret_key = workflow_run_context.totp_secret_value_key(credential_place_holder)
+ totp_secret = workflow_run_context.get_original_secret_value_or_none(totp_secret_key)
+ if totp_secret:
+ secret_value = generate_totp_code(totp_secret)
+ # The pre-minted .totp string is exposed to user code (legacy path),
+ # so register it for masking like any other resolved secret.
+ _register_code_block_secret(workflow_run_context, secret_value)
+ else:
+ LOG.warning(
+ "No TOTP secret found, returning the parameter value as is",
+ parameter_key=parameter.key,
+ )
+
+ real_secret_value = secret_value if secret_value is not None else credential_place_holder
+ parameter_values[credential_field] = real_secret_value
+ real_secret_values[credential_field] = real_secret_value
+ credential_namespace = Credential(**real_secret_values)
+ credential_namespace.otp = _bind_code_block_otp(parameter.key, organization_id, workflow_run_id)
+ credential_namespace.magic_link = _bind_code_block_magic_link(
+ parameter.key, organization_id, workflow_run_id
)
- else:
- secret_value = workflow_run_context.get_original_secret_value_or_none(value)
- parameter_values[parameter.key] = secret_value if secret_value is not None else value
+ parameter_values[parameter.key] = credential_namespace
+ tested_url = workflow_run_context.credential_tested_urls.get(parameter.key)
+ armed_any = False
+ if tested_url:
+ for credential_field, secret in real_secret_values.items():
+ # card_brand and friends are stored as plain values on purpose; arming them
+ # would refuse an ordinary off-site field that happens to read "visa".
+ if credential_field in NON_SECRET_CREDENTIAL_FIELDS:
+ continue
+ armed_any |= credential_release_guard.arm(secret, tested_url, parameter.key)
+ if not armed_any:
+ # Coverage is only measurable if the unarmed case says so: a credential with no
+ # tested_url has no release scope, so its secrets are unguarded on this path.
+ LOG.info(
+ "codeblock_credential_release_unarmed",
+ parameter_key=parameter.key,
+ reason="credential has no usable tested_url",
+ workflow_run_id=workflow_run_id,
+ block_label=self.label,
+ )
+ else:
+ secret_value = workflow_run_context.get_original_secret_value_or_none(value)
+ parameter_values[parameter.key] = secret_value if secret_value is not None else value
- serialized_parameter_values = app.AGENT_FUNCTION.serialize_codeblock_parameters(parameter_values)
+ try:
+ use_codeblock_runner = await app.AGENT_FUNCTION.should_use_codeblock_runner(
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ workflow_run_context=workflow_run_context,
+ organization_id=organization_id,
+ block_label=self.label,
+ browser_session_id=browser_session_id,
+ code=self.code,
+ authored_code=authored_code,
+ )
+ except CodeBlockRunnerSelectionError as selection_error:
+ download_log.close()
+ return await self.build_block_result(
+ success=False,
+ failure_reason=_redact_codeblock_failure_text(
+ str(selection_error), app.AGENT_FUNCTION.serialize_codeblock_parameters(parameter_values)
+ ),
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ if use_codeblock_runner:
+ # The secure runner has a transfer ceiling and `cells` is formatting-only, most of a Sheets read's bytes.
+ # Copy, never mutate: a downstream google_sheets_write replays formatting from the stored `cells`.
+ for key in sheets_read_parameter_keys:
+ parameter_values[key] = {k: v for k, v in parameter_values[key].items() if k != "cells"}
- def scrub_failure_reason(value: str | None, fallback: str = CODE_BLOCK_GENERIC_FAILURE_REASON) -> str | None:
- return _redact_codeblock_failure_text(value, serialized_parameter_values, fallback)
+ serialized_parameter_values = app.AGENT_FUNCTION.serialize_codeblock_parameters(parameter_values)
- def scrub_failed_block_result(result: BlockResult) -> BlockResult:
- return _redact_codeblock_result(result, serialized_parameter_values)
+ def scrub_failure_reason(
+ value: str | None, fallback: str = CODE_BLOCK_GENERIC_FAILURE_REASON
+ ) -> str | None:
+ return _redact_codeblock_failure_text(value, serialized_parameter_values, fallback)
- try:
- use_codeblock_runner = await app.AGENT_FUNCTION.should_use_codeblock_runner(
+ def scrub_failed_block_result(result: BlockResult) -> BlockResult:
+ return _redact_codeblock_result(result, serialized_parameter_values)
+
+ LOG.info(
+ "CodeBlock runner selection at block",
+ use_codeblock_runner=use_codeblock_runner,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
- workflow_run_context=workflow_run_context,
- organization_id=organization_id,
block_label=self.label,
- browser_session_id=browser_session_id,
- code=self.code,
- authored_code=authored_code,
)
- except CodeBlockRunnerSelectionError as selection_error:
- return await self.build_block_result(
- success=False,
- failure_reason=scrub_failure_reason(str(selection_error)),
- output_parameter_value=None,
- status=BlockStatus.failed,
+
+ # Every code block gets a container task v1 + step so its recorded calls render through
+ # the standard action/artifact timeline and are billable; on prompt-bearing blocks the
+ # task also seats a later agent takeover on failure.
+ strategy_aware_typing = await self._workflow_is_copilot_authored(workflow_run_context)
+ playwright_input_defaults = playwright_input_defaults_for_page(page) if strategy_aware_typing else None
+ recorder = CodeBlockActionRecording(
+ code_block=self,
+ page=page,
+ workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
- )
- LOG.info(
- "CodeBlock runner selection at block",
- use_codeblock_runner=use_codeblock_runner,
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- block_label=self.label,
- )
-
- # Every code block gets a container task v1 + step so its recorded calls render through
- # the standard action/artifact timeline and are billable; on prompt-bearing blocks the
- # task also seats a later agent takeover on failure.
- strategy_aware_typing = await self._workflow_is_copilot_authored(workflow_run_context)
- playwright_input_defaults = playwright_input_defaults_for_page(page) if strategy_aware_typing else None
- recorder = CodeBlockActionRecording(
- code_block=self,
- page=page,
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- organization_id=organization_id,
- workflow_run_context=workflow_run_context,
- redaction_parameters=serialized_parameter_values,
- credential_release_guard=credential_release_guard if credential_release_guard.is_armed else None,
- strategy_aware_typing=strategy_aware_typing,
- playwright_input_defaults=playwright_input_defaults,
- )
- if credential_release_guard.is_armed:
- credential_release_guard.log_armed()
- await recorder.create_task_and_step()
- recording_page = recorder.recording_page
- # Bound before the try so the shared except arms can read it even when the secure path raises
- # before the inline claim is wired; a claim that never ran leaves it unarmed (outcome None).
- inline_download_claim_outcome = DownloadClaimOutcomeRecorder()
+ workflow_run_context=workflow_run_context,
+ redaction_parameters=serialized_parameter_values,
+ credential_release_guard=credential_release_guard if credential_release_guard.is_armed else None,
+ strategy_aware_typing=strategy_aware_typing,
+ playwright_input_defaults=playwright_input_defaults,
+ )
+ if credential_release_guard.is_armed:
+ credential_release_guard.log_armed()
+ await recorder.create_task_and_step()
+ recording_page = recorder.recording_page
+ # Bound before the try so the shared except arms can read it even when the secure path raises
+ # before the inline claim is wired; a claim that never ran leaves it unarmed (outcome None).
+ inline_download_claim_outcome = DownloadClaimOutcomeRecorder()
+ except BaseException:
+ download_log.close()
+ raise
try:
await recorder.link_block()
download_evidence = self._bind_download_evidence_probe(
@@ -8519,6 +8762,7 @@ async def wrapper({default_args}):
download_run_id=resolved_download_id,
download_binding=download_binding_of(browser_state),
download_evidence=download_evidence,
+ download_log=download_log,
)
LOG.info(
"Secure CodeBlock override returned",
@@ -8820,25 +9064,47 @@ async def wrapper({default_args}):
session_bound=session_download_lane_active(browser_state),
resolved_download_id=resolved_download_id,
)
- user_function = self.generate_async_user_function(
- self.code,
- recording_page,
- parameter_values,
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- workflow_run_block_id=workflow_run_block_id,
- download_run_id=resolved_download_id,
- download_binding=download_binding_of(browser_state),
- download_evidence=download_evidence,
- download_claim_outcome_recorder=inline_download_claim_outcome,
- authorized_file_materializations=authorized_file_materializations,
- )
+ try:
+ # Inline code arms Playwright's own expect_download, so there is no arm hook to snapshot from; a
+ # block that never attaches skips the registration read entirely.
+ registered_downloads = (
+ await _registered_download_source(
+ download_evidence,
+ page,
+ download_binding=download_binding_of(browser_state),
+ organization_id=organization_id,
+ download_run_id=resolved_download_id or workflow_run_id,
+ )
+ # Python NFKC-normalizes identifiers at parse time, so the call can be spelled in forms a raw
+ # substring test misses.
+ if "attach_authorized_file" in unicodedata.normalize("NFKC", self.code)
+ else None
+ )
+ user_function = self.generate_async_user_function(
+ self.code,
+ recording_page,
+ parameter_values,
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ workflow_run_block_id=workflow_run_block_id,
+ download_run_id=resolved_download_id,
+ download_binding=download_binding_of(browser_state),
+ download_evidence=download_evidence,
+ download_claim_outcome_recorder=inline_download_claim_outcome,
+ authorized_file_materializations=authorized_file_materializations,
+ download_log=download_log,
+ registered_downloads=registered_downloads,
+ )
+ except BaseException:
+ download_log.close()
+ raise
try:
result = await self.execute_user_function_with_timeout(
user_function,
settings.CODE_BLOCK_EXECUTION_TIMEOUT_SECONDS,
)
finally:
+ download_log.close()
# Before download settlement and before any at-failure evidence capture: both are
# trusted browser work on this page, and neither may get the sandbox's dialog answer.
try:
@@ -9202,6 +9468,7 @@ async def wrapper({default_args}):
organization_id=organization_id,
)
finally:
+ download_log.close()
# Safety net for paths the except arms miss (CancelledError, link_block failure).
await recorder.finalize(success=False)
diff --git a/skyvern/forge/taskv3/captcha_tools.py b/skyvern/forge/taskv3/captcha_tools.py
index bd58ab924..5f1a1ff6f 100644
--- a/skyvern/forge/taskv3/captcha_tools.py
+++ b/skyvern/forge/taskv3/captcha_tools.py
@@ -106,7 +106,8 @@ def build_captcha_tools(
"captcha solved; re-observe the page and continue (e.g. retry submit).",
ok_class="solved",
)
- # Absent: no challenge present. Cheap structural no-op that does not count toward the failure cap.
+ # Absent: no challenge is presented, including a widget the page loaded but never showed. No solver
+ # arm ran, so this cheap structural no-op does not count toward the failure cap.
return ToolResult.ok(
"no captcha challenge was detected in the page or its visible frames; nothing was solved. "
"Re-observe before calling solve_captcha again.",
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 311ff7365..e0c19aff8 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -25,6 +25,7 @@ from contextvars import ContextVar
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Awaitable, Callable, Collection, Iterator, Literal, NamedTuple, TypeVar
+from urllib.parse import urlsplit
import structlog
@@ -34,6 +35,7 @@ from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.workflow.context_manager import RANDOM_SECRET_ID_PREFIX
from skyvern.forge.taskv3.handoff_redaction import MAX_HANDOFF_URL_CHARS, sanitize_published_url
from skyvern.forge.taskv3.target_label import describe_target
+from skyvern.webeye.navigation import redact_url_secrets
LOG = structlog.get_logger()
@@ -85,6 +87,8 @@ ToolErrorClass = Literal[
"offset_past_end",
# The offset itself was unusable — negative, or not a whole number of characters.
"invalid_offset",
+ # `navigate`: nothing committed — a net error, or the commit budget expired with no response.
+ "navigation_failed",
# The handler raised instead of returning; classified by `_raised_error_class`.
"driver_timeout",
"timeout_other",
@@ -111,6 +115,12 @@ ToolOkClass = Literal[
"upload_seen",
"consumed_shown",
"attached_no_activity",
+ # `navigate`, in descending order of how far the landed document got: `loaded` saw the load event
+ # fire, `document_ready` returned on domcontentloaded with load still outstanding, and
+ # `committed_not_loaded` got a document that never became ready inside the readiness budget.
+ "loaded",
+ "document_ready",
+ "committed_not_loaded",
]
# Which `covered` message the model actually got. They are one `tool_error_class`, so without this
@@ -330,6 +340,13 @@ def _raised_error_class(exc: BaseException) -> ToolErrorClass:
return "handler_raised"
+def mark_is_filler(mark: Any) -> bool:
+ # look() numbers marks from 1, so 0 addresses nothing: it is an upstream filling the optional slot,
+ # not the model addressing by mark. `to_openai_tool` sets the `strict` key that provokes that, so
+ # this is the tolerance for an upstream that fills it anyway.
+ return mark == 0 and not isinstance(mark, str)
+
+
def _selector_kind(args: dict[str, Any]) -> str:
"""How the model addressed its target on this call, read off the ARGS AS SENT.
@@ -340,7 +357,7 @@ def _selector_kind(args: dict[str, Any]) -> str:
frame perception on -- a plain selector is otherwise resolved inside the handler and its row is
~0. Read the two together with `frame_perception`, which rides the same record for that reason.
"""
- if args.get("mark") is not None:
+ if args.get("mark") is not None and not mark_is_filler(args.get("mark")):
return "mark"
selector = args.get("selector")
# `not selector`, matching what the wrappers themselves treat as absent. Note this does NOT make
@@ -411,6 +428,11 @@ class ToolSpec:
"name": self.name,
"description": self.description,
"parameters": self.parameters,
+ # Stated rather than left unset because OpenRouter reads an unset `strict` as license
+ # to fill every declared property with a type default (`mark: 0`, `selector: ""`),
+ # which the act wrappers then refuse. `True` is not the alternative: these schemas
+ # are not strict-shaped and it 400s. See GOTCHAS.md "Loop" for the measured matrix.
+ "strict": False,
},
}
@@ -1726,9 +1748,26 @@ _TOOL_CALL_RECORD_FIELDS = frozenset(
"covered_branch",
"covered_controls",
"covered_layer_kind",
+ "requested_url",
+ "landed_url",
+ "nav_error_code",
+ "same_page",
+ "readiness_read_failed",
}
)
+# A host is bounded in the DNS but not in a string `urlsplit` was handed, and a record field is
+# indexed: cap the scrubbed value rather than trust what it was reduced from.
+LOGGED_URL_MAX_CHARS = 500
+
+# A hostname is letters (any script, so an IDN still logs its host), digits, dots and hyphens, or an
+# IPv6 literal, which `hostname` hands back with the brackets stripped. Anything else in what
+# `urlsplit` called the host means it found no host at all, whatever it returned: `urlsplit` does not
+# treat a backslash as a path separator, so `https://host\signin\TOKEN` parses the whole run as the
+# authority while the browser normalizes it to `/` and navigates to a path — the token would survive
+# the scrub as part of the "host" and land in an indexed field.
+_LOGGABLE_HOST = re.compile(r"[\w.\-]+|[0-9A-Fa-f.:]+")
+
class _ProgressEvidence(str, Enum):
"""Why the canonical ring was cleared. Every clear names the positive evidence class that
@@ -1835,6 +1874,75 @@ class _CanonicalProgressTracker:
)
+def _logged_url(url: str) -> str:
+ """A URL reduced to what an indexed field may carry: scheme and host, never path, query, userinfo
+ or fragment.
+
+ Unconditional, the model's own argument included. A signed or sign-in URL is a bearer secret
+ wherever it came from, and the model types back the one a page just showed it, so "the model typed
+ this" is no evidence the URL is safe to keep whole.
+
+ The exception is a payload ref, which is logged as the token it is: a name for the target that is
+ not the address. Membership in the run's minted refs, never shape — the same rule the model-facing
+ boundary masks by.
+
+ Never raises. The argument is model-typed, and this is evaluated to build the kwargs of the loop's
+ `taskv3 tool handler raised` line — inside that `except` block — so a raise here escapes the block,
+ the per-call try and the batch loop, aborting the run instead of producing a tool error.
+ """
+ ctx = skyvern_context.current()
+ if ctx is not None and url in ctx.opaque_url_refs:
+ return url[:LOGGED_URL_MAX_CHARS]
+ try:
+ host = urlsplit(url).hostname
+ if host is None or not _LOGGABLE_HOST.fullmatch(host):
+ return "<redacted>"
+ return redact_url_secrets(url)[:LOGGED_URL_MAX_CHARS]
+ except ValueError:
+ # urlsplit parses the port and the IPv6 brackets lazily, on attribute access: a non-numeric or
+ # out-of-range port and an unclosed bracket each raise here, not at the split.
+ return "<redacted>"
+
+
+def _navigate_record_fields(tool_name: str, args: dict[str, Any], result: ToolResult | None) -> dict[str, str | bool]:
+ """What a `navigate` record is about: the URL asked for, where it landed, the driver's code, and
+ whether the browser was already on the page it was sent to.
+
+ Empty for every other tool, so no facet is added fleet-wide. Both URLs are attribution only —
+ scheme and host — which is what a fleet read of navigate outcomes needs and all a log line may
+ hold. The requested one is the ARGUMENT, never the resolved one: an opaque payload ref or a
+ credential placeholder must stay unresolved here.
+ """
+ if tool_name != "navigate":
+ return {}
+ fields: dict[str, str | bool] = {}
+ requested = args.get("url")
+ if isinstance(requested, str) and requested:
+ fields["requested_url"] = _logged_url(requested)
+ data = (result.data if result is not None else None) or {}
+ landed = data.get("landed_url")
+ if isinstance(landed, str) and landed:
+ # Scrubbed again rather than trusted: the tool already reduced it, and the rule belongs to the
+ # field, not to whichever caller filled it.
+ fields["landed_url"] = _logged_url(landed)
+ # A driver's own net:: code, which is a closed vocabulary carrying no address.
+ nav_error_code = data.get("nav_error_code")
+ if isinstance(nav_error_code, str) and nav_error_code:
+ fields["nav_error_code"] = nav_error_code[:LOGGED_URL_MAX_CHARS]
+ # Whether the requested URL was the one the browser was already showing. Nothing reads it but a
+ # post-deploy rate: how often the model sends the browser back to the page it is already on.
+ same_page = data.get("same_page")
+ if isinstance(same_page, bool):
+ fields["same_page"] = same_page
+ # Which fact the `committed_not_loaded` class is about on this row: a document that never became
+ # ready, or a readyState read that failed on a wedged renderer. Present only on that class, so a
+ # rate taken over it can exclude probe failures instead of silently mixing them in.
+ readiness_read_failed = data.get("readiness_read_failed")
+ if isinstance(readiness_read_failed, bool):
+ fields["readiness_read_failed"] = readiness_read_failed
+ return fields
+
+
def _observe_summary_fields(result: ToolResult) -> dict[str, int]:
"""Counts only: the summary is built by the tool, but an indexed field is re-checked here."""
summary = (result.data or {}).get("summary")
@@ -3418,7 +3526,12 @@ async def run_agent_tool_loop(
try:
result = await spec.handler(args)
except Exception as exc:
- LOG.warning("taskv3 tool handler raised", tool=tool_name, exc_info=True)
+ LOG.warning(
+ "taskv3 tool handler raised",
+ tool=tool_name,
+ exc_info=True,
+ **_navigate_record_fields(tool_name, args, None),
+ )
raised_class = _raised_error_class(exc)
result = ToolResult.error(f"tool_error: {type(exc).__name__}: {exc}", error_class=raised_class)
tool_duration_seconds = time.monotonic() - tool_started_at
@@ -3440,6 +3553,9 @@ async def run_agent_tool_loop(
# record; its content is deliberately never logged. Gated on the tool, not the payload,
# so every other tool's record keeps exactly today's fields.
observe_summary = _observe_summary_fields(result) if tool_name == "observe" else {}
+ # Which URL the call was about, so a navigate row is attributable to a target without the
+ # arguments themselves being logged.
+ navigate_fields = _navigate_record_fields(tool_name, args, result)
# Conditional for the same reason observe's counters are: a record only carries a field
# the call actually produced, so an ok call's record keeps exactly the fields it has
# today and `resolve_seconds` is absent (not null) on tools with no address to resolve.
@@ -3570,6 +3686,7 @@ async def run_agent_tool_loop(
batch_index=idx,
**cost_fields,
**observe_summary,
+ **navigate_fields,
**attribution,
)
if spec is not None and spec.billable:
@@ -3795,6 +3912,18 @@ async def run_agent_tool_loop(
)
break
+ if result.status == "ok" and result_data.get("readiness_incomplete"):
+ # A navigate whose document committed but did not finish loading. The rest of the batch
+ # was queued against a loaded page, and before SKY-16278 the tool raised here and the
+ # error branch below skipped it; keep that, so the readiness the tool reported reaches
+ # the model before it chooses its next action.
+ _append_skipped_tool_results(
+ st.messages,
+ tool_calls[idx + 1 :],
+ "the page this batch navigated to had not finished loading — observe it before re-queuing these",
+ )
+ break
+
if result.status == "error":
# The rest of the batch is skipped only when the failed call moved the page: the tool's
# own signal, or the probe sampled before dispatch (a missing reading counts as moved).
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 606e899de..89e14af2c 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -60,6 +60,7 @@ from skyvern.forge.taskv3.loop import (
ToolHandler,
ToolResult,
ToolSpec,
+ mark_is_filler,
record_covered_layer,
record_frame_perception,
record_hit_class,
@@ -74,8 +75,9 @@ from skyvern.forge.taskv3.run_arms import (
)
from skyvern.forge.taskv3.target_label import TARGET_KIND_TOKENS, TARGET_NAME_CAP
from skyvern.webeye.actions.key_names import normalize_key_chord
-from skyvern.webeye.browser_driver_errors import is_driver_timeout_error
+from skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_error
from skyvern.webeye.browser_state import BLANK_PAGE_URLS
+from skyvern.webeye.navigation import driver_nav_error_code, redact_url_secrets
from skyvern.webeye.utils.challenge_signature import CHALLENGE_VENDOR_SIGNATURE
from skyvern.webeye.utils.page import OTP_INPUT_PRIVACY_JS, OTP_SAFE_FRAGMENT_HTML_JS, mask_otp_values_in_html
@@ -657,6 +659,41 @@ def _match_option_exact(value: str, options: list[dict[str, Any]]) -> int | None
return rows[idx][0] if idx is not None and tier == "exact" else None
+def _without_nested_copies(value: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Drop an exact-match row that holds another exact-match row: a wrapper and the element carrying its
+ label are one candidate, and the innermost stands for it. `inside` is a row's nearest tagged ancestor;
+ siblings never share a chain, so identical siblings stay separate and are refused."""
+ want = _exact_tier_key(value)
+ exact = {o.get("n") for o in rows if _exact_tier_key(str(o.get("text") or "")) == want}
+ by_n = {o.get("n"): o for o in rows}
+ wrappers: set[Any] = set()
+ for n in exact:
+ seen: set[Any] = set()
+ up = (by_n.get(n) or {}).get("inside")
+ while up is not None and up not in seen:
+ if up in exact:
+ wrappers.add(up)
+ seen.add(up)
+ up = (by_n.get(up) or {}).get("inside")
+ return [o for o in rows if o.get("n") not in wrappers]
+
+
+def _rows_nested_in(n: int, rows: list[dict[str, Any]]) -> list[str]:
+ """The labels of rows whose `inside` chain reaches row `n`."""
+ by_n = {o.get("n"): o for o in rows}
+ nested: list[str] = []
+ for o in rows:
+ seen: set[Any] = set()
+ up = o.get("inside")
+ while up is not None and up not in seen:
+ if up == n:
+ nested.append(str(o.get("text") or ""))
+ break
+ seen.add(up)
+ up = (by_n.get(up) or {}).get("inside")
+ return nested
+
+
def _exact_tier_key(text: str) -> str:
"""The exact tier's own equality key — `_canon_label` plus the shared matcher's case/apostrophe fold —
for pre-filters asking "which rows did that tier see as this value". A plain `_canon_label` filter
@@ -1258,6 +1295,52 @@ _ROW_SEMANTICS_JS = r"""
const DEPARTURE_SEL =
'a[href],[role="link"],[role="menuitem"],[role="tab"],' +
'button:not([type="button" i]):not([type="reset" i]),input[type="submit" i],input[type="image" i]';
+ // A reset control is deliberately NOT in DEPARTURE_SEL: it does not leave the page. Clicking one
+ // still erases every value already entered, so anything admitted purely on its own text -- which has
+ // no declared row vouching it is an option -- has to be refused for holding one.
+ const RESET_SEL = 'button[type="reset" i],input[type="reset" i]';
+ const wrapsReset = (el) => {
+ try {
+ if (el.matches(RESET_SEL)) return true;
+ // Explicit null-compare rather than a double-negation return: the click suite's fake page
+ // dispatches on that idiom's exact substring to answer the selector-exists probe, and this
+ // helper ships inside _FIND_MENU_JS via _ROW_SEMANTICS_JS.
+ return el.querySelector(RESET_SEL) !== null;
+ } catch (e) {
+ return true;
+ }
+ };
+ // Whether a node's visible text stacks into MORE than the two lines a suggestion row may use.
+ // The undeclared single-winner branch refuses at TWO stacked rows instead; the floors differ on
+ // purpose. That branch picks by geometry, so it has to be conservative, while a searched pool is
+ // adjudicated by the caller's exact matcher and pays for a 2-row floor by refusing the ordinary
+ // label-over-secondary row. Two stacked rows is genuinely undecidable from markup: a container of
+ // exactly two rows stays admitted here, and that is the accepted cost of admitting the common shape.
+ // A label over a grey secondary line is one row, the same allowance the row-size gate makes
+ // ("visible, row-sized (allows a 2-line row)"); three or more stacked text lines is a container,
+ // whose text is the union of its rows and whose click lands on an arbitrary one.
+ const stacksRows = (el) => {
+ const tops = new Set();
+ // DESCENDANTS, not direct children: one wrapper div around the rows leaves a container with a
+ // single child, and a child-only walk then sees one line and calls it a row.
+ let seen = 0;
+ for (const ch of el.querySelectorAll('*')) {
+ if (++seen > 200) return true;
+ let cr;
+ // Fails toward CONTAINER, the opposite of pickableRow's fail-toward-candidate: this answer
+ // decides whether a node with more children than a row should have may be CLICKED, and a
+ // container click lands on an arbitrary row. Unreadable therefore refuses rather than guesses.
+ try { cr = ch.getBoundingClientRect(); } catch (e) { return true; }
+ if (cr.width > 0 && cr.height > 0 && (ch.innerText || '').trim()) tops.add(Math.round(cr.top));
+ if (tops.size >= 3) return true;
+ }
+ return false;
+ };
+ // Whether a node may be TAGGED as something the tool will click, for a pool nothing declared a row
+ // in. Both searched branches use it: a node admitted on its own text has no declared row vouching
+ // that it is an option, so it has to clear every hazard the promotion path clears for a real one.
+ // (isNavRow is already applied to every candidate in the loop above, so it is not repeated here.)
+ const safeToTag = (el) => !wrapsDeparture(el) && !wrapsReset(el) && !stacksRows(el);
const wrapsDeparture = (el) => {
try {
if (el.matches(DEPARTURE_SEL) && isShown(el)) return true;
@@ -1399,8 +1482,18 @@ _FIND_SUGGESTION_JS = (
const wantNorm = String(args.value || '').replace(/\s+/g, ' ').trim().toLowerCase();
// A value with no >=3-char word ("No", "UK") has nothing to overlap; it matches a row only by exact text.
const exact = want.size ? null : String(args.value || '').replace(/\s+/g, ' ').trim().toLowerCase();
+ // Set when the caller typed something other than what it will commit: the typed text only makes rows
+ // appear, so no word of it gates a row, and which reacting node is the value is the caller's exact
+ // matcher's decision, never this script's.
+ const searched = typeof args.match === 'string';
+ // 80 is the shared "row-sized text, not a paragraph" ceiling (_FIND_MENU_JS uses the same one). It
+ // is a flat number everywhere else because no other finder knows what it is looking for -- this one
+ // does: on a searched path the caller named the value in args.match, and only a row whose whole text
+ // IS that value can ever be committed. So the ceiling is measured from it, keeping 80 as the
+ // allowance for the extra parts a declared row can render beside its label.
+ const txtCap = searched ? String(args.match).replace(/\s+/g, ' ').trim().length + 80 : 80;
pQSA('[data-tv3-sugg]').forEach((e) => e.removeAttribute('data-tv3-sugg'));
- if ((!want.size && !exact) || !preReady()) return null;
+ if ((!searched && !want.size && !exact) || !preReady()) return null;
const field = pQS(args.field) || (args.el && args.el.isConnected ? args.el : null);
// No field means no geometry gate, and without it the scan below is page-wide and will happily
// tag -- and then click -- a row far from the control the caller typed into. Refuse instead:
@@ -1444,7 +1537,13 @@ _FIND_SUGGESTION_JS = (
if (preHas(el) && !(openNarrowed && focusHas(el))) continue;
const tag = el.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || tag === 'SCRIPT' || tag === 'STYLE' || tag === 'LABEL' || tag === 'FORM') continue;
- if (el.children.length > 8) continue; // a suggestion row, not a big container
+ // A child COUNT is a proxy for "a big container, not a suggestion row". It is a good enough proxy
+ // when the typed text is the value, but a searched row a widget builds from highlighted fragments
+ // has a child per fragment and must still reach the matcher WHOLE -- and where nothing declares a
+ // row, its pieces have nothing to promote onto. What actually separates the two is whether the
+ // children STACK: a container's sit on different lines, one row's sit on one. Only consulted for
+ // the candidates the count would have dropped, so the ordinary path keeps the cheap test.
+ if (el.children.length > 8 && (!searched || stacksRows(el))) continue;
const r = el.getBoundingClientRect();
if (r.width === 0 || r.height === 0 || r.height > 120) continue; // visible, row-sized (allows a 2-line row)
// anyRegion is for a caller that only asks whether rows reacted and never clicks one: a field kept
@@ -1454,7 +1553,7 @@ _FIND_SUGGESTION_JS = (
if (!(ownPopup && pContains(ownPopup, el)) && (r.top < fr.top - 400 || r.top > fr.bottom + 500)) continue;
}
const txt = (el.innerText || '').trim();
- if (!txt || txt.length > 80) continue;
+ if (!txt || txt.length > txtCap) continue;
// never click something navigational (would leave the form) unless it's explicitly an option;
// last of the gates because it is the only one that walks a subtree
if (isNavRow(el)) continue;
@@ -1470,7 +1569,9 @@ _FIND_SUGGESTION_JS = (
// "No" over "No, I have not ..."). This is only the CANDIDATE gate, not a cross-row ranking: every
// row that clears score > 0 is tagged below and handed to the caller's own precision matcher.
const isExact = norm === (exact !== null ? exact : wantNorm);
- if (exact !== null) {
+ if (searched) {
+ score = 1;
+ } else if (exact !== null) {
if (isExact) score = 2;
else if (norm.split(/\s*[,;:(]\s*|\s+[-\u2013\u2014]\s+/)[0] === exact) score = 1;
} else {
@@ -1483,14 +1584,17 @@ _FIND_SUGGESTION_JS = (
if (!cands.length) return null;
// Drop any candidate that CONTAINS another candidate (a dropdown container over its own rows).
const leaves = cands.filter((c) => !cands.some((o) => o.el !== c.el && pContains(c.el, o.el)));
- const pool = leaves.length ? leaves : cands;
- if (pool.some((c) => !!composedClosest(c.el, rowSel))) {
+ // A searched row built from parts must reach the matcher whole, so nothing is dropped for containing
+ // another candidate; the caller tells nested copies of one candidate from siblings.
+ const pool = searched ? cands : leaves.length ? leaves : cands;
+ const declaredCands = pool.filter((c) => !!composedClosest(c.el, rowSel));
+ if (declaredCands.length) {
// The ROW the widget DECLARED is the unit, not the fragment that happens to hold the matched
// substring: a widget that wraps only the match in its own highlight span leaves that span as the
// innermost candidate, and then every row reads as the same bare query text. Promote each leaf to
// its declared row and dedupe by that row, so the text read back is the row's own full label.
const byRow = new Map();
- for (const c of pool) {
+ for (const c of declaredCands) {
const row = composedClosest(c.el, rowSel);
if (!row || byRow.has(row)) continue;
// The promotion can only widen what a click lands on, so the row it produced has to clear the
@@ -1503,22 +1607,59 @@ _FIND_SUGGESTION_JS = (
const promoted = Array.from(byRow.values());
// Two leaves can promote onto nested rows; keep the innermost so no tagged row holds another.
const rows = promoted.filter((c) => !promoted.some((o) => o.el !== c.el && pContains(c.el, o.el)));
- if (!rows.length) return null;
+ // A candidate the widget declared NO row for is still a reaction: dropping it because some
+ // SIBLING carried role=option is how a roleless exact match disappears before the caller's matcher
+ // ever reads it. It stands for itself, unless a declared row already holds it or it wraps one.
+ // It clears safeToTag, the same hazards the fully-undeclared branch below clears: the candidate
+ // loop's isNavRow only asks whether this node IS navigational, so a plain <div> WRAPPING an
+ // <a href> or a reset control reaches here unflagged, and the searched pool keeps containers on
+ // purpose (pool = cands), so a roleless box whose AGGREGATE text is the value would otherwise be
+ // clicked, landing on an arbitrary one of its rows.
+ const bare = pool.filter(
+ (c) => safeToTag(c.el) && !composedClosest(c.el, rowSel) && !rows.some((o) => pContains(o.el, c.el) || pContains(c.el, o.el))
+ );
+ // Nested bare units are NOT reduced to one: neither end of the chain is reliably the row. A
+ // fragment-built row needs the OUTER node, a roleless list wrapping roleless rows needs the inner
+ // ones, and nothing here can tell those apart -- so both reach the caller, whose exact matcher and
+ // duplicate collapse decide, exactly as the undeclared searched branch already does.
+ const units = rows.concat(bare.map((c) => ({ el: c.el, r: c.r, bare: true })));
+ if (!units.length) return null;
// Top-to-bottom order, same as _FIND_MENU_JS. This finder only says which rows reacted; the caller
// (via _match_menu_option, over the full untruncated text _MENU_OPTION_TEXTS_JS reads back) picks
// which one is the wanted value -- geometry never breaks a tie between them.
- rows.sort((a, b) => a.r.top - b.r.top || a.r.left - b.r.left);
+ units.sort((a, b) => a.r.top - b.r.top || a.r.left - b.r.left);
const options = [];
+ // Which tagged units the widget declared NO row for. Same text is not the same option: the caller
+ // needs the split to keep a bare node from standing in for a row the widget actually declared.
+ const bareNs = [];
let n = 0;
- for (const c of rows) {
+ for (const c of units) {
n++;
c.el.setAttribute('data-tv3-sugg', String(n));
- if (options.length < 15) options.push({ n, text: c.el.innerText.trim().slice(0, 60) });
+ if (c.bare) bareNs.push(n);
+ if (options.length < 15) options.push({ n, text: (c.el.innerText || '').trim().slice(0, 60) });
}
- return { count: n, options, declared: true };
+ return { count: n, options, declared: true, bare: bareNs };
}
// Nothing here declares a row, so there is no unit to name: take the highest score, breaking ties
// toward the smallest (innermost) row.
+ if (searched) {
+ // Nothing names a row, so every reacting node is handed back and the caller's exact matcher, which
+ // reads each one's full text, decides which one is the value. "Every node" still excludes the ones
+ // no pick may land on: with nothing declaring a row, there is even less vouching for these than
+ // for a bare unit beside a declared sibling, so they clear the same hazards.
+ const safe = pool.filter((c) => safeToTag(c.el));
+ if (!safe.length) return null;
+ safe.sort((a, b) => a.r.top - b.r.top || a.r.left - b.r.left);
+ const options = [];
+ let n = 0;
+ for (const c of safe) {
+ n++;
+ c.el.setAttribute('data-tv3-sugg', String(n));
+ if (options.length < 15) options.push({ n, text: (c.el.innerText || '').trim().slice(0, 60) });
+ }
+ return { count: n, options, declared: false };
+ }
pool.sort((a, b) => b.score - a.score || a.h - b.h);
const best = pool[0];
// Two leading-clause matches for a short value ("No, ..." and "No - ...") with no exact row are
@@ -2054,6 +2195,18 @@ _VERIFY_COMMIT_JS = (
const typed = String(args.typed || '').trim();
const chosen = String(args.chosen || '').trim() || typed;
const cur = (el.value || '').trim();
+ // A value that is the whole label of ANOTHER reacting row is that row's commit, not ours — even when it
+ // shares a word with the chosen label (a part of it the click landed on) or is too short to have one.
+ // A value the chosen row itself declares ("CA" for "California") is ours even when a sibling row wears
+ // it, never when a row nested inside the chosen one does: a click there commits that row, not ours.
+ const otherRows = Array.isArray(args.otherRows) ? args.otherRows : [];
+ const nestedRows = Array.isArray(args.nestedRows) ? args.nestedRows : [];
+ const chosenDeclared = Array.isArray(args.chosenValues) ? args.chosenValues : [];
+ const isOtherRow = (v) =>
+ !eqi(v, chosen) &&
+ otherRows.some((o) => eqi(o, v)) &&
+ (nestedRows.some((o) => eqi(o, v)) || !chosenDeclared.some((d) => eqi(d, v)));
+ if (cur && isOtherRow(cur)) return '';
const tagged = pQS('[data-tv3-sugg]');
// The open->observe->pick path tags no suggestion, so `listClosed` would be unconditionally true and
// defeat the change check — the caller sets noSuggestionList so the el.value branch rests on an actual
@@ -2096,7 +2249,7 @@ _VERIFY_COMMIT_JS = (
const preHidden = new Set(Array.isArray(args.preHidden) ? args.preHidden : []);
for (const h of cont.querySelectorAll('input[type=hidden]')) {
const v = (h.value || '').trim();
- if (!v) continue;
+ if (!v || isOtherRow(v)) continue;
if (eqi(v, chosen)) return v;
if (args.noSuggestionList) {
const declaredHidden = Array.isArray(args.chosenValues) ? args.chosenValues : [];
@@ -4177,6 +4330,103 @@ def _click_blocked_only_by_viewport(exc: BaseException) -> bool:
return "outside of the viewport" in message and not any(b in message for b in _OTHER_CLICK_BLOCKERS)
+_COLLATERAL_SCAN_MAX = 200
+# A single field's keystrokes cannot spread wider than the composite control it sits in. Past this, the
+# movement is the page's own and the capture cannot tell which half was ours, so none of it is undone.
+_COLLATERAL_RESTORE_MAX = 12
+_COLLATERAL_FILL_TIMEOUT_MS = 2000
+
+# The collateral tag outlives its call like the act tag, so get_html strips it for the same reason.
+_COLLATERAL_ATTR_RE = re.compile(r'\s+data-tv3-collateral="[^"]*"')
+
+# Read every captured tag back in one pass. A tag whose element the page has since dropped reports
+# null, which reads as "not moved" -- there is nothing left to hand a value back to either way.
+_COLLATERAL_READBACK_JS = (
+ r"""(tags) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ return tags.map((t) => {
+ // The capture tags through open shadow roots, so a plain document query would read null for every
+ // field inside a component and call it "not moved".
+ const f = _q.find('[data-tv3-collateral="' + t + '"]');
+ return f && typeof f.value === 'string' ? f.value : null;
+ });
+}"""
+)
+
+# Every text-holding field our keystrokes could reach if the widget routes them somewhere other than
+# the element we focused, tagged so each one can be read back by the same handle afterwards. Scoped to
+# the target's own form -- or its own root when it has none, which keeps a field inside a component
+# scanning its shadow root rather than the host document. Secret boxes are skipped: their value must
+# not be read, which also means a stray key in one cannot be taken back.
+_COLLATERAL_VALUES_JS = (
+ r"""(arg) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ const el = _q.find(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);
+ if (!el) return [];
+ // Only ever repair inside a grouping the page itself declares. Falling back to the root document
+ // made every unrelated field on a form-less page a candidate, which is a blast radius no rule about
+ // OUR keystrokes can justify; with no declared boundary we decline to capture at all.
+ // closest() stops at a shadow boundary, so a custom element that declares the group on its HOST and
+ // renders the segments inside its shadow root would find no scope at all -- climb to the host and
+ // keep looking, the way the read-back already reaches into those roots.
+ const SCOPES = 'form, fieldset, [role="group"], [role="radiogroup"]';
+ let scope = null;
+ let node = el;
+ while (node && !scope) {
+ try { scope = node.closest ? node.closest(SCOPES) : null; } catch (e) { scope = null; }
+ if (scope) break;
+ let root = null;
+ try { root = Node.prototype.getRootNode.call(node); } catch (e) { root = null; }
+ node = root && root.host ? root.host : null;
+ }
+ if (!scope || !scope.querySelectorAll) return [];
+ // A host's own fields live in its shadow tree, which querySelectorAll on the host cannot see. And
+ // when the declared group is an ancestor in the LIGHT dom, the target's siblings are in the target's
+ // own root rather than anywhere under the scope -- so that root is always in the set.
+ const roots = [scope];
+ if (scope.shadowRoot) roots.push(scope.shadowRoot);
+ // Only when the target sits behind a SHADOW boundary: a shadow root has a host, the document does
+ // not. Without that test `getRootNode` returns the document for every ordinary light-DOM field, the
+ // whole page joins the scan, and "bounded to a grouping the page declares" stops being true in the
+ // common case.
+ let own = null;
+ try { own = Node.prototype.getRootNode.call(el); } catch (e) { own = null; }
+ // ...and only when the declared scope is OUTSIDE that root. A group declared INSIDE the component
+ // already bounds the scan, and widening to the whole root would put the component's other fields
+ // back in range -- the same over-reach as the document case, one boundary in.
+ if (own && own.host && own !== scope && !own.contains(scope) && own.querySelectorAll && !roots.includes(own)) {
+ roots.push(own);
+ }
+ """
+ + OTP_INPUT_PRIVACY_JS
+ + r"""
+ const out = [];
+ let seen = 0;
+ for (const f of roots.flatMap((r) => Array.from(r.querySelectorAll('input, textarea')))) {
+ if (f === el) continue;
+ if (f.disabled || f.readOnly) continue;
+ if (typeof f.value !== 'string') continue;
+ const t = (f.getAttribute('type') || '').toLowerCase();
+ if (t === 'password' || t === 'hidden' || t === 'file' || t === 'checkbox' || t === 'radio') continue;
+ try { if (isOtpInputValueSecret(f)) continue; } catch (e) { continue; }
+ if (++seen > """
+ + str(_COLLATERAL_SCAN_MAX)
+ + r""") break;
+ // Never reuse a tag already on the element: cloneNode copies it, so a page that clones a form row
+ // would leave two elements answering to one record and the read-back would resolve the wrong one.
+ const tag = seen + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
+ try { f.setAttribute('data-tv3-collateral', tag); } catch (e) { continue; }
+ out.push([tag, f.value]);
+ }
+ return out;
+}"""
+)
+
+
# How type put the caret in a field: a checked click, focus() alone, or an unchecked press at its centre.
_Reach = Literal["click", "focus", "point"]
@@ -5006,8 +5256,11 @@ _MENU_OPTION_TEXTS_JS = (
}
}
} catch (e) { /* attributes unreadable: no veto values */ }
+ // The nearest tagged ancestor, so a caller can tell a node nested inside another candidate from a sibling.
+ const outer = el.parentElement ? composedClosest(el.parentElement, '[data-tv3-' + attr + ']') : null;
return {
n: parseInt(el.getAttribute('data-tv3-' + attr), 10),
+ inside: outer ? parseInt(outer.getAttribute('data-tv3-' + attr), 10) : null,
text: (el.innerText || el.textContent || '').trim(),
nav: nav,
setsize: Number.isFinite(setsize) && setsize > 0 ? setsize : 0,
@@ -7456,6 +7709,113 @@ async def _count_filled_fields(page: Any) -> int:
return total
+_DOCUMENT_READY_STATE_JS = "() => document.readyState"
+
+# The lifecycle level a readyState reading proves the document reached. `commit` means the response
+# arrived and nothing since -- the level `page.goto(wait_until="commit")` returns on.
+_READINESS_BY_READY_STATE = {"loading": "commit", "interactive": "domcontentloaded", "complete": "load"}
+
+# The floor the commit attempt keeps out of BROWSER_LOADING_TIMEOUT_MS, so a readiness budget set
+# larger than that total can never leave the navigation itself no time at all.
+_NAVIGATE_MIN_COMMIT_TIMEOUT_MS = 5000
+
+# Held back out of the readiness budget for the readyState read that decides the verdict. The
+# lifecycle waits may spend everything else; the read itself has to stay bounded, because a renderer
+# wedged on a synchronous script never answers an evaluate and one given no time would report a page
+# that did load as unreadable.
+_NAVIGATE_READINESS_PROBE_RESERVE_MS = 1000
+
+
+def _navigate_budgets() -> tuple[int, int]:
+ """The (commit, readiness) millisecond budgets, which sum to BROWSER_LOADING_TIMEOUT_MS exactly."""
+ total = settings.BROWSER_LOADING_TIMEOUT_MS
+ readiness = max(0, min(settings.TASK_V3_NAVIGATE_READINESS_TIMEOUT_MS, total - _NAVIGATE_MIN_COMMIT_TIMEOUT_MS))
+ return total - readiness, readiness
+
+
+async def _document_readiness(page: Any, timeout_seconds: float) -> str | None:
+ """The lifecycle level the current document has reached, or None when it could not be read.
+
+ Read from `document.readyState` rather than from whether the wait raised: the raw-CDP engine's
+ `wait_for_load_state` is advisory and returns normally on timeout, so the exception is not a
+ signal every engine gives.
+
+ Bounded because a renderer wedged on a synchronous script never answers an evaluate, and the
+ navigation's stated ceiling has to hold against that — a deadline enforced between awaits cannot
+ interrupt this one.
+ """
+ try:
+ state = await asyncio.wait_for(page.evaluate(_DOCUMENT_READY_STATE_JS), timeout=timeout_seconds)
+ except Exception:
+ LOG.info("taskv3 navigate readiness probe failed", exc_info=True)
+ return None
+ return _READINESS_BY_READY_STATE.get(state) if isinstance(state, str) else None
+
+
+async def _wait_for_readiness(page: Any, budget_ms: int) -> tuple[str | None, float]:
+ """Wait up to `budget_ms` for the committed document to fire domcontentloaded, then load.
+
+ Waits on the document already committed and never re-issues a navigation: a re-goto discards a
+ partially fetched bundle and refetches it from zero, which on a starved link is self-defeating.
+
+ `load` is still what this waits for -- the budget is the bound, not the event -- and what the
+ document actually reached by the time the budget runs out is READ off `readyState` rather than
+ inferred from which wait gave up.
+ """
+ started = time.monotonic()
+ wait_budget_ms = max(0.0, budget_ms - _NAVIGATE_READINESS_PROBE_RESERVE_MS)
+ for state in ("domcontentloaded", "load"):
+ remaining_ms = wait_budget_ms - (time.monotonic() - started) * 1000
+ if remaining_ms <= 0:
+ break
+ try:
+ await page.wait_for_load_state(state, timeout=remaining_ms)
+ except Exception as exc:
+ if not is_driver_error(exc):
+ raise
+ # Any driver refusal leaves the verdict to the readyState read below, which answers for the
+ # document rather than for the wait; and load cannot fire before domcontentloaded has.
+ break
+ probe_ms = max(budget_ms - (time.monotonic() - started) * 1000, _NAVIGATE_READINESS_PROBE_RESERVE_MS)
+ reached = await _document_readiness(page, probe_ms / 1000)
+ return reached, time.monotonic() - started
+
+
+def _scrub_urls_in_text(text: str) -> str:
+ """Every http(s) URL in a driver's message reduced to scheme and host.
+
+ A driver names the URL that failed in full, query string included, and a sign-in or signed link is
+ a bearer secret there exactly as it is in a log line. The ref path already rewrites these spans to
+ the ref token; this is the same rewrite for a URL that was never a ref.
+ """
+
+ def _redact(match: re.Match[str]) -> str:
+ try:
+ return redact_url_secrets(match.group(0))
+ except ValueError:
+ return "<redacted>"
+
+ return URL_IN_TEXT.sub(_redact, text)
+
+
+def _readiness_note(reached: str | None, waited_seconds: float) -> str:
+ """What the model is told about a page whose load event has not fired; empty once it has."""
+ if reached == "load":
+ return ""
+ waited = f"{waited_seconds:.0f}s"
+ if reached is None:
+ return f"; whether the document is ready could not be read after {waited} — observe the page before deciding"
+ if reached == "domcontentloaded":
+ return (
+ f"; the document is ready after {waited}, but the page is still loading its scripts and "
+ "resources — act on what has rendered, or wait for the rest"
+ )
+ return (
+ f"; the document was not ready after {waited} and the page is still loading its scripts and "
+ "resources — act on what has rendered, or wait for the rest"
+ )
+
+
# A probe that reads the DOM from the page's own JS realm can be answered by the page: prototype
# methods and instance properties are both replaceable there, so a forged label earns a forced click
# through a real cover. These probes run in a per-page isolated world instead, a realm the page has
@@ -8130,6 +8490,11 @@ async def _probe_evaluate(target: Any, js: str, selector: str, arg: dict[str, An
`target` is the realm the element lives in. The fallback deliberately stays in THAT realm rather
than dropping to the page's: losing isolation is the trade this fallback has always made, but
answering about the wrong document is not a trade, it is a wrong answer wearing a verdict's clothes.
+
+ `arg` reaches the probe ONLY on the fallback leg. The isolated leg rebuilds it from the selector
+ alone -- see `_evaluate_isolated`, which hardcodes `el: null` so the page cannot re-point a marker
+ at a decoy between the marking and the read. A probe that needs a caller-supplied value therefore
+ cannot use this helper: the key silently does not arrive, and whatever it feeds reads undefined.
"""
_PROBE_ISOLATED.set(None)
isolated = await _evaluate_isolated(target, js, selector)
@@ -8961,6 +9326,7 @@ def build_browser_tools(
# The click/type reaction gate stamps data-tv3-pre on every visible element and the reach probe
# marks the layer it names; bookkeeping that, left in place, costs truncation budget in noise.
html = html.replace(' data-tv3-pre="1"', "").replace(' data-tv3-cover="1"', "")
+ html = _COLLATERAL_ATTR_RE.sub("", html)
# The act-by-mark tag outlives its call, so unlike the other data-tv3-* bookkeeping it is
# still on the page when this runs. It is a stable handle rather than a dangerous one -- the
# token belongs to the element, not the number -- but it is ours, not the page's, and it
@@ -10371,7 +10737,7 @@ def build_browser_tools(
return committed, readable
async def _find_suggestion_rows(
- page: Any, selector: str, query: str, *, any_region: bool = False
+ page: Any, selector: str, query: str, *, any_region: bool = False, match: str | None = None
) -> dict[str, Any] | None:
try:
found = await page.evaluate(
@@ -10381,6 +10747,7 @@ def build_browser_tools(
"field": selector,
"el": (await _probe_arg(page, selector))["el"],
"anyRegion": any_region,
+ "match": match,
},
)
except Exception as e:
@@ -10389,23 +10756,44 @@ def build_browser_tools(
return found if isinstance(found, dict) and found.get("count") else None
async def _await_suggestion_rows(
- page: Any, selector: str, query: str, rounds: int, *, any_region: bool = False
+ page: Any,
+ selector: str,
+ query: str,
+ rounds: int,
+ *,
+ any_region: bool = False,
+ match: str | None = None,
+ settled: Callable[[dict[str, Any]], Awaitable[bool]] | None = None,
) -> dict[str, Any] | None:
# The base poll extends while the widget shows a visible in-flight indicator — the same
# bounded busy extension the open->observe path applies: production pods run at a fraction
# of a vCPU, so a fetch that renders instantly on a laptop lands seconds later there.
+ # `settled` lets the caller keep polling past a reaction it does not accept yet (a "Searching..."
+ # row before the results); the last reaction is returned when time runs out.
found: dict[str, Any] | None = None
+ refused_a_reaction = False
soft_deadline = time.monotonic() + 0.4 * rounds
hard_deadline = time.monotonic() + 8.0
while True:
await asyncio.sleep(0.4)
- found = await _find_suggestion_rows(page, selector, query, any_region=any_region)
+ found = await _find_suggestion_rows(page, selector, query, any_region=any_region, match=match)
if found is not None:
- break
+ if settled is None or await settled(found):
+ break
+ refused_a_reaction = True
now = time.monotonic()
if now >= hard_deadline:
break
if now >= soft_deadline:
+ # A reaction `settled` REFUSED is positive evidence this widget renders into this
+ # field's list and has not finished: the caller's own acceptance test says so, which is
+ # a stronger signal than _MENU_BUSY_JS reading markup for it. A bare
+ # `<li role="option">Searching...</li>` carries no ARIA, role or class that probe can
+ # see, so leaving the exit to it ends the wait on the placeholder with seconds of the
+ # cap still unspent. Nothing reacting at all is not evidence of anything, so a field
+ # that never answered still stops here rather than spending the whole cap.
+ if refused_a_reaction:
+ continue
try:
busy = bool(await page.evaluate(_MENU_BUSY_JS, await _probe_arg(page, selector)))
except Exception:
@@ -10442,7 +10830,7 @@ def build_browser_tools(
# reading it here would always see the list its own typing just opened.
async def _find() -> dict[str, Any] | None:
- return await _find_suggestion_rows(page, selector, probe or value)
+ return await _find_suggestion_rows(page, selector, probe or value, match=value if probe else None)
async def _full_rows() -> list[dict[str, Any]]:
# The tagger truncates each label to 60 chars for payload size; the match must see the whole
@@ -10465,6 +10853,10 @@ def build_browser_tools(
# unmatched row, lone or not, is refused like any other so the model chooses explicitly.
return _match_option_exact(value, rows)
+ # Which tagged units the widget declared no row for, kept so verification can ask about the row
+ # actually CHOSEN rather than about the mixed pool it came from.
+ bare_tagged: set[int] = set()
+
async def _resolve(found: dict[str, Any]) -> tuple[bool, list[dict[str, Any]], int | None, int]:
# A widget that declares its rows hands the pick to the exact matcher over every row it
# tagged. Where nothing declares one, the finder already reduced the reaction to a single
@@ -10477,8 +10869,14 @@ def build_browser_tools(
return bool(found.get("declared")), [], None, 0
if found.get("declared"):
rows = await _full_rows()
- declared_size = max((int(o.get("setsize") or 0) for o in rows), default=0)
- overflow = declared_size if rows and declared_size > len(rows) else 0
+ nonlocal bare_tagged
+ bare_ns = {x for x in (found.get("bare") or []) if isinstance(x, int)}
+ bare_tagged = bare_ns
+ # Only rows the widget DECLARED count against its own aria-setsize; a bare node padding
+ # the list would hide a genuinely truncated one.
+ declared_rendered = [o for o in rows if o.get("n") not in bare_ns]
+ declared_size = max((int(o.get("setsize") or 0) for o in declared_rendered), default=0)
+ overflow = declared_size if declared_rendered and declared_size > len(declared_rendered) else 0
idx = _pick(rows)
if idx is None and overflow == 0:
# No exact-label winner over the complete rendered list — but "several rows" may be
@@ -10488,9 +10886,33 @@ def build_browser_tools(
want = _exact_tier_key(value)
matched = [o for o in rows if _exact_tier_key(str(o.get("text") or "")) == want]
if len(matched) >= 2:
- idx = _lone_duplicate_candidate(matched)
+ # A row the widget DECLARED outranks a bare node wearing the same label. Text
+ # agreement is what the collapse reads, and these two agree on it while being
+ # different options — the bare one can commit another record under an identical
+ # label, which reads as success. Only the declared unit may stand for them.
+ declared_matched = [o for o in matched if o.get("n") not in bare_ns]
+ if declared_matched:
+ idx = (
+ _lone_duplicate_candidate(declared_matched)
+ if len(declared_matched) >= 2
+ else declared_matched[0].get("n")
+ )
+ else:
+ # Every exact match is bare, so the text-agreement collapse cannot run:
+ # bare rows carry no declared identity for it to veto on, and two distinct
+ # records wearing one label would read as a single candidate. Only nesting
+ # is decidable here — a wrapper and the node carrying its label are ONE
+ # candidate, related by the `inside` chain, and the innermost stands for
+ # them. Siblings never share that chain, so they survive as two and refuse.
+ survivors = _without_nested_copies(value, matched)
+ if len(survivors) == 1:
+ idx = survivors[0].get("n")
return True, rows, idx, overflow
- return False, tagged, (_match_option_exact(value, tagged) if exact_only else 1), 0
+ if exact_only:
+ # The tagged labels are cut at 60 chars; an exact match has to see the whole text.
+ rows = await _full_rows()
+ return False, rows, _match_option_exact(value, _without_nested_copies(value, rows)), 0
+ return False, tagged, 1, 0
async def _row_info(n: int) -> dict[str, Any]:
try:
@@ -10499,10 +10921,26 @@ def build_browser_tools(
info = None
return info if isinstance(info, dict) else {}
- found = await _await_suggestion_rows(page, selector, probe or value, rounds)
+ judged: tuple[bool, list[dict[str, Any]], int | None, int] | None = None
+
+ async def _names_the_value(found: dict[str, Any]) -> bool:
+ # A searched reaction answers a broader question than `value`, so the poll ends only when the
+ # exact matcher names a row; whatever reacted before that (a loading row) is not the answer.
+ nonlocal judged
+ judged = await _resolve(found)
+ return judged[2] is not None
+
+ found = await _await_suggestion_rows(
+ page,
+ selector,
+ probe or value,
+ rounds,
+ match=value if probe else None,
+ settled=_names_the_value if probe else None,
+ )
if found is None:
return _TypeaheadPick(None, None, False, None, clicked=False, declared=False)
- declared_rows, rows, idx, overflow = await _resolve(found)
+ declared_rows, rows, idx, overflow = judged if judged is not None else await _resolve(found)
if idx is None:
note = (
f"the list declares {overflow} rows and only {len(rows)} are rendered — type the option's full label"
@@ -10605,10 +11043,19 @@ def build_browser_tools(
"noSuggestionList": from_focus,
"suggTagged": True,
"commitEvtArmed": commit_evt_armed,
- "declaredRows": declared_rows,
+ # The DECLARED-row exemption in the verifier is about the row that was clicked, not
+ # about the pool it was picked from: a bare row in a mixed list must not inherit it,
+ # or a re-render that merely drops the tags reads as the list closing on a commit.
+ "declaredRows": declared_rows and idx not in bare_tagged,
"fieldDeclared": await _field_declares_list(page, selector),
"preHidden": pre_hidden,
"chosenValues": declared,
+ "otherRows": [
+ text
+ for text in (str(o.get("text") or "") for o in rows)
+ if _exact_tier_key(text) != _exact_tier_key(best_txt)
+ ],
+ "nestedRows": _rows_nested_in(idx, rows),
},
best_txt,
pre_surface_hit,
@@ -10659,6 +11106,80 @@ def build_browser_tools(
except Exception:
return False
+ async def _capture_collateral(page: Any, selector: str) -> list[list[str]]:
+ # Read every sibling field the keystrokes could reach, immediately BEFORE they are sent. Taken
+ # any earlier this would also hold whatever the focus click made the page write, which is the
+ # page reacting to a click it did get -- not ours to take back.
+ try:
+ captured = await _probe_evaluate(page, _COLLATERAL_VALUES_JS, selector, await _probe_arg(page, selector))
+ except Exception:
+ return []
+ return captured if isinstance(captured, list) else []
+
+ async def _collateral_moved_while_typing(page: Any, captured: list[list[str]]) -> list[list[str]]:
+ # Read the siblings back the moment the keys stop, and keep only the ones that moved. The
+ # restore happens much later -- after the suggestion poll -- and a page write that resolves in
+ # that gap (a focus-triggered fetch, an autofill, a deferred widget update) was not caused by
+ # our keystrokes. Deciding ownership from the target alone cannot see the difference; the
+ # timing can.
+ if not captured:
+ return []
+ try:
+ now = await page.evaluate(_COLLATERAL_READBACK_JS, [e[0] for e in captured if len(e) == 2])
+ except Exception:
+ return []
+ if not isinstance(now, list) or len(now) != len(captured):
+ return []
+ return [
+ entry for entry, value in zip(captured, now, strict=False) if isinstance(value, str) and value != entry[1]
+ ]
+
+ async def _restore_collateral(page: Any, captured: list[list[str]]) -> None:
+ # A segmented control routes keys to the segment ITS OWN cursor is on, which focus() does not
+ # move, so the characters land in a sibling input while the target reads back empty. The caller
+ # has already proved the target never took the keys, so a sibling that moved holds them.
+ # One evaluate reads every tag back: a per-field locator would pay its own actionability
+ # timeout for each field the page has since hidden or re-rendered away.
+ try:
+ current = await page.evaluate(_COLLATERAL_READBACK_JS, [e[0] for e in captured if len(e) == 2])
+ except Exception:
+ return
+ if not isinstance(current, list) or len(current) != len(captured):
+ return
+ moved: list[tuple[str, str]] = []
+ for (tag, was), now in zip(captured, current, strict=False):
+ if not isinstance(now, str) or now == was:
+ continue
+ moved.append((tag, was))
+ if not moved:
+ return
+ if len(moved) > _COLLATERAL_RESTORE_MAX:
+ # One field's keystrokes cannot reach this many. Something else in the page moved them, and
+ # a restore would overwrite it -- refuse the whole set rather than pick a subset to undo.
+ LOG.info("taskv3 type collateral too wide to attribute", fields=len(moved))
+ return
+ for tag, was in moved:
+ try:
+ # fill() fires no blur, so a widget that only commits on blur can still hold the stray
+ # keys internally. The input and what the page renders from it are repaired either way.
+ # Short wait on purpose: this field was writable moments ago and visibly moved, so a
+ # page that has since hidden or disabled it is not going to become actionable -- the
+ # full timeout would just buy that refusal once per field.
+ await page.fill(f'[data-tv3-collateral="{tag}"]', was, timeout=_COLLATERAL_FILL_TIMEOUT_MS)
+ except Exception:
+ LOG.debug("taskv3 collateral restore failed", tag=tag)
+ # Count what actually went back, over the fields that MOVED. Counting over the whole scan would
+ # let every untouched sibling satisfy `now == was` and report a repair that never happened --
+ # the same false success this path exists to refuse.
+ try:
+ after = await page.evaluate(_COLLATERAL_READBACK_JS, [tag for tag, _ in moved])
+ except Exception:
+ return
+ if not isinstance(after, list) or len(after) != len(moved):
+ return
+ restored = sum(1 for (_, was), now in zip(moved, after, strict=False) if isinstance(now, str) and now == was)
+ LOG.info("taskv3 type collateral restored", fields=restored, attempted=len(moved))
+
async def _restore_pre_type_value(page: Any, selector: str, pre_value: str | None, typed: list[str]) -> None:
# A refusal must hand the field back the way it found it. Leaving our query behind overwrites
# whatever the page had already put there -- a cascade-filled code, a prefilled dial code -- with
@@ -10678,7 +11199,14 @@ def build_browser_tools(
LOG.debug("taskv3 pre-type value restore failed", selector=selector)
async def _type_and_commit(
- page: Any, selector: str, value: str, rounds: int, *, focus_fallback: bool = False
+ page: Any,
+ selector: str,
+ value: str,
+ rounds: int,
+ *,
+ focus_fallback: bool = False,
+ collateral: list[list[str]] | None = None,
+ query: str | None = None,
) -> tuple[_TypeaheadPick, str | None, str | None, _Reach]:
# Keystroke-type (so a widget's async suggestion fetch fires on real key events). Snapshot the
# visible DOM BEFORE the focus click, not just before typing: a widget that opens its full list on
@@ -10712,8 +11240,16 @@ def build_browser_tools(
await page.evaluate(_FOCUS_SNAPSHOT_JS, await _probe_arg(page, selector))
except Exception:
pass
+ # `query` is what the caller chose to search with; the row committed must still be `value` exactly.
+ typed = query or value
+ if collateral is not None and reach != "click":
+ # Only a field the click could not reach can misroute its keys, and only that path restores.
+ # A checked click leaves the page untagged and pays nothing.
+ collateral.extend(await _capture_collateral(page, selector))
await page.fill(selector, "", timeout=15000)
- await page.type(selector, value, delay=15, timeout=15000)
+ await page.type(selector, typed, delay=15, timeout=15000)
+ if collateral:
+ collateral[:] = await _collateral_moved_while_typing(page, collateral)
if not presnapshot_ok or reach != "click":
# Without the pre-snapshot the reaction-gate can't tell a new suggestion from static page
# text, so don't run the finder ungated (it could click unrelated content) — leave the typed
@@ -10725,7 +11261,15 @@ def build_browser_tools(
pre_own,
reach,
)
- pick = await _commit_typeahead(page, selector, value, rounds, pre_own=pre_own)
+ pick = await _commit_typeahead(
+ page,
+ selector,
+ value,
+ rounds,
+ exact_only=typed != value,
+ probe=typed if typed != value else None,
+ pre_own=pre_own,
+ )
return pick, pre_value, pre_own, reach
async def _close_lingering_typeahead_list(
@@ -11127,9 +11671,10 @@ def build_browser_tools(
async def _type_typeahead_commit(page: Any, selector: str, text: str, *, text_is_secret: bool) -> ToolResult:
# keystroke-type (via _type_and_commit) so a widget that fetches suggestions on key events —
# not just on a single `input` from fill — still surfaces them, then commit the best match.
+ collateral: list[list[str]] = []
try:
pick, pre_value, _pre_own, reach = await _type_and_commit(
- page, selector, text, rounds=3, focus_fallback=True
+ page, selector, text, rounds=3, focus_fallback=True, collateral=collateral
)
except _FieldCovered as exc:
return _covered_error(exc.selector, exc.occluder)
@@ -11171,7 +11716,22 @@ def build_browser_tools(
await asyncio.sleep(0.3)
if await _find_suggestion_rows(page, selector, text, any_region=True) is None:
return ToolResult.ok(f"typed into {selector}")
+ # Collateral is ours only when the keystrokes demonstrably went nowhere near the target, and
+ # there are two ways that shows: the target still holds what it held before, or it is empty
+ # because this call cleared it and nothing landed after. A target holding anything ELSE took
+ # some of the text, so a sibling that moved with it is the widget distributing that value --
+ # a segment auto-advance, a cascade -- which is the page's, not ours to undo. Decided BEFORE
+ # the target restore, which would otherwise make every target look unchanged.
+ ours = False
+ if collateral and not reacted and pre_value is not None:
+ held_now = await _read_field_value(page, selector)
+ ours = held_now == pre_value or held_now == ""
await _restore_pre_type_value(page, selector, pre_value, [text])
+ if ours:
+ # After the target restore, not before: handing the target its value back is itself a
+ # write this widget can misroute, so the sibling has to be read once that write is done
+ # or we would restore it and then corrupt it again.
+ await _restore_collateral(page, collateral)
return ToolResult.error(
f"typed into {selector}, but it does not hold the typed text afterwards — the field is NOT "
"filled and may hold part of it. It sits outside the viewport and could only be "
@@ -11839,16 +12399,18 @@ def build_browser_tools(
return any(holds(norm(part)) for part in surface.split("\u0001"))
- async def _commit_custom_combobox(page: Any, selector: str, value: str) -> ToolResult:
+ async def _commit_custom_combobox(page: Any, selector: str, value: str, search: str | None = None) -> ToolResult:
# Every non-ok exit below must close the field's OWN list if the attempt left it open (D2) —
# applied once here, at the exit, rather than at every refusal branch below.
opened_by_typing = await _anchor_typeable(page, selector) and await _list_opened_on_an_empty_field(
page, selector
)
- result = await _commit_custom_combobox_attempt(page, selector, value)
+ result = await _commit_custom_combobox_attempt(page, selector, value, search)
return await _close_own_list_on_exit(page, selector, result, opened_by_typing=opened_by_typing)
- async def _commit_custom_combobox_attempt(page: Any, selector: str, value: str) -> ToolResult:
+ async def _commit_custom_combobox_attempt(
+ page: Any, selector: str, value: str, search: str | None = None
+ ) -> ToolResult:
# Shared custom-combobox commit — the ONE path select_combobox and select_option's non-native
# branch both route through. Two mechanisms, one tool call: a TYPEAHEAD (searchable react-select /
# spl-autocomplete) commits by keystroke-type -> WAIT for the reacting suggestion -> click ->
@@ -11914,6 +12476,10 @@ def build_browser_tools(
# query or on focus and start answering at two characters, which is the only question that
# reaches a vocabulary the value itself is absent from ("Illinois" -> "Il" -> "IL").
rungs: list[str] = []
+ if query:
+ # The caller already chose what to ask; typing pieces of the value over it would also
+ # overwrite whatever the widget wrote in answer.
+ return rungs
leading = value.split(",", 1)[0].strip()
if leading and leading != value:
rungs.append(leading)
@@ -11985,10 +12551,11 @@ def build_browser_tools(
# Every query this call puts in the field, so a refusal can tell OUR text (safe to take back)
# from a value the widget wrote in reaction (the page's, and not ours to discard).
- typed_queries: list[str] = [value]
+ query = search if search and search != value else None
+ typed_queries: list[str] = [query or value]
if await _anchor_typeable(page, selector):
try:
- pick, pre_value, pre_own, _ = await _type_and_commit(page, selector, value, rounds=8)
+ pick, pre_value, pre_own, _ = await _type_and_commit(page, selector, value, rounds=8, query=query)
except _FieldCovered as exc:
# A widget that renders its committed selection as a pill list OVER its own input is
# not blocked — it is DONE when a pill in its own container already carries the
@@ -12021,11 +12588,19 @@ def build_browser_tools(
await _restore_pre_type_value(page, selector, pre_value, typed_queries)
return _identical_text_rows_error(selector, value, same_text, tags_live=False, note=pick.note)
await _restore_pre_type_value(page, selector, pre_value, typed_queries)
+ # Some widgets search only part of what is typed, so the full label can answer with
+ # other rows; what to search for instead is the caller's call, not a rule's.
+ next_step = (
+ f"none of them is {value!r}: pass one of these rows exactly as value, or a different search"
+ if query
+ else "pass the option's full text as value; if value already is that full text, call "
+ "select_combobox with it and a shorter search the widget answers with this row (e.g. its code)"
+ )
return _ambiguous_rows_error(
selector,
value,
pick.candidates,
- next_step="pass the option's full text",
+ next_step=next_step,
note=pick.note,
rows_unread=bool(pick.overflow),
)
@@ -12037,18 +12612,20 @@ def build_browser_tools(
why = await _unverifiable_because(page, selector)
if why:
return ToolResult.ok(
- f"typed {value!r} into {selector}; {why}, so the suggestion list could not be seen "
+ f"typed {query or value!r} into {selector}; {why}, so the suggestion list could not be seen "
"and no selection was verified — re-observe to confirm the value committed before "
"relying on it"
)
# Everything below that re-asks the widget, or hands the field back, is written for a
# control whose rows a rule can name; a field that declares no list keeps today's path.
declared_field = await _field_declares_list(page, selector)
+ # A caller-chosen search is our text wherever it was typed, so a refusal takes it back.
+ restore_on_refusal = declared_field or query is not None
# A drill-down widget hides its options under expandable category rows, so open→observe→pick's
# flat enumeration cannot reach them — surface the categories and fail loudly instead.
cats = await _categories_note(page, selector)
if cats:
- if declared_field:
+ if restore_on_refusal:
await _restore_pre_type_value(page, selector, pre_value, typed_queries)
return ToolResult.error(
f"no autocomplete suggestion matched {value!r} for {selector}; the field is NOT filled. {cats}"
@@ -12095,7 +12672,7 @@ def build_browser_tools(
offered_total = len(offered)
if not offered:
offered, offered_total = on_open, on_open_total
- if not offered:
+ if not offered and not query:
await _offer_on_empty_query()
offered, offered_total = await _read_offered()
if len(offered) > 15:
@@ -12103,6 +12680,8 @@ def build_browser_tools(
await _restore_pre_type_value(page, selector, pre_value, typed_queries)
else:
offered, offered_total = await _read_offered()
+ if restore_on_refusal:
+ await _restore_pre_type_value(page, selector, pre_value, typed_queries)
if offered and offered_total > len(offered):
offered_note = (
f". The list offers {offered_total} rows; the first {len(offered)}: "
@@ -12124,7 +12703,7 @@ def build_browser_tools(
)
# The focus-click of the type attempt may have opened this widget's list, so close it first.
opened = await _open_observe_pick(page, selector, value, close_open_menu=True)
- if declared_field and opened.status != "ok":
+ if restore_on_refusal and opened.status != "ok":
await _restore_pre_type_value(page, selector, pre_value, typed_queries)
return opened
if pick.declared and not pick.clicked:
@@ -12135,7 +12714,7 @@ def build_browser_tools(
if isinstance(laddered, ToolResult) and laddered.status == "ok":
return laddered
await _restore_pre_type_value(page, selector, pre_value, typed_queries)
- return await _typeahead_verdict_result(
+ verdict = await _typeahead_verdict_result(
pick.suggestion,
pick.committed,
pick.readable,
@@ -12143,6 +12722,11 @@ def build_browser_tools(
surface_vouched_pre_click=pick.pre_surface_hit,
shared_surface=pick.shared_surface,
)
+ # A click the widget ignored leaves the caller's search in the field, which is text the
+ # widget never accepted as a value.
+ if query is not None and verdict.status != "ok":
+ await _restore_pre_type_value(page, selector, pre_value, typed_queries)
+ return verdict
# A non-typeable anchor (a button/div that only opens a list on click): open, observe, pick.
return await _open_observe_pick(page, selector, value)
@@ -12369,14 +12953,47 @@ def build_browser_tools(
)
else:
_reload_confirm_pending[0] = None
+ # Commit first, then wait for readiness on THAT document, under budgets that sum to today's
+ # single-attempt ceiling. A page whose bundle is starved still commits in under a second, so
+ # one wait_until="load" attempt spends the whole ceiling and reports nothing about the page;
+ # here the wait is bounded by the readiness budget and what it reached is reported either way.
+ commit_timeout_ms, readiness_budget_ms = _navigate_budgets()
try:
- response = await page.goto(url, timeout=60000, wait_until="load")
+ response = await page.goto(url, timeout=commit_timeout_ms, wait_until="commit")
except Exception as exc:
- if not from_ref:
+ # The driver's own net:: code, which is a closed vocabulary and carries no URL, so the
+ # loop's log line keeps naming why a navigation failed now that this returns rather than
+ # raising with a traceback.
+ nav_error_code = driver_nav_error_code(str(exc))
+ # Only a driver's own refusal is a navigation verdict. A Playwright-family error is one, and
+ # so is a net:: code from any engine (the raw-CDP engine's errors are not a Playwright
+ # family). Anything else raised in here is this repo's own defect: it keeps its traceback
+ # through the loop's raise line instead of flattening into a cause-less navigation_failed.
+ if not is_driver_error(exc) and nav_error_code is None:
raise
# Playwright names the URL that failed, which after a redirect is not the ref: every URL
- # in the cause was reached by following the ref, so the model sees it as the token.
- return ToolResult.error(f"navigation failed: {URL_IN_TEXT.sub(lambda _m: requested, str(exc))}")
+ # in the cause was reached by following the ref, so the model sees it as the token. A URL
+ # that was never a ref is reduced to scheme and host instead — the driver names it whole,
+ # query string included, and the model's own argument is already echoed above.
+ detail = URL_IN_TEXT.sub(lambda _m: requested, str(exc)) if from_ref else _scrub_urls_in_text(str(exc))
+ failure: dict[str, Any] = {}
+ if nav_error_code is not None:
+ failure["nav_error_code"] = nav_error_code
+ return ToolResult.error(
+ f"navigation to {requested} did not commit: {detail}",
+ failure or None,
+ error_class="navigation_failed",
+ )
+ reached, readiness_seconds = await _wait_for_readiness(page, readiness_budget_ms)
+ # Through _current_page() because `is_closed` is page-only: a Frame does not implement it, and
+ # `page` here is whatever realm the call resolved in.
+ if _current_page().is_closed():
+ # The readiness wait swallows any driver refusal, so a page that died inside it would
+ # otherwise report as a committed-but-unread page the model could act on.
+ return ToolResult.error(
+ f"navigation to {requested} committed but the page closed before it finished loading",
+ error_class="navigation_failed",
+ )
landed = await _url(page)
# A payload ref that redirects hands its provenance to wherever it lands, so a credential the
# landing URL carries is masked at the boundary exactly like the ref itself. An error page
@@ -12387,11 +13004,30 @@ def build_browser_tools(
# Surface the HTTP status: an error page otherwise reads as a successful navigation, hiding
# dead URLs and blank shells from the model.
status = f" (HTTP {response.status})" if response is not None else ""
+ # Reported, never adjudicated: the tool says which lifecycle level the document reached and how
+ # long it waited, and the model decides whether to observe, wait, or move on.
+ readiness = _readiness_note(reached, readiness_seconds)
# page_state_changed tells the loop's action-loop guard the world moved: a re-attempt after
# a navigation is a fresh attempt, not a repeat against unchanged state. A same-URL reload is
# flagged separately: it resets state rather than progressing it, and the loop's budget
- # extension must not read it as page-change evidence.
- data: dict[str, Any] = {"page_state_changed": True}
+ # extension must not read it as page-change evidence. `same_page` is the pre-navigation
+ # reading, carried for the record alone — nothing here branches on it.
+ data: dict[str, Any] = {
+ "page_state_changed": True,
+ "landed_url": redact_url_secrets(landed),
+ "same_page": same_page,
+ }
+ if reached not in ("load", "domcontentloaded"):
+ # The loop's cue to stop the batch here: the rest of it was queued against a document this
+ # call could not report as ready, and the model has to read that before it acts again. A
+ # ready document is NOT one of these -- the page may still be fetching, but the model can
+ # act on what parsed, which is the whole point of returning at domcontentloaded.
+ data["readiness_incomplete"] = True
+ # One ok_class, two different facts: a document that genuinely never became ready, and a
+ # readyState read that failed (a wedged renderer answers no evaluate). The result text
+ # already distinguishes them for the model; this says which to a fleet read, without a
+ # fourth class.
+ data["readiness_read_failed"] = reached is None
# Classified from where the navigation LANDED, not what was requested: a same-URL request
# that redirects somewhere new is a real transition, while any request (alias, redirect,
# or the URL itself) landing back on the pre-navigation page is a reload in effect.
@@ -12426,7 +13062,13 @@ def build_browser_tools(
if "navigation_dead_end" in data:
outcome["navigation_dead_end"] = data["navigation_dead_end"]
data[ACTION_OUTCOME_DATA_KEY] = outcome
- return ToolResult.ok(f"navigated to {landed}{status}", data=data)
+ # Spelled literally per branch, not looked up: `ok_class` is only type-checked inside loop.py,
+ # so a computed value here would be checked by nothing.
+ if reached == "load":
+ return ToolResult.ok(f"navigated to {landed}{status}", data=data, ok_class="loaded")
+ if reached == "domcontentloaded":
+ return ToolResult.ok(f"navigated to {landed}{status}{readiness}", data=data, ok_class="document_ready")
+ return ToolResult.ok(f"navigated to {landed}{status}{readiness}", data=data, ok_class="committed_not_loaded")
async def file_upload(args: dict[str, Any]) -> ToolResult:
# Lazy import: keeps this module importable for unit tests without the full forge/storage graph.
@@ -12599,7 +13241,8 @@ def build_browser_tools(
return ambiguous
selector = await _resolve_mirrored_host_control(page, selector)
value = _resolve_text(args["value"])
- return await _commit_custom_combobox(page, selector, value)
+ search = args.get("search")
+ return await _commit_custom_combobox(page, selector, value, _resolve_text(str(search)) if search else None)
def _look_nothing_marked_message() -> str:
base = "look: no interactive controls are visible in the viewport."
@@ -12850,6 +13493,8 @@ def build_browser_tools(
def _with_act_by_mark(handler: ToolHandler) -> ToolHandler:
async def wrapped(args: dict[str, Any]) -> ToolResult:
+ if mark_is_filler(args.get("mark")):
+ args.pop("mark")
mark = args.get("mark")
if mark is None:
return await handler(args)
@@ -13435,8 +14080,13 @@ def build_browser_tools(
"Fill an autocomplete/typeahead/combobox field (location, school, employer lookups): types the "
"value, waits for the suggestion list to render, selects the best-matching suggestion, and "
"verifies the field committed. Use this INSTEAD of `type` for such fields — it errors if no "
- "suggestion matches so you never leave uncommitted raw text.",
- _obj({"selector": {"type": "string"}, "value": {"type": "string"}}, ["selector", "value"]),
+ "suggestion matches so you never leave uncommitted raw text. Optional `search`: what to type "
+ "instead of `value` when the widget does not list the option for its full text (e.g. the code of "
+ "'City, County, State - 12345'); the option selected must still be exactly `value`.",
+ _obj(
+ {"selector": {"type": "string"}, "value": {"type": "string"}, "search": {"type": "string"}},
+ ["selector", "value"],
+ ),
select_combobox,
),
_spec(
@@ -13472,7 +14122,13 @@ def build_browser_tools(
),
wait,
),
- _spec("navigate", "Navigate the browser to a URL.", _obj({"url": {"type": "string"}}, ["url"]), navigate),
+ _spec(
+ "navigate",
+ "Navigate the browser to a URL. The result reports where it landed, the HTTP status, and "
+ "whether the page has finished loading.",
+ _obj({"url": {"type": "string"}}, ["url"]),
+ navigate,
+ ),
_spec(
"file_upload",
"Upload a file (local path or URL) into a file input, or into the upload button/dropzone that "
diff --git a/skyvern/services/otp_email.py b/skyvern/services/otp_email.py
index a5109acb3..b253101b5 100644
--- a/skyvern/services/otp_email.py
+++ b/skyvern/services/otp_email.py
@@ -47,9 +47,24 @@ class EmailOTPSourceContext:
credential_ids: list[str] | None = None
credential_ids_loaded_at: datetime | None = None
+ # Set while a refresh is in flight and left set if it never returns, so an empty cached list is
+ # not reported as a current absence of inboxes.
+ credential_list_refresh_failed: bool = False
last_searched_at_by_credential: dict[str, datetime] = field(default_factory=dict)
+ # Credentials whose most recent search raised. Cleared once a search returns, so a wait that
+ # ends here can say the mailbox was unreachable rather than empty.
+ failed_credential_ids: set[str] = field(default_factory=set)
+ # Credentials whose search returned at least once. A wait cancelled mid-search leaves the
+ # credential out of here, which is the only way to tell an unfinished search from an empty one.
+ completed_credential_ids: set[str] = field(default_factory=set)
+ # Candidates the parser rejected. They are deliberately left out of seen_message_keys so a later
+ # tick retries them, so this is keyed by message to keep a retried one from counting twice.
+ unreadable_message_keys: set[tuple[str, str]] = field(default_factory=set)
seen_message_keys: set[tuple[str, str]] = field(default_factory=set)
seen_message_key_order: deque[tuple[str, str]] = field(default_factory=deque)
+ # Eviction is recorded rather than inferred from the set size: the cap spans every credential,
+ # so filtering to the connected ones can leave a count below it that is still a lower bound.
+ messages_evicted: bool = False
provider_state: dict[str, dict] = field(default_factory=dict)
def has_seen_message(self, credential_id: str, message_id: str) -> bool:
@@ -70,6 +85,7 @@ class EmailOTPSourceContext:
self.seen_message_key_order.append(key)
while len(self.seen_message_key_order) > MAX_SEEN_EMAIL_MESSAGE_IDS:
self.seen_message_keys.discard(self.seen_message_key_order.popleft())
+ self.messages_evicted = True
@dataclass
@@ -156,7 +172,7 @@ class GmailOTPSource:
required_scopes=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
if not credentials or not credentials.token:
- return []
+ raise EmailOTPSearchError("no usable Gmail credentials", source=self.name)
try:
candidates = await google_gmail_service.search_recent_otp_messages(
access_token=credentials.token,
@@ -226,7 +242,7 @@ class OutlookOTPSource:
required_scopes=["Mail.Read"],
)
if not access_token:
- return []
+ raise EmailOTPSearchError("no usable Outlook credentials", source=self.name)
excluded_message_ids = context.seen_message_ids_for_credential(credential_id)
try:
candidates = await outlook.search_recent_otp_messages(
diff --git a/skyvern/services/otp_service.py b/skyvern/services/otp_service.py
index 8d27e456f..b5cc0a653 100644
--- a/skyvern/services/otp_service.py
+++ b/skyvern/services/otp_service.py
@@ -44,6 +44,13 @@ class RawOTPVerificationContext:
# Types that were present but rejected for not matching expected_otp_type; lets a caller
# that times out say which kind of OTP did arrive instead of only that none matched.
observed_otp_types: set[OTPType] = field(default_factory=set)
+ # Every stored row the queries returned, before any run, task or expiry filter. Rows Skyvern
+ # persisted from its own inbox search are in here too, so this is not a forwarded/pushed count.
+ # A row in here was returned, not necessarily parsed: the reparse budget stops the scan early.
+ seen_row_ids: set[str] = field(default_factory=set)
+ # False until the stored-code queries return once, so a wait that times out first can say the
+ # store went unchecked instead of claiming it was empty.
+ store_queried: bool = False
@dataclass
@@ -1063,6 +1070,9 @@ async def _get_otp_value_from_db(
created_after=created_after,
excluded_ids={row_id for row_id, otp_type in context.misses if otp_type == expected_otp_type},
)
+ context.seen_row_ids.update(row.totp_code_id for row in totp_codes)
+ context.seen_row_ids.update(row.totp_code_id for row in raw_rows)
+ context.store_queried = True
# The parsed repository groups run-scoped rows ahead of unscoped forwarded
# messages, and raw rows come from a separate query. Re-establish global
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 0615de6e0..df7acb56c 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -104,6 +104,7 @@ from skyvern.forge.sdk.api.files import (
get_run_temp_dir,
list_downloading_files_in_directory,
list_files_in_directory,
+ normalize_download_identity,
resolve_run_download_id,
wait_for_download_finished,
)
@@ -1524,6 +1525,55 @@ async def _save_adopted_session_download(
# the expensive dropdown/custom-select rescrape; never gates persistence or task finalization.
_false_click_download_eligible: ContextVar[bool] = ContextVar("false_click_download_eligible", default=False)
+# True once an action has committed a real browser dispatch (reached the type handler). Reset per
+# action at the ``handle_action`` wrapper entry and read back there to decide whether a failed action
+# owns its download reservations: a committed dispatch retains them for the durable-credit seam; a
+# no-dispatch exit (pre-handler error, stale abort, already-in-desired-state suppression) releases
+# them. Fails toward retention -- a missed suppression stays committed, degrading to base-equivalent
+# retention rather than releasing a genuinely-owned claim.
+_browser_dispatch_committed: ContextVar[bool] = ContextVar("browser_dispatch_committed", default=False)
+
+
+def _suppress_redundant_desired_click() -> list[ActionResult]:
+ """A control already in the desired state: no physical click is dispatched. Mark the action
+ no-dispatch so its epoch's download reservations are released rather than retained on exit."""
+ _browser_dispatch_committed.set(False)
+ return [ActionAbort(desired_state_reached=True)]
+
+
+def _settle_download_reservations_on_exit(
+ context: SkyvernContext,
+ task: Task,
+ action: Action,
+ prior_reservations: tuple[tuple[Page, ...], tuple[Page, ...]],
+ *,
+ failed: bool,
+) -> None:
+ """Decide a finished action's download reservations on the dispatch boundary, not on result status.
+
+ - No browser dispatch committed (pre-handler exit, stale abort, already-desired-state suppression):
+ the epoch cannot own a download, so release it now for every outcome.
+ - Dispatched and not failed: the reservations are causally owned; keep them for the credit seam.
+ - Dispatched then failed/raised: keep them until this step's durable-credit seam can consume them,
+ then release if uncredited (restoring generic blank-page recovery). An internal-recovery close
+ keeps its guarded claim in place -- it mints no epoch reservation, so nothing new is deferred.
+ """
+ if not _browser_dispatch_committed.get():
+ # retain_download_popup_reservations also stops the epoch's capture listener.
+ context.retain_download_popup_reservations(task.task_id, prior_reservations)
+ return
+ if not failed:
+ # A later successful dispatch owns reservations beyond the failed epoch's snapshot.
+ context.cancel_pending_download_reservation_release(task.task_id)
+ return
+ if isinstance(action, ClosePageAction) and action.is_internal_recovery:
+ return
+ # Dispatched then failed: keep the capture listener armed to the next action's entry -- the same
+ # boundary as a successful dispatch -- so a popup that joins the context after handle_action returns
+ # but before the next action is still observed. Only the reservation release is deferred, to the
+ # step's durable-credit seam, instead of dropping the claim now.
+ context.stash_pending_download_reservation_release(task.task_id, prior_reservations)
+
def _remove_download_listener(page: Page, callback: Callable[[Download], None]) -> None:
off = getattr(page, "off", None)
@@ -1611,12 +1661,21 @@ def _record_action_owned_popup_delta(
task_id: str,
initiating_page: Page,
baseline: _PageDeltaBaseline | None,
+ download_dir: Path | None = None,
+ attempt_started_at: datetime | None = None,
+ session_baseline_files: list[str] | None = None,
+ session_observed: bool = False,
) -> _PageDeltaOutcome:
"""At the action-finally boundary, claim every still-present Page newly added to the initiating
BrowserContext since the baseline, excluding the initiating and baseline pages (store-deduped by exact
identity; no delayed/global/credit-time sweep). Valid only inside the baseline's exact BrowserContext:
if recovery reconnected into a different context, claim zero (``context_replaced``) rather than treating
- that context's pre-existing tabs as new. Disabled (zero) when the baseline was unavailable."""
+ that context's pre-existing tabs as new. Disabled (zero) when the baseline was unavailable.
+
+ Each delta claim is anchored to the run dir's file snapshot at this boundary, unioned with the caller's
+ pre-fetched session snapshot (final + in-flight) when the run has a browser session, so dead-blank
+ recovery observes it against its own baseline, not a stale block baseline. No snapshot at all (no run
+ dir, no session) -> recovery falls back to the block baseline for those pages."""
if owning_context is None or baseline is None:
return _PageDeltaOutcome(claimed=0, context_replaced=False, pages=[])
try:
@@ -1626,27 +1685,42 @@ def _record_action_owned_popup_delta(
current_pages = list(current_context.pages)
except Exception:
return _PageDeltaOutcome(claimed=0, context_replaced=False, pages=[])
+ baseline_files: list[str] | None = None
+ if download_dir is not None:
+ baseline_files = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
+ if session_baseline_files:
+ baseline_files = baseline_files + list(session_baseline_files)
+ elif session_baseline_files:
+ baseline_files = list(session_baseline_files)
delta_pages: list[Page] = []
for candidate in current_pages:
if candidate is initiating_page:
continue
if any(candidate is baseline_page for baseline_page in baseline.pages):
continue
- owning_context.record_download_popup_claim(task_id, candidate)
+ owning_context.record_download_popup_claim(
+ task_id,
+ candidate,
+ baseline_files=baseline_files,
+ session_observed=session_observed,
+ # Augment (union) the per-page session baseline: for a page already event-recorded with a stale
+ # pre-action snapshot, this later finally-boundary session snapshot is unioned in, not ignored.
+ session_baseline_files=session_baseline_files,
+ )
delta_pages.append(candidate)
+ # A single delta popup owns any new file unambiguously (round-14 credit). Two or more claimed at this
+ # one instant are same-action siblings with no file->page mapping: mark them so a non-complete recovery
+ # does not early-credit-and-close one sibling on another sibling's later-settling file, cancelling its
+ # own still-pending download. The shared file snapshot above stays correct for "pre-existed this sweep";
+ # this only guards a file that lands AFTER the sweep, which no per-candidate snapshot could baseline.
+ if len(delta_pages) > 1:
+ owning_context.mark_download_popup_claim_delta_siblings(task_id, delta_pages)
return _PageDeltaOutcome(claimed=len(delta_pages), context_replaced=False, pages=delta_pages)
-# The CDP download interceptor names its in-flight temp file ``<final>.<uuid4().hex>.crdownload`` (32
-# lowercase hex chars) before hard-linking to ``<final>``; Chrome-native downloads use ``<final>.crdownload``.
-# Stripped after the ``.crdownload`` suffix, this collapses both temp shapes to the same ``<final>`` identity.
-_INTERCEPTOR_TEMP_IDENTITY_RE = re.compile(r"\.[0-9a-f]{32}$")
-
-
-def _normalize_download_identity(file: str) -> str:
- if not file.endswith(BROWSER_DOWNLOADING_SUFFIX):
- return file
- return _INTERCEPTOR_TEMP_IDENTITY_RE.sub("", file.removesuffix(BROWSER_DOWNLOADING_SUFFIX))
+# Shared identity normalization (defined in the files module) so the in-flight -> settled collapse is
+# identical on the v4 false-click path and the dead-blank recovery observer.
+_normalize_download_identity = normalize_download_identity
def _local_download_signal_identities(download_dir: Path, *, attempt_started_at: datetime | None = None) -> set[str]:
@@ -1735,7 +1809,11 @@ async def _settle_and_close_false_click_download(
continue
observed_delta_pages.append(candidate)
if owning_context is not None:
- owning_context.record_download_popup_claim(task.task_id, candidate)
+ owning_context.record_download_popup_claim(
+ task.task_id,
+ candidate,
+ baseline_files=list_files_in_directory(download_dir, attempt_started_at=attempt_started_at),
+ )
if _local_download_signal_identities(download_dir, attempt_started_at=attempt_started_at) - signal_before:
file_signal_observed = True
if observed_delta_pages and file_signal_observed:
@@ -2278,6 +2356,15 @@ async def _recover_download_page(
recovered_page = await browser_state.get_working_page()
if recovered_page is None:
raise RuntimeError("Browser reconnect did not create a working page")
+ # The replacement working page is deliberately created and persistent. On the direct new_page path
+ # it just joined the initiating context and the download context.on("page") owner may have recorded
+ # it as a blank late candidate; retire it from both registries as the next synchronous ownership op
+ # -- before the navigation await -- so a delayed download credit cannot close it. (The reconnect path
+ # produces a page on a fresh context with no owner armed, so it is never recorded and this is a safe
+ # no-op there.)
+ recovery_context = skyvern_context.current()
+ if recovery_context is not None:
+ recovery_context.retire_intentional_page(task.task_id, recovered_page)
await browser_state.navigate_to_url(page=recovered_page, url=page_url_before_download)
await browser_state.set_active_page(recovered_page)
except Exception:
@@ -4582,6 +4669,63 @@ class ActionHandler:
*,
file_download_false_click_eligible: bool = False,
allow_stale_refresh: bool = False,
+ ) -> list[ActionResult]:
+ context = skyvern_context.current()
+ prior_reservations: tuple[tuple[Page, ...], tuple[Page, ...]] = ((), ())
+ if context is not None:
+ # Stop the previous action's capture listener before this action begins (the fixed causal
+ # capture boundary). A prior dispatched-then-failed epoch's reservations are NOT released
+ # here: they must survive later same-batch actions and durable credit, so the deferred
+ # release is applied only at the step's complete-on-download no-credit seam (or terminal
+ # cleanup). This action's own baseline snapshot therefore still includes those reservations,
+ # so a no-dispatch retain below preserves rather than disturbs the earlier failed epoch.
+ context.stop_download_popup_capture(task.task_id)
+ prior_reservations = context.snapshot_download_popup_reservations(task.task_id)
+ _browser_dispatch_committed.set(False)
+ try:
+ results = await ActionHandler._handle_action_with_downloads(
+ scraped_page,
+ task,
+ step,
+ page,
+ action,
+ file_download_false_click_eligible=file_download_false_click_eligible,
+ allow_stale_refresh=allow_stale_refresh,
+ )
+ except BaseException as exit_error:
+ if context is not None:
+ if isinstance(exit_error, Exception):
+ _settle_download_reservations_on_exit(context, task, action, prior_reservations, failed=True)
+ else:
+ # A cancellation (BaseException, not Exception) re-raises through the step loop's
+ # `except CancelledError`, which -- unlike every failure handler -- re-raises without
+ # running clean_up_task, so no next action and no teardown will invalidate capture at a
+ # later boundary. Keeping the listener armed here (the ordinary failed-dispatch behavior)
+ # would strand it on the live BrowserContext. Detach now and drop this epoch's reservation;
+ # retain keeps prior epochs, and once the listener is off a queued callback cannot recreate
+ # what it released.
+ context.retain_download_popup_reservations(task.task_id, prior_reservations)
+ raise
+ if context is not None:
+ _settle_download_reservations_on_exit(
+ context,
+ task,
+ action,
+ prior_reservations,
+ failed=_terminal_action_status(results) == ActionStatus.failed,
+ )
+ return results
+
+ @staticmethod
+ async def _handle_action_with_downloads(
+ scraped_page: ScrapedPage,
+ task: Task,
+ step: Step,
+ page: Page,
+ action: Action,
+ *,
+ file_download_false_click_eligible: bool = False,
+ allow_stale_refresh: bool = False,
) -> list[ActionResult]:
# task_id, step_id auto-attached by @traced from SkyvernContext
_action_span = otel_trace.get_current_span()
@@ -4605,25 +4749,26 @@ class ActionHandler:
# Ownership transfer: this action's incoming page is now accepted navigation state, so retire any
# stale task-scoped popup claim for that exact Page left by an earlier action that never got a durable
# download credit. Identity-based, before any action-specific branch so it covers the false-click,
- # explicit-download, and non-download paths alike; recovery rebinds and switch-tab adoption are the
- # next action entry's transfer, not this one.
+ # explicit-download, and non-download paths alike. SWITCH_TAB retires its selected target in the
+ # switch handler, where that exact Page is first known.
# An internal-recovery close must NOT retire the dead page's claim here: the recovery guard
# below reads it to fail closed on a claimed download popup, so retiring it would blind that
# check and let recovery close a page that is still capturing a download.
_reuse_owning_context = skyvern_context.current()
- if (
- not (isinstance(action, ClosePageAction) and action.is_internal_recovery)
- and _reuse_owning_context is not None
- and _reuse_owning_context.discard_download_popup_claim(task.task_id, page)
+ if _reuse_owning_context is not None and not (
+ isinstance(action, ClosePageAction) and action.is_internal_recovery
):
- with contained_effect("retire reused download popup claim"):
- LOG.info(
- "Retired download popup claim for reused page",
- task_id=task.task_id,
- step_id=step.step_id,
- discarded=1,
- reason="page_reused_as_initiating",
- )
+ discarded_claim = _reuse_owning_context.discard_download_popup_claim(task.task_id, page)
+ discarded_candidate = _reuse_owning_context.discard_download_popup_late_candidate(task.task_id, page)
+ if discarded_claim or discarded_candidate:
+ with contained_effect("retire reused download popup claim"):
+ LOG.info(
+ "Retired download popup claim for reused page",
+ task_id=task.task_id,
+ step_id=step.step_id,
+ discarded=1,
+ reason="page_reused_as_initiating",
+ )
# TODO: maybe support all action types in the future(?)
trigger_download_action = (
isinstance(action, (SelectOptionAction, ClickAction, DownloadFileAction)) and action.download
@@ -4729,11 +4874,44 @@ class ActionHandler:
# captured in the action coroutine (never current() here). The in-seam cleanup below
# stays the primary close; the claim is a superset backstop, deduped by Page identity.
if false_click_owning_context is not None:
- false_click_owning_context.record_download_popup_claim(task.task_id, download_page)
+ false_click_owning_context.record_download_popup_claim(
+ task.task_id,
+ download_page,
+ baseline_files=list_files_in_directory(
+ false_click_download_dir, attempt_started_at=false_click_attempt_started_at
+ ),
+ )
false_click_popup_event_count += 1
page.on("popup", on_popup)
+ def on_context_child(child_page: Page) -> None:
+ # Discovery can outlive the action's popup listener; closing still requires durable credit.
+ if false_click_owning_context is None or false_click_baseline is None:
+ return
+ if child_page is page or child_page.context is not false_click_baseline.browser_context:
+ return
+ if any(child_page is baseline_page for baseline_page in false_click_baseline.pages):
+ return
+ false_click_owning_context.record_download_popup_late_candidate(
+ task.task_id,
+ child_page,
+ baseline_files=list_files_in_directory(
+ false_click_download_dir, attempt_started_at=false_click_attempt_started_at
+ ),
+ )
+
+ if (
+ false_click_owning_context is not None
+ and false_click_gate_context is not None
+ and false_click_baseline is not None
+ and false_click_baseline.browser_context is false_click_gate_context
+ ):
+ # Remain observable after return, until the next action or credit/teardown.
+ false_click_owning_context.arm_download_popup_context_listener(
+ task.task_id, false_click_gate_context, on_context_child
+ )
+
async def process_captured_download(results: list[ActionResult] | None) -> None:
await asyncio.sleep(0)
captured: tuple[Download, Page] | None = None
@@ -4874,6 +5052,8 @@ class ActionHandler:
task_id=task.task_id,
initiating_page=page,
baseline=false_click_baseline,
+ download_dir=false_click_download_dir,
+ attempt_started_at=false_click_attempt_started_at,
)
if false_click_delta.context_replaced:
with contained_effect("record download popup context replacement"):
@@ -4959,12 +5139,21 @@ class ActionHandler:
# be recorded here for the task's credit seam to close it later. Records into the context
# captured in the action coroutine, never current() at Playwright dispatch time.
if context is not None:
- context.record_download_popup_claim(task.task_id, popup_page)
+ context.record_download_popup_claim(
+ task.task_id,
+ popup_page,
+ baseline_files=list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
+ + session_download_baseline,
+ session_observed=bool(task.browser_session_id),
+ # Augment the per-page session baseline so the action-finally resnapshot (which re-records
+ # this same popup) can union a later, more conservative session view over this one.
+ session_baseline_files=session_download_baseline,
+ )
def _download_signal_identity(file: str) -> str:
return _normalize_download_identity(file)
- async def _list_download_signal_files() -> list[str]:
+ async def _list_download_signal_files(*, capture_session_into: list[str] | None = None) -> list[str]:
files = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if task.browser_session_id:
downloading_files_in_browser_session = await app.STORAGE.list_downloading_files_in_browser_session(
@@ -4973,7 +5162,10 @@ class ActionHandler:
downloaded_files_in_browser_session = await app.STORAGE.list_downloaded_files_in_browser_session(
organization_id=task.organization_id, browser_session_id=task.browser_session_id
)
- files = files + downloaded_files_in_browser_session + downloading_files_in_browser_session
+ session_files = downloaded_files_in_browser_session + downloading_files_in_browser_session
+ if capture_session_into is not None:
+ capture_session_into.extend(session_files)
+ files = files + session_files
return files
async def _list_final_download_files() -> list[str]:
@@ -5055,8 +5247,14 @@ class ActionHandler:
if browser_state:
initial_page_count = len(await browser_state.list_valid_pages())
+ # The per-claim session baseline is the SESSION portion of the single authoritative pre-click read
+ # below -- captured in one listing, never a second one. Pre-click, so it can never include this
+ # action's own download (round-14 invariant); if the read fails, the whole action fails on the
+ # authoritative baseline (as before this PR) rather than minting false durable credit.
+ session_download_baseline: list[str] = []
signal_file_identities_before = {
- _download_signal_identity(file) for file in await _list_download_signal_files()
+ _download_signal_identity(file)
+ for file in await _list_download_signal_files(capture_session_into=session_download_baseline)
}
list_files_before = list(signal_file_identities_before)
LOG.info(
@@ -5592,11 +5790,24 @@ class ActionHandler:
except Exception:
with contained_effect("remove download popup claim recorder"):
LOG.warning("Failed to remove download popup claim recorder", exc_info=True)
+ # Baseline the swept popups against the PRE-ACTION session view (captured before the click),
+ # NOT a fresh finally re-snapshot. Causal attribution: only files present before the action
+ # began are provably not this action's own download. A finally re-fetch cannot tell an earlier
+ # action's just-settled file from THIS popup's own just-settled download (both appear after the
+ # pre-action fetch), so re-fetching risks baselining out -- and permanently denying credit to --
+ # the popup's own download that settles anywhere in the teardown/grace window. Earlier actions'
+ # files are already in the pre-action view (they exist at action start); the residual (an earlier
+ # in-flight download not yet listed at pre-action, a storage-listing latency) is accepted so the
+ # own download is never denied credit. The delta sweep still re-reads the LOCAL dir here.
explicit_delta = _record_action_owned_popup_delta(
context,
task_id=task.task_id,
initiating_page=page,
baseline=explicit_baseline,
+ download_dir=download_dir,
+ attempt_started_at=attempt_started_at,
+ session_baseline_files=session_download_baseline,
+ session_observed=bool(task.browser_session_id),
)
if explicit_delta.context_replaced:
with contained_effect("record download popup context replacement"):
@@ -5758,11 +5969,18 @@ class ActionHandler:
actions_result.append(stop_result)
return actions_result
+ # Setup can interact before returning or raising; exceptions must retain ownership.
+ # Only a normal, explicitly effect-free setup exit clears this commitment.
+ _browser_dispatch_committed.set(True)
# do setup before action handler
if setup := ActionHandler._setup_action_types.get(action.action_type):
results = await setup(action, page, scraped_page, task, step)
actions_result.extend(results)
if results and results[-1] != ActionSuccess:
+ if isinstance(action, (ClickAction, SelectOptionAction)) and all(
+ result.success and not result.setup_performed for result in results
+ ):
+ _browser_dispatch_committed.set(False)
return actions_result
# do the handler
@@ -6799,7 +7017,7 @@ async def _apply_label_desired_click_state(
action=action,
desired_state=desired_state,
)
- return [ActionAbort(desired_state_reached=True)]
+ return _suppress_redundant_desired_click()
LOG.info(
"Label's bound control differs from the desired state, continuing with a single normal click",
action=action,
@@ -6834,7 +7052,7 @@ async def _apply_checkbox_desired_click_state(
return None
if native_state == desired_state:
LOG.info("Control already in the desired state, suppressing the redundant click", action=action)
- return [ActionAbort(desired_state_reached=True)]
+ return _suppress_redundant_desired_click()
LOG.info("Setting the native control to the desired state", action=action, desired_state=desired_state)
set_outcome = await _set_native_checkbox_state(element, should_check=desired_state)
if set_outcome is NativeSetOutcome.VERIFIED:
@@ -6853,10 +7071,10 @@ async def _apply_checkbox_desired_click_state(
positively_unselected = state is _GridRowSelection.UNSELECTED
if positively_selected and desired_state:
LOG.info("Row already selected, suppressing the redundant click", action=action)
- return [ActionAbort(desired_state_reached=True)]
+ return _suppress_redundant_desired_click()
if positively_unselected and not desired_state:
LOG.info("Row already unselected, suppressing the redundant click", action=action)
- return [ActionAbort(desired_state_reached=True)]
+ return _suppress_redundant_desired_click()
if not desired_state:
# Deselect intent. Only a positively-SELECTED row is driven off its selection; an UNMARKED row is
@@ -6873,7 +7091,7 @@ async def _apply_checkbox_desired_click_state(
native_checked = None
if native_checked is False:
LOG.info("Unmarked row with the box positively off already matches desired unselected", action=action)
- return [ActionAbort(desired_state_reached=True)]
+ return _suppress_redundant_desired_click()
LOG.info("Unmarked row can't be proven unselected, continuing the normal click", action=action)
return None
@@ -6931,7 +7149,7 @@ async def _apply_desired_click_state(
action=action,
desired_state=desired_state,
)
- return [ActionAbort(desired_state_reached=True)]
+ return _suppress_redundant_desired_click()
if element.get_tag_name() == "input":
# Only a native radio reaches here (checkbox is handled above; a non-toggle input has no
# readable state and already fell open). The guard below rejects a checked radio requested
@@ -10829,6 +11047,13 @@ async def handle_new_tab_action(
return [ActionFailure(Exception("No browser state found for the task"), stop_execution_on_failure=False)]
validated_url = await asyncio.to_thread(validate_fetch_url, action.url)
new_page = await browser_state.new_page()
+ # A deliberately-created tab is not a stranded download popup. The context.on("page") owner records this
+ # exact new page (still blank) the instant new_page() joins it, so retire it from both download-popup
+ # registries as the very next synchronous op -- before the navigation await below, during which a delayed
+ # download credit could otherwise close the intentional tab. Idempotent if no owner recorded it.
+ new_tab_context = skyvern_context.current()
+ if new_tab_context is not None:
+ new_tab_context.retire_intentional_page(task.task_id, new_page)
try:
await browser_state.navigate_to_url(page=new_page, url=validated_url)
except Exception as e:
@@ -10871,6 +11096,10 @@ async def handle_switch_tab_action(
)
]
target_page = pages[action.tab_index]
+ # Retire the selected tab before activation yields to delayed download credit.
+ context = skyvern_context.current()
+ if context is not None:
+ context.retire_intentional_page(task.task_id, target_page)
await browser_state.set_active_page(target_page)
try:
await target_page.bring_to_front()
diff --git a/skyvern/webeye/actions/multi_field_totp.py b/skyvern/webeye/actions/multi_field_totp.py
index efa667935..1e368ee7e 100644
--- a/skyvern/webeye/actions/multi_field_totp.py
+++ b/skyvern/webeye/actions/multi_field_totp.py
@@ -1,5 +1,6 @@
"""Shared OTP group discovery and continuity checks; no browser writes."""
+import json
import re
from dataclasses import dataclass
from enum import StrEnum
@@ -14,6 +15,7 @@ from skyvern.webeye.scraper.scraped_page import ScrapedPage
from skyvern.webeye.scraper.scraper import structural_identity
from skyvern.webeye.utils.document import get_main_document_loader_id
from skyvern.webeye.utils.dom import resolve_locator
+from skyvern.webeye.utils.page import SkyvernFrame
LOG = structlog.get_logger()
@@ -320,7 +322,16 @@ async def _multi_field_totp_frame_gone(page: Page, frame_id: str) -> bool | None
continue
try:
frame_element = await frame.frame_element()
- current_id = await frame_element.get_attribute(SKYVERN_ID_ATTR)
+ # The iframe's ElementHandle is owned by the frame that resolved it -- its parent, or the
+ # main frame when an orphan attach briefly leaves `parent_frame` None -- so read the id
+ # there through the common evaluate abstraction, in the handle's own context.
+ # `get_attribute` would instead block for the full 30s action timeout re-resolving
+ # `:scope` once the parent document navigated.
+ current_id = await SkyvernFrame.evaluate(
+ frame=frame.parent_frame or page.main_frame,
+ expression=f"(element) => element.getAttribute({json.dumps(SKYVERN_ID_ATTR)})",
+ arg=frame_element,
+ )
except Exception:
unknown_frame = True
continue
diff --git a/skyvern/webeye/browser_object_predicates.py b/skyvern/webeye/browser_object_predicates.py
index edfab02ad..bb259d259 100644
--- a/skyvern/webeye/browser_object_predicates.py
+++ b/skyvern/webeye/browser_object_predicates.py
@@ -32,6 +32,37 @@ _REQUIRED_PAGE_CAPABILITIES = ("main_frame", "context", "bring_to_front", "evalu
_FRAME_ONLY_CAPABILITIES = ("page", "parent_frame")
+# Every member ``DownloadLike`` promises. ``suggested_filename`` + ``save_as`` are the
+# download discriminators: no page, frame, or response carries them, so an object that
+# reaches an upload helper by mistake is rejected on capability alone.
+_REQUIRED_DOWNLOAD_CAPABILITIES = ("suggested_filename", "path", "failure", "save_as", "page")
+
+
+class DownloadLike(Protocol):
+ """Structural download surface a caller may rely on once ``is_download_like`` holds."""
+
+ @property
+ def suggested_filename(self) -> str: ...
+
+ @property
+ def page(self) -> Any: ...
+
+ def path(self) -> Any: ...
+
+ def failure(self) -> Any: ...
+
+ def save_as(self, path: Any) -> Any: ...
+
+
+def is_download_like(obj: object) -> TypeGuard[DownloadLike]:
+ """True if ``obj`` structurally presents as a browser download a claim resolved to.
+
+ Engine-neutral stand-in for ``isinstance(obj, Download)``: a raw-CDP or Patchright
+ download answers the same capabilities without sharing Playwright's class identity.
+ """
+ return all(hasattr(obj, capability) for capability in _REQUIRED_DOWNLOAD_CAPABILITIES)
+
+
class PageLike(Protocol):
"""Structural page surface a caller may rely on once ``is_page_like`` holds.
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.py
index d5649098a..b35719c84 100644
--- a/skyvern/webeye/cdp_download_interceptor.py
+++ b/skyvern/webeye/cdp_download_interceptor.py
@@ -610,6 +610,17 @@ def normalize_download_filename(filename: str, content_type: str = "") -> str:
return filename
+def monitor_saved_download_name(filename: str, content_type: str = "") -> str:
+ """The basename this monitor would save ``filename`` under, or "" when it is not a usable basename.
+
+ It percent-decodes, so names that differ only by escaping land on one file.
+ """
+ try:
+ return _validated_download_basename(filename, content_type)
+ except ValueError:
+ return ""
+
+
def _validated_download_basename(filename: str, content_type: str = "") -> str:
decoded_filename = filename.strip()
while True:
@@ -3075,6 +3086,13 @@ async def false_click_download_attribution_is_quiescent(browser_context: Browser
return await interceptor.prove_pre_action_download_quiescence()
+def is_monitoring_browser_downloads_for_context(browser_context: BrowserContext | None) -> bool:
+ interceptor = (
+ getattr(browser_context, "_skyvern_cdp_download_interceptor", None) if browser_context is not None else None
+ )
+ return isinstance(interceptor, CDPDownloadInterceptor) and interceptor.is_monitoring_browser_downloads()
+
+
def has_download_interceptor_for_context(browser_context: BrowserContext | None) -> bool:
interceptor = (
getattr(browser_context, "_skyvern_cdp_download_interceptor", None) if browser_context is not None else None
diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.py
index 0eedd1005..8e423e972 100644
--- a/skyvern/webeye/scraper/scraper.py
+++ b/skyvern/webeye/scraper/scraper.py
@@ -837,7 +837,17 @@ async def add_frame_interactable_elements(
# it will get stuck when we `frame.evaluate()` on an invisible iframe
if not await frame_element.is_visible():
return elements, element_tree
- skyvern_id = await frame_element.get_attribute(SKYVERN_ID_ATTR)
+ # The iframe's ElementHandle is owned by the frame that resolved it -- its parent, or the main
+ # frame when an orphan attach briefly leaves `parent_frame` None -- so read the id there through
+ # the common evaluate abstraction, in the handle's own context. `get_attribute` would instead
+ # re-resolve the handle through the driver's `:scope` selector, blocking for the full 30s action
+ # timeout once the parent document navigated; evaluating in the owning context fails fast.
+ skyvern_id = await SkyvernFrame.evaluate(
+ frame=frame.parent_frame or frame.page.main_frame,
+ expression=f"(element) => element.getAttribute({json.dumps(SKYVERN_ID_ATTR)})",
+ arg=frame_element,
+ engine_selection=engine_selection,
+ )
if not skyvern_id:
LOG.info(
"No Skyvern id found for frame, skipping",
diff --git a/skyvern/webeye/utils/captcha_solver.py b/skyvern/webeye/utils/captcha_solver.py
index 86bea58f7..3b582b017 100644
--- a/skyvern/webeye/utils/captcha_solver.py
+++ b/skyvern/webeye/utils/captcha_solver.py
@@ -109,6 +109,7 @@ async def _bounded_locator_count(locator: Any) -> int:
try:
return await asyncio.wait_for(locator.count(), timeout=1.0)
except Exception:
+ LOG.info("CAPTCHA locator count did not complete", arm="presence", exc_info=True)
return 0
@@ -127,6 +128,26 @@ def _intersects_viewport(box: Any, viewport: Any) -> bool:
)
+async def _has_presented_match(locator: Any, viewport: dict[str, float] | None, *, arm: str = "presence") -> bool:
+ """Whether the locator has a match laid out where a user could act on it. Every match is walked, not a
+ prefix: a stale hidden widget can precede the live one, and a candidate that raises is skipped rather than
+ read as evidence the page carries no challenge."""
+ try:
+ async with asyncio.timeout(1.0):
+ for index in range(await locator.count()):
+ candidate = locator.nth(index)
+ try:
+ if not await candidate.is_visible():
+ continue
+ if viewport is None or _intersects_viewport(await candidate.bounding_box(), viewport):
+ return True
+ except Exception:
+ LOG.info("CAPTCHA presented-match candidate could not be read", arm=arm, exc_info=True)
+ except Exception:
+ LOG.info("CAPTCHA presented-match probe did not complete", arm=arm, exc_info=True)
+ return False
+
+
async def _frame_has_visible_match(
frame: Any, selector: str | None, viewport: Any, *, challenge_frames: bool = False
) -> bool:
@@ -151,13 +172,7 @@ async def _frame_has_visible_match(
return box is not None and box["width"] > 1 and box["height"] > 1 and _intersects_viewport(box, viewport)
if selector is None:
return False
- # Every match, not a prefix: stale hidden widgets can precede the live one; the timeout bounds the walk.
- matches = frame.locator(selector)
- for index in range(await matches.count()):
- match = matches.nth(index)
- if await match.is_visible() and _intersects_viewport(await match.bounding_box(), viewport):
- return True
- return False
+ return await _has_presented_match(frame.locator(selector), viewport, arm="nested_presence")
async def _visible_child_frame_match(
@@ -281,14 +296,13 @@ async def _solve_challenge_ladder_impl(
"""
start = time.monotonic()
checkbox = page.locator(_CAPTCHA_CHECKBOX_SELECTOR)
- checkbox_count = await _bounded_locator_count(checkbox)
marker = page.locator(_CAPTCHA_MARKER_SELECTOR)
- marker_count = await _bounded_locator_count(marker)
# A challenge nested in a child frame only widens this presence check: the DOM-checkbox arm below
# clicks through a page-level locator and can never drive a nested checkbox.
if (
- checkbox_count == 0
- and marker_count == 0
+ not await _has_presented_match(checkbox, None)
+ # No viewport at page level: a marker below the fold of a long form is still a challenge.
+ and not await _has_presented_match(marker, None)
and not await _visible_child_frame_match(
page,
f"{_CAPTCHA_CHECKBOX_SELECTOR}, {_CAPTCHA_MARKER_SELECTOR}" if probe_child_frames else None,
@@ -297,7 +311,7 @@ async def _solve_challenge_ladder_impl(
):
return False
- if checkbox_count == 1:
+ if await _bounded_locator_count(checkbox) == 1:
candidate = checkbox.first
try:
if await candidate.is_visible() and await candidate.is_enabled():
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index b6669a2c0..e5209c51f 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -3,6 +3,7 @@
# -- begin speed up unit tests
import asyncio
import contextlib
+import hashlib
import itertools
import logging
import os
@@ -24,6 +25,7 @@ from opentelemetry import trace as otel_trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from playwright.async_api import Download
from playwright.async_api import Error as PlaywrightError
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
@@ -34,6 +36,7 @@ from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api import files
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.db.models import Base
+from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager
from skyvern.webeye.utils import page as page_module
from skyvern.webeye.utils.page import ScreenshotMode
@@ -406,6 +409,51 @@ def make_input_element_mock(*, element_id: str = "AADC", attrs: dict[str, object
return el
+def make_claimed_download_mock(
+ *,
+ path: Path | str | None,
+ suggested_filename: str,
+ path_error: BaseException | None = None,
+ failure: str | None = None,
+ failure_error: BaseException | None = None,
+ context: object | None = None,
+) -> Download:
+ """A Playwright ``Download`` double for the value a ``page.expect_download`` claim resolves to.
+ ``spec`` is the real class so the attach guard's ``isinstance`` check sees what it does live."""
+ download = MagicMock(spec=Download)
+ if path_error is not None:
+ download.path.side_effect = path_error
+ else:
+ download.path.return_value = None if path is None else str(path)
+ if failure_error is not None:
+ download.failure.side_effect = failure_error
+ else:
+ download.failure.return_value = failure
+ download.suggested_filename = suggested_filename
+ download.page = SimpleNamespace(context=context)
+ return download
+
+
+SESSION_DOWNLOAD_BYTES = b"session-delivered certificate"
+
+
+def registered_download_row(
+ filename: str = "certificate.pdf",
+ content: bytes = SESSION_DOWNLOAD_BYTES,
+ artifact_id: str | None = "a_session",
+ checksum: str | None = None,
+ file_size: int | None = None,
+) -> FileInfo:
+ """A DOWNLOAD row as the run's registration lists it for a file a remote browser session delivered."""
+ return FileInfo(
+ url=f"https://storage.test/{filename}",
+ filename=filename,
+ checksum=hashlib.sha256(content).hexdigest() if checksum is None else checksum,
+ file_size=len(content) if file_size is None else file_size,
+ artifact_id=artifact_id,
+ )
+
+
@dataclass
class DownloadDestinationHarness:
"""A real HTTP server plus a stubbed resolver, for exercising download destination checks.
diff --git a/tests/unit/copilot_route_test_support.py b/tests/unit/copilot_route_test_support.py
index ea0ab3257..016f98869 100644
--- a/tests/unit/copilot_route_test_support.py
+++ b/tests/unit/copilot_route_test_support.py
@@ -36,6 +36,21 @@ def terminal_narrative_payload() -> dict[str, Any]:
}
+def narrative_payload_with_run(run_id: str | None) -> dict[str, Any]:
+ return {
+ **terminal_narrative_payload(),
+ "turnFacts": {
+ "factsAvailable": True,
+ "evaluationState": None,
+ "runId": run_id,
+ "runCompleted": None,
+ "terminalCause": None,
+ "blocksRunThisTurn": None,
+ "ranCleanOnCurrentSource": False,
+ },
+ }
+
+
def install_fake_create(monkeypatch: pytest.MonkeyPatch) -> dict[str, object]:
"""Capture the stream handler that the route hands to EventSourceStream."""
captured: dict[str, object] = {}
diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.py
index b2364fe6c..519ddd23d 100644
--- a/tests/unit/copilot_test_helpers.py
+++ b/tests/unit/copilot_test_helpers.py
@@ -39,6 +39,7 @@ from skyvern.forge.sdk.copilot.runtime import record_sensitive_origin_run_taint,
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml as process_workflow_yaml
+from skyvern.forge.sdk.schemas.credentials import Credential, CredentialType, CredentialVaultType, PasswordCredential
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequest
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
@@ -78,6 +79,48 @@ DISPATCHED_NAV_ONLY_HTML = (
)
+def wire_credential_vault(
+ monkeypatch: pytest.MonkeyPatch,
+ secrets: PasswordCredential,
+ *,
+ credential_id: str = "cred_1",
+ name: str = "authtest simple",
+) -> Credential:
+ """Serve one saved credential from the org database and ``secrets`` from its vault."""
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ credential = Credential(
+ credential_id=credential_id,
+ organization_id="org-1",
+ name=name,
+ vault_type=CredentialVaultType.SKYVERN,
+ item_id="item_1",
+ credential_type=CredentialType.PASSWORD,
+ username=secrets.username,
+ card_last4=None,
+ card_brand=None,
+ created_at=now,
+ modified_at=now,
+ )
+ monkeypatch.setattr(
+ forge_app.DATABASE,
+ "credentials",
+ SimpleNamespace(
+ get_credential=AsyncMock(return_value=credential),
+ get_credentials_by_ids=AsyncMock(return_value=[credential]),
+ ),
+ raising=False,
+ )
+ vault = SimpleNamespace(get_credential_item=AsyncMock(return_value=SimpleNamespace(name=name, credential=secrets)))
+ # `app` is an AppHolder proxy without __delattr__; patch the underlying instance so teardown can delete it.
+ monkeypatch.setattr(
+ object.__getattribute__(forge_app, "_inst"),
+ "CREDENTIAL_VAULT_SERVICES",
+ {CredentialVaultType.SKYVERN: vault},
+ raising=False,
+ )
+ return credential
+
+
def make_stub_artifact(
artifact_id: str,
file_name: str,
diff --git a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
index 9d881aa01..e37e8846d 100644
--- a/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
+++ b/tests/unit/forge/sdk/copilot/test_browser_code_tool.py
@@ -7,12 +7,15 @@ from contextlib import asynccontextmanager
from dataclasses import replace
from types import SimpleNamespace
from typing import Any
+from unittest.mock import AsyncMock, MagicMock
import pytest
from playwright.async_api import Page
from skyvern.forge import app
from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.copilot import mcp_adapter
+from skyvern.forge.sdk.copilot import runtime as runtime_module
from skyvern.forge.sdk.copilot.browser_ablation import (
CopilotBrowserCodeMode,
CopilotToolSurface,
@@ -24,10 +27,23 @@ from skyvern.forge.sdk.copilot.browser_code_contract import (
BrowserCodeSession,
BrowserCodeSessionUnavailableError,
)
-from skyvern.forge.sdk.copilot.runtime import CopilotBrowserGenerationRetired
-from skyvern.forge.sdk.copilot.tools import _build_skyvern_mcp_overlays
+from skyvern.forge.sdk.copilot.runtime import CopilotBrowserGenerationRetired, browser_session_recovery
+from skyvern.forge.sdk.copilot.secret_scrub import clear_session_scrub_values, register_secret_scrub_value
+from skyvern.forge.sdk.copilot.tools import (
+ _build_skyvern_mcp_overlays,
+)
from skyvern.forge.sdk.copilot.tools import browser_code as browser_code_module
-from skyvern.forge.sdk.copilot.tools import copilot_native_tools, get_skyvern_mcp_alias_map
+from skyvern.forge.sdk.copilot.tools import (
+ copilot_native_tools,
+ edit_block_and_run_tool,
+ get_skyvern_mcp_alias_map,
+)
+from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
+from skyvern.forge.sdk.copilot.tools import (
+ update_and_run_blocks_tool,
+)
+from skyvern.forge.sdk.copilot.workflow_yaml import stored_block_code
+from skyvern.webeye.browser_errors import BrowserCdpConnectionError
from skyvern.webeye.persistent_sessions_manager import BrowserRetirementReason
from tests.unit.conftest import make_copilot_context
@@ -179,6 +195,83 @@ async def test_the_cell_runs_inside_the_browser_lease_and_a_retired_lease_report
assert result["value"] == 1
+async def test_a_debug_cell_that_cannot_reach_its_browser_states_the_last_run_browser(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def prepared(*_args: object, **_kwargs: object) -> tuple[dict[str, Any], None, None]:
+ return {"ok": False, "error": "The browser session could not be reached."}, None, None
+
+ monkeypatch.setattr(browser_code_module, "_prepare_browser_session_for_dispatch", prepared)
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_debug"
+ ctx.last_run_blocks_browser_session_id = "pbs_run"
+ ctx.last_run_blocks_workflow_run_id = "wr_1"
+
+ result = await browser_code_module.run_browser_code(ctx, "1")
+
+ assert result["ok"] is False
+ assert result["last_run_browser_session_id"] == "pbs_run"
+ assert result["last_run_workflow_run_id"] == "wr_1"
+ assert ctx.browser_session_id == "pbs_debug"
+
+
+ ("run_session_id", "states_last_run"),
+ [pytest.param("pbs_run", True, id="distinct-run-browser"), pytest.param("pbs_debug", False, id="same-browser")],
+)
+async def test_a_cell_whose_browser_cannot_be_entered_returns_the_acquisition_fact(
+ monkeypatch: pytest.MonkeyPatch, run_session_id: str, states_last_run: bool
+) -> None:
+ async def prepared(*_args: object, **_kwargs: object) -> tuple[None, None, None]:
+ return None, None, None
+
+ manager = MagicMock()
+ manager.get_browser_state = AsyncMock(side_effect=BrowserCdpConnectionError("CDP connection failed"))
+ monkeypatch.setattr(runtime_module, "app", SimpleNamespace(PERSISTENT_SESSIONS_MANAGER=manager))
+ monkeypatch.setattr(browser_code_module, "_prepare_browser_session_for_dispatch", prepared)
+ ctx = make_copilot_context()
+ ctx.api_key = "sk-test"
+ ctx.browser_session_id = "pbs_debug"
+ ctx.last_run_blocks_browser_session_id = run_session_id
+ ctx.last_run_blocks_workflow_run_id = "wr_1"
+
+ result = await browser_code_module.run_browser_code(ctx, "1")
+
+ assert result["ok"] is False
+ assert "CDP connection failed" in result["error"]
+ assert result["browser_session_id"] == "pbs_debug"
+ assert ("last_run_browser_session_id" in result) is states_last_run
+ assert ctx.browser_session_id == "pbs_debug"
+
+
+async def test_an_unclassified_acquisition_failure_is_named_by_type_not_by_its_own_text(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A classified error's message has been through CDP-endpoint redaction; an unclassified one has
+ not, so its text can carry an internal address and stays out of the model's result."""
+
+ async def prepared(*_args: object, **_kwargs: object) -> tuple[None, None, None]:
+ return None, None, None
+
+ manager = MagicMock()
+ manager.get_browser_state = AsyncMock(side_effect=RuntimeError("connect ws://10.1.2.3:9222/devtools refused"))
+ monkeypatch.setattr(runtime_module, "app", SimpleNamespace(PERSISTENT_SESSIONS_MANAGER=manager))
+ monkeypatch.setattr(browser_code_module, "_prepare_browser_session_for_dispatch", prepared)
+ ctx = make_copilot_context()
+ ctx.api_key = "sk-test"
+ ctx.browser_session_id = "pbs_debug"
+
+ result = await browser_code_module.run_browser_code(ctx, "1")
+
+ assert result["ok"] is False
+ assert "RuntimeError" in result["error"]
+ assert "10.1.2.3" not in json.dumps(result)
+ assert "devtools" not in json.dumps(result)
+
+
@pytest.mark.parametrize("session_ended", [True, False], ids=["session over", "capacity refusal"])
@pytest.mark.asyncio
async def test_a_refusal_that_says_the_session_is_over_drops_it_now(
@@ -771,3 +864,948 @@ async def test_a_debug_reestablishment_does_not_rebind_a_cell_pinned_to_the_last
debug = await browser_code_module.run_browser_code(ctx, "1")
assert "handles_invalidated" in debug and rebinds == ["pbs_chat"]
+
+
+async def test_browser_code_uses_the_existing_page_then_recovery_lock_order(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page_held = asyncio.Event()
+ browser_code_waiting_for_page = asyncio.Event()
+ probe = _LeaseProbeSession([])
+ real_page_custody_lock = browser_code_module.browser_page_custody_lock
+
+ @asynccontextmanager
+ async def observed_page_custody(ctx: Any) -> AsyncIterator[None]:
+ browser_code_waiting_for_page.set()
+ async with real_page_custody_lock(ctx):
+ yield
+
+ @asynccontextmanager
+ async def lease(_ctx: object, **_kwargs: object) -> AsyncIterator[None]:
+ yield
+
+ async def current_page(session_id: str | None = None) -> tuple[SimpleNamespace, None]:
+ return SimpleNamespace(page=probe.page), None
+
+ async def open_session(**_kwargs: object) -> BrowserCodeSession:
+ return probe
+
+ async def prepared(*_args: object, **_kwargs: object) -> tuple[None, None, None]:
+ return None, None, None
+
+ async def page_then_recovery() -> None:
+ async with real_page_custody_lock(ctx):
+ page_held.set()
+ await browser_code_waiting_for_page.wait()
+ async with browser_session_recovery(ctx):
+ pass
+
+ monkeypatch.setattr(browser_code_module, "browser_page_custody_lock", observed_page_custody)
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", lease)
+ monkeypatch.setattr(browser_code_module, "get_page", current_page)
+ monkeypatch.setattr(browser_code_module, "_prepare_browser_session_for_dispatch", prepared)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "open_copilot_browser_code_session", open_session)
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_original"
+ competing_call = asyncio.create_task(page_then_recovery())
+ await page_held.wait()
+
+ try:
+ result = await asyncio.wait_for(browser_code_module.run_browser_code(ctx, "1"), timeout=0.5)
+ finally:
+ if not competing_call.done():
+ competing_call.cancel()
+ await asyncio.gather(competing_call, return_exceptions=True)
+
+ assert result["ok"] is True
+
+
+def _cell(*, ok: bool) -> BrowserCodeCellResult:
+ return BrowserCodeCellResult(
+ ok=ok,
+ value={"observed": True} if ok else None,
+ stdout=None,
+ stdout_truncated=False,
+ error_code=None if ok else "user_code_error",
+ error=None if ok else "NameError: stale_helper is not defined",
+ failing_line=None if ok else 3,
+ operations=(),
+ operations_omitted=0,
+ session_alive=True,
+ current_url="https://fixture.test/",
+ )
+
+
+async def test_fresh_namespace_rebinds_to_the_current_browser_before_resetting(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_replacement"
+ order: list[str] = []
+ session = MagicMock(session_id="browser_code_session", page=object())
+
+ async def reset_namespace() -> None:
+ order.append("reset")
+
+ async def session_for_page(*_args: object, **_kwargs: object) -> object:
+ order.append("rebind")
+ return session
+
+ async def run_cell(*_args: object, **_kwargs: object) -> BrowserCodeCellResult:
+ order.append("run")
+ return _cell(ok=True)
+
+ session.reset_namespace = AsyncMock(side_effect=reset_namespace)
+ session.close = AsyncMock()
+ ctx.browser_code_host.session = session
+
+ @asynccontextmanager
+ async def browser_scope(_ctx: object, **_kwargs: object) -> AsyncIterator[None]:
+ yield
+
+ monkeypatch.setattr(browser_code_module, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(
+ browser_code_module,
+ "_prepare_browser_session_for_dispatch",
+ AsyncMock(return_value=(None, None, None)),
+ )
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", browser_scope)
+ monkeypatch.setattr(
+ browser_code_module,
+ "get_page",
+ AsyncMock(return_value=(SimpleNamespace(page=object()), None)),
+ )
+ monkeypatch.setattr(browser_code_module, "_session_for_page", session_for_page)
+ monkeypatch.setattr(browser_code_module, "_run_cell", run_cell)
+
+ result = await browser_code_module.run_browser_code(ctx, "result = 1", fresh_namespace=True)
+
+ assert result["ok"] is True
+ assert order == ["rebind", "reset", "run"]
+
+
+async def test_fresh_namespace_does_not_reset_a_session_opened_for_a_replacement_browser(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_replacement"
+ old_session = MagicMock(session_id="old_browser_code_session")
+ replacement_session = MagicMock(session_id="replacement_browser_code_session")
+ replacement_session.reset_namespace = AsyncMock()
+ ctx.browser_code_host.session = old_session
+
+ @asynccontextmanager
+ async def browser_scope(_ctx: object, **_kwargs: object) -> AsyncIterator[None]:
+ yield
+
+ monkeypatch.setattr(browser_code_module, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(
+ browser_code_module,
+ "_prepare_browser_session_for_dispatch",
+ AsyncMock(return_value=(None, None, None)),
+ )
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", browser_scope)
+ monkeypatch.setattr(
+ browser_code_module,
+ "get_page",
+ AsyncMock(return_value=(SimpleNamespace(page=object()), None)),
+ )
+ monkeypatch.setattr(
+ browser_code_module,
+ "_session_for_page",
+ AsyncMock(return_value=replacement_session),
+ )
+ monkeypatch.setattr(browser_code_module, "_run_cell", AsyncMock(return_value=_cell(ok=True)))
+
+ result = await browser_code_module.run_browser_code(ctx, "result = 1", fresh_namespace=True)
+
+ assert result["ok"] is True
+ replacement_session.reset_namespace.assert_not_awaited()
+
+
+async def test_sensitive_origin_refusal_does_not_claim_the_namespace_was_reset(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ session = MagicMock(session_id="browser_code_session")
+ session.reset_namespace = AsyncMock()
+ ctx.browser_code_host.session = session
+ monkeypatch.setattr(browser_code_module, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(
+ browser_code_module,
+ "_prepare_browser_session_for_dispatch",
+ AsyncMock(return_value=(None, None, None)),
+ )
+ monkeypatch.setattr(browser_code_module, "sensitive_origin_page_facts_withheld", lambda *_args: True)
+
+ result = await browser_code_module.run_browser_code(ctx, "result = 1", fresh_namespace=True)
+
+ assert result["ok"] is False
+ assert "fresh_namespace" not in result
+ session.reset_namespace.assert_not_awaited()
+
+
+async def test_cancelled_fresh_namespace_discards_session_and_records_interruption(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_browser_code"
+ reset_started = asyncio.Event()
+ never_finishes = asyncio.Event()
+
+ async def blocked_reset() -> None:
+ reset_started.set()
+ await never_finishes.wait()
+
+ session = MagicMock(session_id="browser_code_session")
+ session.reset_namespace = AsyncMock(side_effect=blocked_reset)
+ session.close = AsyncMock()
+ session.last_dispatched_operation.return_value = BrowserCodeOperation(
+ operation="click",
+ selector="#previous",
+ succeeded=True,
+ )
+ ctx.browser_code_host.session = session
+ monkeypatch.setattr(browser_code_module, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(
+ browser_code_module,
+ "_prepare_browser_session_for_dispatch",
+ AsyncMock(return_value=(None, None, None)),
+ )
+
+ @asynccontextmanager
+ async def browser_scope(_ctx: object, **_kwargs: object) -> AsyncIterator[None]:
+ yield
+
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", browser_scope)
+ monkeypatch.setattr(
+ browser_code_module,
+ "get_page",
+ AsyncMock(return_value=(SimpleNamespace(page=object()), None)),
+ )
+ monkeypatch.setattr(browser_code_module, "_session_for_page", AsyncMock(return_value=session))
+
+ reset = asyncio.create_task(browser_code_module.run_browser_code(ctx, "result = 1", fresh_namespace=True))
+ await asyncio.wait_for(reset_started.wait(), timeout=1)
+ reset.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await reset
+
+ assert ctx.browser_code_host.interrupted is True
+ assert ctx.browser_code_host.interrupted_operation is None
+ assert browser_code_module._take_interruption_note(ctx.browser_code_host) == {
+ "previous_call_interrupted": {
+ "state": "the previous run_browser_code call was cancelled and its interpreter stopped"
+ }
+ }
+ session.last_dispatched_operation.assert_not_called()
+ session.close.assert_awaited_once()
+ assert ctx.browser_code_host.session is None
+
+
+async def test_failed_fresh_namespace_reset_discards_the_closed_session(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_reset_failure"
+ session = MagicMock(session_id="browser_code_session")
+ session.reset_namespace = AsyncMock(
+ side_effect=BrowserCodeSessionUnavailableError(
+ "The replacement runner refused the session.", error_code="runner_unavailable"
+ )
+ )
+ session.close = AsyncMock()
+ ctx.browser_code_host.session = session
+ monkeypatch.setattr(browser_code_module, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(
+ browser_code_module,
+ "_prepare_browser_session_for_dispatch",
+ AsyncMock(return_value=(None, None, None)),
+ )
+
+ @asynccontextmanager
+ async def browser_scope(_ctx: object, **_kwargs: object) -> AsyncIterator[None]:
+ yield
+
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", browser_scope)
+ monkeypatch.setattr(
+ browser_code_module,
+ "get_page",
+ AsyncMock(return_value=(SimpleNamespace(page=object()), None)),
+ )
+ monkeypatch.setattr(browser_code_module, "_session_for_page", AsyncMock(return_value=session))
+
+ result = await browser_code_module.run_browser_code(ctx, "result = 1", fresh_namespace=True)
+
+ assert result["error_code"] == "runner_unavailable"
+ assert "refused" in result["error"]
+ session.close.assert_awaited_once()
+ assert ctx.browser_code_host.session is None
+
+
+async def test_build_test_browser_acquisition_waits_for_source_promotion_lock(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_original"
+ verification_started = asyncio.Event()
+
+ async def replace_browser(_ctx: object, **_kwargs: object) -> None:
+ verification_started.set()
+ ctx.browser_session_id = "pbs_replacement"
+
+ monkeypatch.setattr(run_execution_module, "verify_build_test_browser_session_by_attaching", replace_browser)
+
+ async with ctx.browser_session_recovery_lock:
+ acquisition = asyncio.create_task(run_execution_module.acquire_build_test_browser_session(ctx, fresh=False))
+ await asyncio.sleep(0)
+ assert verification_started.is_set() is False
+ assert acquisition.done() is False
+ assert ctx.browser_session_id == "pbs_original"
+
+ assert await acquisition is None
+ assert verification_started.is_set() is True
+ assert ctx.browser_session_id == "pbs_replacement"
+
+
+async def test_unavailable_workbench_does_not_remove_anchored_edit_and_run(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: repair_me
+ code: |
+ return {"value": "before"}
+"""
+ ctx = make_copilot_context(workflow_yaml)
+ captured: dict[str, str] = {}
+
+ async def persist(payload: dict[str, str], _context: object, **_kwargs: object) -> dict[str, object]:
+ captured["workflow_yaml"] = payload["workflow_yaml"]
+ return {"ok": True, "data": {"block_count": 1}}
+
+ assert (
+ await AgentFunction().copilot_browser_code_mode(
+ organization_id=ctx.organization_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ )
+ is CopilotBrowserCodeMode.OFF
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.await_pending_credential_pause", AsyncMock())
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_and_run_requires_skipped_run", lambda *_args: False)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._clear_pending_browser_interaction_observation", lambda *_args: None
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._get_prior_workflow_definition", AsyncMock(return_value=None))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_workflow", persist)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._record_workflow_update_result", lambda *_args: None)
+ run_updated = AsyncMock(return_value=json.dumps({"ok": True, "data": {"workflow_run_id": "wr_anchored"}}))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._run_updated_workflow_blocks", run_updated)
+
+ result = await edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps(
+ {
+ "label": "repair_me",
+ "expected_code": '"before"',
+ "replacement_code": '"after"',
+ "block_labels": ["repair_me"],
+ }
+ ),
+ )
+
+ assert json.loads(result)["ok"] is True
+ assert stored_block_code(captured["workflow_yaml"], "repair_me") == 'return {"value": "after"}\n'
+ run_updated.assert_awaited_once()
+
+
+async def test_source_provenance_is_pinned_to_the_browser_leased_for_the_cell(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ leased_session_ids: list[str | None] = []
+ retained_session_ids: list[str | None] = []
+ replacement_tasks: list[asyncio.Task[None]] = []
+ probe = _LeaseProbeSession([])
+
+ @asynccontextmanager
+ async def lease(ctx: Any, **_kwargs: object) -> AsyncIterator[None]:
+ async def replace_browser() -> None:
+ async with browser_session_recovery(ctx):
+ ctx.browser_session_id = "pbs_replacement"
+ ctx.browser_session_continuity_generation += 1
+
+ replacement_tasks.append(asyncio.create_task(replace_browser()))
+ await asyncio.sleep(0)
+ yield
+
+ async def current_page(session_id: str | None = None) -> tuple[SimpleNamespace, None]:
+ leased_session_ids.append(session_id)
+ return SimpleNamespace(page=probe.page), None
+
+ async def open_session(**_kwargs: object) -> BrowserCodeSession:
+ return probe
+
+ async def prepared(*_args: object, **_kwargs: object) -> tuple[None, None, None]:
+ return None, None, None
+
+ def retain_source(
+ _ctx: object,
+ _code: str,
+ _cell: BrowserCodeCellResult,
+ *,
+ browser_session_id: str | None,
+ browser_session_generation: int,
+ last_run_workflow_run_id: str | None = None,
+ ) -> str:
+ retained_session_ids.append(browser_session_id)
+ return f"browser-code-source:{browser_session_generation}"
+
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", lease)
+ monkeypatch.setattr(browser_code_module, "get_page", current_page)
+ monkeypatch.setattr(browser_code_module, "_prepare_browser_session_for_dispatch", prepared)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "open_copilot_browser_code_session", open_session)
+ monkeypatch.setattr(browser_code_module, "retain_executed_browser_code_source", retain_source)
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_original"
+
+ result = await browser_code_module.run_browser_code(ctx, "1")
+ await asyncio.gather(*replacement_tasks)
+
+ assert result["ok"] is True
+ assert leased_session_ids == retained_session_ids == ["pbs_original"]
+
+
+def test_executed_source_references_are_exact_outcome_bound_and_context_scoped() -> None:
+ ctx = make_copilot_context()
+ successful_source = 'value = "café"\n\nvalue'
+ failed_source = "stale_helper()\n"
+
+ successful_reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ successful_source,
+ _cell(ok=True),
+ browser_session_id=ctx.browser_session_id,
+ browser_session_generation=4,
+ )
+ failed_reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ failed_source,
+ _cell(ok=False),
+ browser_session_id=ctx.browser_session_id,
+ browser_session_generation=4,
+ )
+ ctx.browser_session_continuity_generation = 4
+
+ successful = browser_code_module.resolve_executed_browser_code_source(ctx, successful_reference)
+ failed = browser_code_module.resolve_executed_browser_code_source(ctx, failed_reference)
+ assert successful.status == "valid"
+ assert successful.source == successful_source
+ assert successful.execution_ok is True
+ assert failed.status == "valid"
+ assert failed.source == failed_source
+ assert failed.execution_ok is False
+ assert failed.execution_error_code == "user_code_error"
+
+ another_turn = make_copilot_context()
+ assert browser_code_module.resolve_executed_browser_code_source(another_turn, successful_reference).status == (
+ "wrong_turn"
+ )
+ another_owner = make_copilot_context()
+ another_owner.organization_id = "other-owner"
+ assert browser_code_module.resolve_executed_browser_code_source(another_owner, successful_reference).status == (
+ "wrong_owner"
+ )
+
+ ctx.browser_session_continuity_generation = 5
+ assert browser_code_module.resolve_executed_browser_code_source(ctx, successful_reference).status == (
+ "wrong_generation"
+ )
+ ctx.browser_session_continuity_generation = 4
+ missing = successful_reference.rsplit(":", 1)[0] + ":missing"
+ assert browser_code_module.resolve_executed_browser_code_source(ctx, missing).status == "missing"
+
+ browser_code_module.expire_executed_browser_code_sources(ctx.browser_code_host)
+ expired = browser_code_module.resolve_executed_browser_code_source(ctx, successful_reference)
+ assert expired.status == "expired"
+ assert expired.source is None
+
+
+def test_executed_source_reference_expires_when_browser_session_is_replaced_without_generation_change() -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_original"
+ reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ "result = {'ok': True}",
+ _cell(ok=True),
+ browser_session_id="pbs_original",
+ browser_session_generation=0,
+ )
+
+ ctx.browser_session_id = "pbs_replacement"
+
+ resolution = browser_code_module.resolve_executed_browser_code_source(ctx, reference)
+ assert resolution.status == "wrong_session"
+
+
+async def test_run_browser_code_preserves_opaque_source_reference_during_secret_scrub(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_browser_code"
+ register_secret_scrub_value(ctx, "code")
+
+ @asynccontextmanager
+ async def browser_scope(_ctx: object, **_kwargs: object) -> AsyncIterator[None]:
+ yield
+
+ monkeypatch.setattr(browser_code_module, "_authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr(
+ browser_code_module,
+ "_prepare_browser_session_for_dispatch",
+ AsyncMock(return_value=(None, None, None)),
+ )
+ monkeypatch.setattr(browser_code_module, "mcp_browser_context", browser_scope)
+ monkeypatch.setattr(
+ browser_code_module,
+ "get_page",
+ AsyncMock(return_value=(SimpleNamespace(page=object()), None)),
+ )
+ monkeypatch.setattr(browser_code_module, "_session_for_page", AsyncMock(return_value=object()))
+ monkeypatch.setattr(
+ browser_code_module,
+ "_run_cell",
+ AsyncMock(return_value=replace(_cell(ok=True), value={"secret": "code"})),
+ )
+ monkeypatch.setattr(browser_code_module, "_record_outcome", lambda *_args, **_kwargs: None)
+
+ try:
+ result = await browser_code_module.run_browser_code(ctx, "result = 1\nresult")
+
+ reference = result["executed_source_reference"]
+ assert isinstance(reference, str)
+ assert reference in ctx.browser_code_host.executed_sources
+ assert browser_code_module.resolve_executed_browser_code_source(ctx, reference).status == "valid"
+ assert result["value"]["secret"] != "code"
+ finally:
+ clear_session_scrub_values(ctx.browser_session_id)
+
+
[email protected]("initial_code", ["stale_helper()\n", ""])
+async def test_edit_block_and_run_promotes_the_complete_executed_source_without_retyping(
+ monkeypatch: pytest.MonkeyPatch,
+ initial_code: str,
+) -> None:
+ code_yaml = f" code: |\n {initial_code.strip()}\n" if initial_code else ' code: ""\n'
+ workflow_yaml = (
+ """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: repair_me
+"""
+ + code_yaml
+ )
+ candidate = 'async def renamed_helper():\n return "café"\n\nresult = {"value": await renamed_helper()}\nresult'
+ ctx = make_copilot_context(workflow_yaml)
+ reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ candidate,
+ _cell(ok=True),
+ browser_session_id=ctx.browser_session_id,
+ browser_session_generation=0,
+ )
+ captured: dict[str, Any] = {}
+
+ async def persist(payload: dict[str, Any], _context: object, **_kwargs: object) -> dict[str, object]:
+ captured["workflow_yaml"] = payload["workflow_yaml"]
+ captured["expected_exact_code_by_label"] = payload["_expected_exact_code_by_label"]
+ return {"ok": True, "data": {"block_count": 1}}
+
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.await_pending_credential_pause", AsyncMock())
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_and_run_requires_skipped_run", lambda *_args: False)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._clear_pending_browser_interaction_observation", lambda *_args: None
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._get_prior_workflow_definition", AsyncMock(return_value=None))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_workflow", persist)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._record_workflow_update_result", lambda *_args: None)
+ run_updated = AsyncMock(return_value=json.dumps({"ok": True, "data": {"workflow_run_id": "wr_saved"}}))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._run_updated_workflow_blocks", run_updated)
+
+ result = await edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps(
+ {
+ "label": "repair_me",
+ "executed_source_reference": reference,
+ "block_labels": ["repair_me"],
+ "parameters": {"ordinary_input": "kept for the saved run"},
+ }
+ ),
+ )
+
+ assert json.loads(result)["ok"] is True
+ assert stored_block_code(captured["workflow_yaml"], "repair_me") == candidate
+ assert captured["expected_exact_code_by_label"] == {"repair_me": candidate}
+ assert run_updated.await_args.kwargs["parameters"] == {"ordinary_input": "kept for the saved run"}
+
+
+async def test_promotion_blocks_concurrent_browser_recovery_until_source_is_persisted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: repair_me
+ code: |
+ stale_helper()
+"""
+ candidate = 'result = {"value": "repaired"}\nresult'
+ ctx = make_copilot_context(workflow_yaml)
+ ctx.browser_session_id = "pbs_original"
+ reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ candidate,
+ _cell(ok=True),
+ browser_session_id=ctx.browser_session_id,
+ browser_session_generation=0,
+ )
+ update_started = asyncio.Event()
+ allow_update = asyncio.Event()
+ persisted_generations: list[int] = []
+
+ async def persist(_payload: dict[str, str], _context: object, **_kwargs: object) -> dict[str, object]:
+ update_started.set()
+ await allow_update.wait()
+ persisted_generations.append(ctx.browser_session_continuity_generation)
+ return {"ok": True, "data": {"block_count": 1}}
+
+ outcome = mcp_adapter._BrowserSessionContinuityOutcome(
+ lost_session_id="pbs_original",
+ root_session_id="pbs_original",
+ disposition="reestablished",
+ replacement_session_id="pbs_replacement",
+ )
+ monkeypatch.setattr(mcp_adapter, "_get_continuity_outcome", AsyncMock(return_value=outcome))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.await_pending_credential_pause", AsyncMock())
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_and_run_requires_skipped_run", lambda *_args: False)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._clear_pending_browser_interaction_observation", lambda *_args: None
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._get_prior_workflow_definition", AsyncMock(return_value=None))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_workflow", persist)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._record_workflow_update_result", lambda *_args: None)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._run_updated_workflow_blocks",
+ AsyncMock(return_value=json.dumps({"ok": True, "data": {"workflow_run_id": "wr_saved"}})),
+ )
+
+ promotion = asyncio.create_task(
+ edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps(
+ {
+ "label": "repair_me",
+ "executed_source_reference": reference,
+ "block_labels": ["repair_me"],
+ }
+ ),
+ )
+ )
+ await asyncio.wait_for(update_started.wait(), timeout=1)
+ recovery = asyncio.create_task(
+ mcp_adapter._handle_browser_session_loss(
+ ctx,
+ tool_name="evaluate",
+ call_path="model",
+ lost_session_id="pbs_original",
+ )
+ )
+ try:
+ await asyncio.sleep(0)
+ assert recovery.done() is False
+ assert ctx.browser_session_continuity_generation == 0
+ finally:
+ allow_update.set()
+ promotion_result = await promotion
+ recovery_result = await recovery
+
+ assert json.loads(promotion_result)["ok"] is True
+ assert recovery_result == "reestablished"
+ assert persisted_generations == [0]
+ assert ctx.browser_session_continuity_generation == 1
+
+
+ "edit_source",
+ [
+ {},
+ {"expected_code": "old"},
+ {"replacement_code": "new"},
+ {
+ "expected_code": "old",
+ "replacement_code": "new",
+ "executed_source_reference": "browser_code_source:also-present",
+ },
+ ],
+)
+async def test_edit_block_and_run_requires_exactly_one_complete_edit_source(
+ edit_source: dict[str, str],
+) -> None:
+ ctx = make_copilot_context("workflow_definition:\n parameters: []\n blocks: []\n")
+ ctx.completion_verification_result = {"success": True, "reason": "stale"}
+ result = await edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps({"label": "repair_me", "block_labels": ["repair_me"], **edit_source}),
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["error_code"] == "invalid_edit_source"
+ assert ctx.completion_verification_result is None
+
+
+async def test_invalid_executed_source_reference_cannot_persist_or_start_a_run(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: repair_me
+ code: |
+ stale_helper()
+"""
+ persist = AsyncMock()
+ run_updated = AsyncMock()
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_workflow", persist)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._run_updated_workflow_blocks", run_updated)
+
+ source_ctx = make_copilot_context(workflow_yaml)
+ source_reference = browser_code_module.retain_executed_browser_code_source(
+ source_ctx,
+ "return {'ok': True}",
+ _cell(ok=True),
+ browser_session_id=source_ctx.browser_session_id,
+ browser_session_generation=0,
+ )
+ another_turn = make_copilot_context(workflow_yaml)
+ another_owner = make_copilot_context(workflow_yaml)
+ another_owner.organization_id = "other-owner"
+ wrong_generation = source_ctx
+ wrong_generation.browser_session_continuity_generation = 1
+ wrong_session = make_copilot_context(workflow_yaml)
+ wrong_session.browser_session_id = "pbs_original"
+ wrong_session_reference = browser_code_module.retain_executed_browser_code_source(
+ wrong_session,
+ "return {'ok': True}",
+ _cell(ok=True),
+ browser_session_id="pbs_original",
+ browser_session_generation=0,
+ )
+ wrong_session.browser_session_id = "pbs_replacement"
+ expired = make_copilot_context(workflow_yaml)
+ expired_reference = browser_code_module.retain_executed_browser_code_source(
+ expired,
+ "return {'ok': True}",
+ _cell(ok=True),
+ browser_session_id=expired.browser_session_id,
+ browser_session_generation=0,
+ )
+ browser_code_module.expire_executed_browser_code_sources(expired.browser_code_host)
+
+ cases = [
+ (make_copilot_context(workflow_yaml), "browser-code-source:not-present", "missing"),
+ (another_turn, source_reference, "wrong_turn"),
+ (another_owner, source_reference, "wrong_owner"),
+ (wrong_generation, source_reference, "wrong_generation"),
+ (wrong_session, wrong_session_reference, "wrong_session"),
+ (expired, expired_reference, "expired"),
+ ]
+ for ctx, reference, expected_status in cases:
+ # A credential skip left by an earlier call must not be reported as the reason this edit failed.
+ ctx.last_run_skipped_unbound_credentials = True
+ result = await edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps(
+ {
+ "label": "repair_me",
+ "executed_source_reference": reference,
+ "block_labels": ["repair_me"],
+ }
+ ),
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["error_code"] == "invalid_executed_source_reference"
+ assert parsed["reference_status"] == expected_status
+ assert ctx.last_run_skipped_unbound_credentials is False
+ persist.assert_not_awaited()
+ run_updated.assert_not_awaited()
+
+
+async def test_session_only_helpers_are_persisted_and_reported_by_the_saved_run(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: repair_me
+ code: |
+ stale_helper()
+"""
+ source = """async def candidate():
+ await tabs()
+ await switch_tab(0)
+ await click_and_wait_for_popup("#open")
+ await click_and_download("#download")
+ await files.write("note.txt", "hello")
+ await fill_credential("#password", "cred_1", "password")
+
+await candidate()
+"""
+ persist = AsyncMock(return_value={"ok": True, "data": {"block_count": 1}})
+ run_updated = AsyncMock(return_value=json.dumps({"ok": False, "error": "NameError: tabs is not defined"}))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_and_run_requires_skipped_run", lambda *_args: False)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._clear_pending_browser_interaction_observation", lambda *_args: None
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._get_prior_workflow_definition", AsyncMock(return_value=None))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_workflow", persist)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._record_workflow_update_result", lambda *_args: None)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._run_updated_workflow_blocks", run_updated)
+ ctx = make_copilot_context(workflow_yaml)
+ reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ source,
+ _cell(ok=True),
+ browser_session_id=ctx.browser_session_id,
+ browser_session_generation=0,
+ )
+
+ result = await edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps(
+ {
+ "label": "repair_me",
+ "executed_source_reference": reference,
+ "block_labels": ["repair_me"],
+ }
+ ),
+ )
+
+ parsed = json.loads(result)
+ assert parsed == {"ok": False, "error": "NameError: tabs is not defined"}
+ persisted_payload = persist.await_args.args[0]
+ assert stored_block_code(persisted_payload["workflow_yaml"], "repair_me") == source
+ run_updated.assert_awaited_once()
+
+
[email protected]("reference_is_valid", [True, False])
+async def test_update_and_run_blocks_fills_a_new_block_from_the_executed_source(
+ monkeypatch: pytest.MonkeyPatch,
+ reference_is_valid: bool,
+) -> None:
+ submitted_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: extract_rows
+ code: |
+"""
+ candidate = 'rows = {"WC-101": "Ironclad"}\nreturn rows'
+ ctx = make_copilot_context("workflow_definition:\n parameters: []\n blocks: []\n")
+ reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ candidate,
+ _cell(ok=True),
+ browser_session_id=ctx.browser_session_id,
+ browser_session_generation=0,
+ )
+ persisted: list[dict[str, Any]] = []
+
+ async def persist(payload: dict[str, Any], _context: object, **_kwargs: object) -> dict[str, object]:
+ persisted.append(payload)
+ return {"ok": True, "data": {"block_count": 1}}
+
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.await_pending_credential_pause", AsyncMock())
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._authority_tool_error", lambda *_args: None)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_and_run_requires_skipped_run", lambda *_args: False)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._clear_pending_browser_interaction_observation", lambda *_args: None
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._get_prior_workflow_definition", AsyncMock(return_value=None))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._update_workflow", persist)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._record_workflow_update_result", lambda *_args: None)
+ run_updated = AsyncMock(return_value=json.dumps({"ok": True, "data": {"workflow_run_id": "wr_saved"}}))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._run_updated_workflow_blocks", run_updated)
+
+ result = await update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": submitted_yaml,
+ "block_labels": ["extract_rows"],
+ "executed_source_references": {
+ "extract_rows": reference if reference_is_valid else "browser_code_source:not:a:real:one"
+ },
+ }
+ ),
+ )
+
+ if reference_is_valid:
+ assert json.loads(result)["ok"] is True
+ # Exact bytes, from the empty block scalar a model writes when told to leave the code empty.
+ assert stored_block_code(persisted[0]["workflow_yaml"], "extract_rows") == candidate
+ assert persisted[0]["_expected_exact_code_by_label"] == {"extract_rows": candidate}
+ run_updated.assert_awaited_once()
+ else:
+ assert json.loads(result)["error_code"] == "invalid_executed_source_reference"
+ assert persisted == []
+ run_updated.assert_not_awaited()
+
+
+def test_a_last_run_cell_reference_follows_that_run_not_the_chat_browser() -> None:
+ ctx = make_copilot_context()
+ ctx.browser_session_id = "pbs_debug"
+ ctx.browser_session_continuity_generation = 2
+ ctx.last_run_blocks_workflow_run_id = "wr_failed"
+ ctx.last_run_blocks_browser_session_id = "pbs_run"
+ reference = browser_code_module.retain_executed_browser_code_source(
+ ctx,
+ "return {'ok': True}",
+ _cell(ok=True),
+ browser_session_id="pbs_run",
+ browser_session_generation=0,
+ last_run_workflow_run_id="wr_failed",
+ )
+
+ assert browser_code_module.resolve_executed_browser_code_source(ctx, reference).status == "valid"
+
+ ctx.last_run_blocks_workflow_run_id = "wr_newer"
+ ctx.last_run_blocks_browser_session_id = "pbs_newer"
+ assert browser_code_module.resolve_executed_browser_code_source(ctx, reference).status == "wrong_session"
diff --git a/tests/unit/forge/sdk/copilot/test_organization_usage_tool.py b/tests/unit/forge/sdk/copilot/test_organization_usage_tool.py
new file mode 100644
index 000000000..03eacf7de
--- /dev/null
+++ b/tests/unit/forge/sdk/copilot/test_organization_usage_tool.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from skyvern.forge import app
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.copilot.output_utils import format_tool_result_for_user
+from skyvern.forge.sdk.copilot.tools import (
+ BROWSER_BOUND_TOOL_NAMES,
+ copilot_native_tools,
+ get_organization_usage_quota_tool,
+)
+from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
+from tests.unit.conftest import make_copilot_context
+
+TOOL_NAME = "get_organization_usage_quota"
+
+
+async def test_a_deployment_without_billing_reports_every_field_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(app, "AGENT_FUNCTION", AgentFunction())
+ ctx = make_copilot_context()
+
+ raw = await get_organization_usage_quota_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name=TOOL_NAME),
+ "{}",
+ )
+ payload = json.loads(raw)
+
+ assert payload["ok"] is True
+ data = payload["data"]
+ assert data["credits_note"]
+ assert data["billing_page_path"] is None
+ assert [value for key, value in data.items() if key != "credits_note"] == [None] * (len(data) - 1)
+ assert format_tool_result_for_user(TOOL_NAME, payload) == ""
+
+
+def test_the_tool_takes_no_arguments_and_needs_no_browser() -> None:
+ schema = get_organization_usage_quota_tool.params_json_schema
+
+ assert schema.get("properties", {}) == {}
+ assert schema.get("required", []) == []
+ assert schema["additionalProperties"] is False
+ assert TOOL_NAME not in BROWSER_BOUND_TOOL_NAMES
+
+
+# Frozen on purpose: the previous ordered catalog is the only thing that witnesses "the existing
+# tool surface is unchanged" when a sibling is dropped, renamed or reordered.
+CATALOG_WITHOUT_THIS_TOOL = [
+ "ask_user",
+ "set_work_plan",
+ "update_workflow",
+ "edit_block",
+ "edit_block_and_run",
+ "add_block",
+ "delete_block",
+ "list_credentials",
+ "list_integrations",
+ "run_blocks_and_collect_debug",
+ "test_workflow_from_blank_browser",
+ "get_run_results",
+ "update_and_run_blocks",
+ "discover_workflow_entrypoint",
+ "search_web",
+ "inspect_page_for_composition",
+ "inspect_locator_matches",
+ "fill_credential_field",
+ "request_credential",
+ "run_browser_code",
+]
+
+
[email protected]("supports_question_tool", [True, False])
[email protected]("browser_code_available", [True, False])
+def test_the_tool_joins_every_catalog_combination_without_displacing_one(
+ supports_question_tool: bool,
+ browser_code_available: bool,
+) -> None:
+ names = [
+ tool.name
+ for tool in copilot_native_tools(
+ supports_question_tool=supports_question_tool,
+ browser_code_available=browser_code_available,
+ )
+ ]
+
+ assert names.count(TOOL_NAME) == 1
+ expected = [
+ name
+ for name in CATALOG_WITHOUT_THIS_TOOL
+ if (name != "ask_user" or supports_question_tool) and (name != "run_browser_code" or browser_code_available)
+ ]
+ assert [name for name in names if name != TOOL_NAME] == expected
+
+
+async def test_a_self_heal_turn_cannot_read_account_usage(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(app, "AGENT_FUNCTION", AgentFunction())
+ ctx = make_copilot_context()
+ ctx.turn_origin = TurnOrigin.runtime_self_heal
+
+ payload = json.loads(
+ await get_organization_usage_quota_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name=TOOL_NAME),
+ "{}",
+ )
+ )
+
+ assert payload["ok"] is False
+ assert payload["error"]
diff --git a/tests/unit/google/test_otp_service_gmail.py b/tests/unit/google/test_otp_service_gmail.py
index 8ef3f236a..5dbc5c872 100644
--- a/tests/unit/google/test_otp_service_gmail.py
+++ b/tests/unit/google/test_otp_service_gmail.py
@@ -523,3 +523,216 @@ async def test_get_otp_value_from_email_throttles_gmail_searches_within_polling_
get_credentials.assert_awaited_once()
search_messages.assert_awaited_once()
assert all(log.get("event") != "Unexpected email OTP lookup failure" for log in logs)
+
+
+async def test_failed_gmail_search_is_recorded_then_cleared_by_a_successful_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(id="goac_1", scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES))
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[credential]))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ search_messages = AsyncMock(
+ side_effect=[google_gmail_service.GmailAPIError(status=503, code=None, message="unavailable"), []]
+ )
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", search_messages)
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
+
+ context = EmailOTPVerificationContext()
+ source_context = context.for_source(otp_email.GmailOTPSource.name)
+
+ assert (
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ is None
+ )
+ assert source_context.failed_credential_ids == {"goac_1"}
+
+ source_context.last_searched_at_by_credential.clear()
+ assert (
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ is None
+ )
+ assert source_context.failed_credential_ids == set()
+ assert source_context.completed_credential_ids == {"goac_1"}
+
+
+async def test_refreshed_credential_list_drops_a_failure_for_a_disconnected_inbox(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(id="goac_current", scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES))
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[credential]))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", AsyncMock(return_value=[]))
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
+
+ context = EmailOTPVerificationContext()
+ source_context = context.for_source(otp_email.GmailOTPSource.name)
+ source_context.failed_credential_ids.add("goac_disconnected")
+
+ assert (
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ is None
+ )
+
+ assert source_context.credential_ids == ["goac_current"]
+ assert source_context.failed_credential_ids == set()
+
+
+async def test_unparseable_gmail_candidate_is_counted_without_being_marked_seen(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(id="goac_1", scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES))
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[credential]))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ candidate = google_gmail_service.GmailMessageCandidate(
+ message_id="msg_unreadable",
+ content="Your verification code is 123456",
+ internal_date=datetime.now(timezone.utc),
+ )
+ monkeypatch.setattr(
+ otp_email.google_gmail_service, "search_recent_otp_messages", AsyncMock(return_value=[candidate])
+ )
+ monkeypatch.setattr(otp_service, "parse_otp_login", AsyncMock(side_effect=RuntimeError("parser down")))
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
+
+ context = EmailOTPVerificationContext()
+ source_context = context.for_source(otp_email.GmailOTPSource.name)
+
+ assert (
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ is None
+ )
+
+ assert source_context.unreadable_message_keys == {("goac_1", "msg_unreadable")}
+ assert not source_context.has_seen_message("goac_1", "msg_unreadable")
+
+
+async def test_unusable_gmail_token_counts_as_a_failed_search(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(id="goac_1", scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES))
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[credential]))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=None))
+ search_messages = AsyncMock(return_value=[])
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", search_messages)
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
+
+ context = EmailOTPVerificationContext()
+ source_context = context.for_source(otp_email.GmailOTPSource.name)
+
+ assert (
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ is None
+ )
+
+ search_messages.assert_not_awaited()
+ assert source_context.failed_credential_ids == {"goac_1"}
+ assert source_context.completed_credential_ids == set()
+
+
+async def test_parse_cancelled_by_the_budget_still_marks_the_message_it_reached(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import asyncio
+
+ agent = AgentFunction()
+ credential = SimpleNamespace(id="goac_1", scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES))
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[credential]))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ candidate = google_gmail_service.GmailMessageCandidate(
+ message_id="msg_in_flight",
+ content="Your verification code is 123456",
+ internal_date=datetime.now(timezone.utc),
+ )
+ monkeypatch.setattr(
+ otp_email.google_gmail_service, "search_recent_otp_messages", AsyncMock(return_value=[candidate])
+ )
+ monkeypatch.setattr(otp_service, "parse_otp_login", AsyncMock(side_effect=asyncio.CancelledError()))
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
+
+ context = EmailOTPVerificationContext()
+ source_context = context.for_source(otp_email.GmailOTPSource.name)
+
+ with pytest.raises(asyncio.CancelledError):
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+
+ assert source_context.unreadable_message_keys == {("goac_1", "msg_in_flight")}
+ assert not source_context.has_seen_message("goac_1", "msg_in_flight")
+
+
+async def test_a_credential_list_refresh_that_never_returns_leaves_the_list_marked_stale(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import asyncio
+
+ agent = AgentFunction()
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
+
+ context = EmailOTPVerificationContext()
+ source_context = context.for_source(otp_email.GmailOTPSource.name)
+ source_context.credential_ids = []
+ source_context.credential_ids_loaded_at = datetime(2020, 1, 1, tzinfo=timezone.utc)
+
+ monkeypatch.setattr(
+ otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(side_effect=asyncio.CancelledError())
+ )
+ with pytest.raises(asyncio.CancelledError):
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ assert source_context.credential_list_refresh_failed is True
+
+ credential = SimpleNamespace(id="goac_1", scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES))
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[credential]))
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", AsyncMock(return_value=[]))
+ assert (
+ await agent.get_otp_value_from_email(
+ organization_id="org_1", totp_identifier="[email protected]", context=context
+ )
+ is None
+ )
+ assert source_context.credential_list_refresh_failed is False
diff --git a/tests/unit/microsoft/test_otp_service_outlook.py b/tests/unit/microsoft/test_otp_service_outlook.py
index ab9f4269a..aadfea0bb 100644
--- a/tests/unit/microsoft/test_otp_service_outlook.py
+++ b/tests/unit/microsoft/test_otp_service_outlook.py
@@ -100,8 +100,17 @@ async def test_outlook_source_uses_mail_read_credential_and_persists_candidate(
tokenless = _agent(monkeypatch, [SimpleNamespace(id="without_token", scopes_granted=["Mail.Read"])])
monkeypatch.setattr(tokenless, "get_microsoft_credentials", AsyncMock(return_value=None))
search.reset_mock()
- assert await tokenless.get_otp_value_from_email(organization_id="org", totp_identifier="[email protected]") is None
+ tokenless_context = otp_email.EmailOTPVerificationContext()
+ assert (
+ await tokenless.get_otp_value_from_email(
+ organization_id="org", totp_identifier="[email protected]", context=tokenless_context
+ )
+ is None
+ )
search.assert_not_awaited()
+ tokenless_source = tokenless_context.for_source(otp_email.OutlookOTPSource.name)
+ assert tokenless_source.failed_credential_ids == {"without_token"}
+ assert tokenless_source.completed_credential_ids == set()
@pytest.mark.asyncio
diff --git a/tests/unit/test_actions.py b/tests/unit/test_actions.py
index a7eccfea6..0f0978f15 100644
--- a/tests/unit/test_actions.py
+++ b/tests/unit/test_actions.py
@@ -331,8 +331,8 @@ def test_action_log_payload_keeps_non_otp_input_debuggable() -> None:
@pytest.mark.asyncio
-async def test_create_action_redacts_response_but_preserves_action_json_for_hydration() -> None:
- secret_value = "OTP_SECRET_VALUE_SHOULD_NOT_APPEAR"
+async def test_create_action_persists_the_typed_otp_code_on_the_response_column() -> None:
+ otp_code = "OTP_CODE_THE_CUSTOMER_MUST_SEE"
started_at = datetime(2026, 7, 30, 12, 0, 0)
finished_at = datetime(2026, 7, 30, 12, 0, 1)
captured_models = []
@@ -363,9 +363,9 @@ async def test_create_action_redacts_response_but_preserves_action_json_for_hydr
step_order=0,
action_order=0,
element_id="otp-field",
- text=secret_value,
+ text=otp_code,
intention="Enter verification code",
- response=secret_value,
+ response=otp_code,
totp_code_required=True,
started_at=started_at,
finished_at=finished_at,
@@ -374,16 +374,16 @@ async def test_create_action_redacts_response_but_preserves_action_json_for_hydr
await repo.create_action(action)
persisted_model = captured_models[0]
- assert persisted_model.response == REDACTED_OTP_VALUE
- assert persisted_model.action_json["text"] == secret_value
- assert persisted_model.action_json["response"] == secret_value
+ assert persisted_model.response == otp_code
+ assert persisted_model.action_json["text"] == otp_code
+ assert persisted_model.action_json["response"] == otp_code
assert persisted_model.started_at == started_at
assert persisted_model.finished_at == finished_at
hydrated_action = hydrate_action(persisted_model)
assert isinstance(hydrated_action, InputTextAction)
- assert hydrated_action.text == secret_value
- assert hydrated_action.response == secret_value
+ assert hydrated_action.text == otp_code
+ assert hydrated_action.response == otp_code
assert hydrated_action.model_dump(mode="json")["started_at"] == "2026-07-30T12:00:00"
assert hydrated_action.model_dump(mode="json")["finished_at"] == "2026-07-30T12:00:01"
diff --git a/tests/unit/test_agent_cleanup_download_suffix.py b/tests/unit/test_agent_cleanup_download_suffix.py
index 5ae739d8b..a16bdce70 100644
--- a/tests/unit/test_agent_cleanup_download_suffix.py
+++ b/tests/unit/test_agent_cleanup_download_suffix.py
@@ -15,6 +15,7 @@ from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.api.files import check_downloading_files_and_wait_for_download_to_complete
from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.models import StepStatus
from skyvern.schemas.runs import RunEngine
from skyvern.webeye.actions.models import DetailedAgentStepOutput
from tests.unit._fingerprint_expectations import expected_fingerprint
@@ -1618,6 +1619,106 @@ async def test_execute_step_complete_on_download_closes_claimed_popup_before_han
assert update_task_indices and all(close_i < i for i in update_task_indices)
+async def test_execute_step_no_credit_releases_deferred_dispatched_failure_reservation(tmp_path) -> None:
+ """Point-(a) wiring on the real execute_step path: when the complete_on_download seam finds NO durable
+ credit, a dispatched-then-failed action's deferred reservation is released at the step boundary --
+ before the retry scrape -- restoring generic blank-page recovery. Removing the execute_step apply-call
+ leaves the marker wedged and blocks #17139 recovery."""
+ agent = ForgeAgent()
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+
+ task = _make_task(task_id="task-no-credit")
+ task.status = SimpleNamespace(value="running")
+ task.navigation_goal = "Download invoice"
+ task.data_extraction_goal = None
+ task.complete_criterion = None
+ task.terminate_criterion = None
+ task.browser_address = None
+ task.max_steps_per_run = None
+ task.url = "https://example.com"
+ task.proxy_location = None
+ task.llm_key = None
+ task.task_type = "general"
+
+ step = MagicMock()
+ step.step_id = "step-1"
+ step.order = 0
+ step.retry_index = 0
+ step.status = StepStatus.failed
+
+ organization = MagicMock()
+ organization.organization_id = task.organization_id
+ organization.max_steps_per_run = None
+
+ task_block = MagicMock()
+ task_block.complete_on_download = True
+ task_block.download_timeout = None
+ task_block.download_suffix = "req-123"
+
+ marker = _claimed_popup(":")
+ browser_state = MagicMock()
+ browser_state.browser_context = _RUN_CONTEXT
+ browser_state.get_working_page = AsyncMock(return_value=None)
+
+ ctx = SkyvernContext(task_id=task.task_id)
+ ctx.record_download_popup_claim(task.task_id, marker)
+ # A prior dispatched-then-failed action deferred its release to this step's credit seam.
+ ctx.stash_pending_download_reservation_release(task.task_id, ((), ()))
+
+ async def agent_step_side_effect(*args, **kwargs):
+ # No download file lands: the complete_on_download seam finds no credit.
+ return step, DetailedAgentStepOutput(
+ scraped_page=None,
+ extract_action_prompt=None,
+ llm_response=None,
+ actions=None,
+ action_results=None,
+ actions_and_results=None,
+ cua_response=None,
+ )
+
+ with (
+ patch("skyvern.forge.agent.analytics.capture"),
+ patch("skyvern.forge.agent.skyvern_context.ensure_context", return_value=ctx),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=[]),
+ patch("skyvern.forge.agent.app") as mock_app,
+ patch.object(agent, "initialize_execution_state", AsyncMock(return_value=(step, browser_state, None))),
+ patch.object(agent, "agent_step", AsyncMock(side_effect=agent_step_side_effect)),
+ patch.object(agent, "update_step", AsyncMock(side_effect=lambda s, *a, **k: s)),
+ patch.object(agent, "update_task_errors_from_detailed_output", AsyncMock(return_value=task)),
+ patch.object(agent, "handle_failed_step", AsyncMock(return_value=None)),
+ patch.object(agent, "clean_up_task", AsyncMock()),
+ ):
+ mock_app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=None)
+ mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=task)
+ mock_app.DATABASE.tasks.update_task = AsyncMock(return_value=task)
+ mock_app.AGENT_FUNCTION.validate_step_execution = AsyncMock()
+ mock_app.AGENT_FUNCTION.post_step_execution = AsyncMock()
+ mock_app.ARTIFACT_MANAGER.flush_step_archive = AsyncMock()
+ mock_app.BROWSER_MANAGER.get_for_task = MagicMock(return_value=None)
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[])
+
+ await agent.execute_step(
+ organization=organization,
+ task=task,
+ step=step,
+ task_block=task_block,
+ close_browser_on_completion=True,
+ complete_verification=True,
+ engine=RunEngine.skyvern_v1,
+ )
+
+ # No credit -> the deferred release fired at the step seam: the marker is freed for blank recovery,
+ # not closed, and the pending release is consumed.
+ assert not ctx.has_download_popup_claim(task.task_id, marker)
+ assert task.task_id not in ctx.pending_download_reservation_release
+ marker.close.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_clean_up_task_closes_claimed_popup_on_cleanup_finalization_credit(tmp_path) -> None:
"""Second durable-credit seam: when the ``download_suffix``/``list_files_before`` finalization inside
diff --git a/tests/unit/test_agent_step_characterization.py b/tests/unit/test_agent_step_characterization.py
index f94d23b82..a3ab5cd2c 100644
--- a/tests/unit/test_agent_step_characterization.py
+++ b/tests/unit/test_agent_step_characterization.py
@@ -10,7 +10,7 @@ from zoneinfo import ZoneInfo
import pytest
-from skyvern.exceptions import NoTOTPVerificationCodeFound
+from skyvern.exceptions import NoTOTPVerificationCodeFound, ScrapingFailedBlankPage
from skyvern.forge import app
from skyvern.forge.agent import ForgeAgent, StepPromptResult
from skyvern.forge.sdk.core import skyvern_context
@@ -235,6 +235,25 @@ async def test_no_generated_actions_marks_step_failed(monkeypatch: pytest.Monkey
assert output.actions == []
+async def test_credited_dead_blank_recovery_persists_completed_not_failed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Full path: a dead-blank scrape whose credited grace returns [] must NOT persist the step as
+ failed at the zero-action seam. execute_step's single complete-on-download seam owns the finalize
+ and task completion, so agent_step returns a completed step (no failed terminal step/metrics)."""
+ rig = make_agent_step_rig(monkeypatch)
+ rig.agent.build_and_record_step_prompt = AsyncMock(side_effect=ScrapingFailedBlankPage())
+ rig.agent._empty_page_recovery_plan = AsyncMock(return_value=[]) # credited complete-on-download
+
+ step, output = await rig.run(task_block=FileDownloadBlock.model_construct(label="dl", complete_on_download=True))
+
+ assert step.status == StepStatus.completed
+ assert StepStatus.failed not in rig.update_statuses
+ assert rig.action_handler.await_count == 0
+ assert output.actions == []
+
+
@pytest.mark.asyncio
async def test_totp_polling_timeout_produces_terminate_action(monkeypatch: pytest.MonkeyPatch) -> None:
rig = make_agent_step_rig(monkeypatch, task_overrides={"totp_identifier": "[email protected]"})
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index d25d58f56..6bf2c75ea 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -5231,33 +5231,78 @@ async def test_execute_task_v3_persisted_final_url_is_stripped_to_bare(monkeypat
@pytest.mark.asyncio
-async def test_execute_task_v3_floors_runtime_secrets_when_redaction_disabled(
+async def test_execute_task_v3_row_keeps_the_typed_code_and_still_floors_a_model_hidden_link(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from skyvern.forge import agent as agent_mod
- # Org opted out of artifact redaction — runtime-resolved secrets (e.g. a verification code)
- # must still be floored out of the persisted turn text.
+ # The one-time code the run typed is a record the customer reads back off the row. A sign-in link
+ # registered as model-hidden is a signed URL, so it is still floored out of the same turn text.
monkeypatch.setattr(
"skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled", lambda *_a, **_k: False
)
- monkeypatch.setattr(
- "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts",
- lambda *_a, **_k: {"73914268"},
- )
+ sign_in_link = "https://example.test/magic?token=ZQ3F8K2N7PLM4RTY"
outcome = LoopOutcome(status="completed", reason="done", billable_actions=["type"])
_step, task, _loop, _post = await _run_execute_task_v3(
monkeypatch,
outcome,
action_rounds=[[RoundAction("type", {"selector": "#otp", "text": "73914268"}, True, billable=True)]],
- action_round_texts=["typing the verification code 73914268 into the field"],
+ action_round_texts=[f"typing the verification code 73914268 from {sign_in_link}"],
+ context_overrides={
+ "runtime_secret_values": {"73914268", sign_in_link},
+ "model_hidden_values": {sign_in_link},
+ },
data_extraction_goal=None,
extracted_information_schema=None,
)
assert task.status == TaskStatus.completed
# The type action's own row, not the terminal decision row appended after it.
persisted = agent_mod.app.DATABASE.workflow_params.create_action.await_args_list[0].kwargs["action"]
- assert "73914268" not in (persisted.reasoning or "")
+ assert persisted.text == "73914268"
+ assert "73914268" in (persisted.reasoning or "")
+ assert sign_in_link not in (persisted.reasoning or "")
+ assert REDACTED_SECRET_PLACEHOLDER in (persisted.reasoning or "")
+
+
+async def test_execute_task_v3_row_scrubs_the_run_password_but_keeps_the_runtime_otp_code(
+ monkeypatch: pytest.MonkeyPatch,
+ workflow_context_manager_factory: Callable[..., Any],
+) -> None:
+ from skyvern.forge import agent as agent_mod
+
+ # Against the real context manager, not a lambda: the run's registered password still leaves the
+ # row, and the one-time code the same manager registered stays on it.
+ password = "hunter2-correct-horse"
+ otp_code = "73914268"
+ manager = workflow_context_manager_factory(
+ workflow_run_id="wr_otp_row",
+ secrets={"secret_pw": password},
+ runtime_otp_values={otp_code},
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled",
+ manager.artifact_redaction_enabled,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run",
+ manager.get_secret_values_for_run,
+ )
+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=["type"])
+ _step, task, _loop, _post = await _run_execute_task_v3(
+ monkeypatch,
+ outcome,
+ workflow_run_id="wr_otp_row",
+ action_rounds=[[RoundAction("type", {"selector": "#otp", "text": otp_code}, True, billable=True)]],
+ action_round_texts=[f"typing {otp_code} after signing in with {password}"],
+ data_extraction_goal=None,
+ extracted_information_schema=None,
+ )
+ assert task.status == TaskStatus.completed
+ persisted = agent_mod.app.DATABASE.workflow_params.create_action.await_args_list[0].kwargs["action"]
+ assert persisted.text == otp_code
+ assert otp_code in (persisted.reasoning or "")
+ assert password not in (persisted.reasoning or "")
assert REDACTED_SECRET_PLACEHOLDER in (persisted.reasoning or "")
diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.py
index 2c357ad23..66d4b7632 100644
--- a/tests/unit/test_background_task_executor.py
+++ b/tests/unit/test_background_task_executor.py
@@ -2773,6 +2773,105 @@ async def test_scheduled_run_cannot_clobber_the_callers_context() -> None:
assert child_context[0].organization_id == "org_1"
+async def test_scheduled_run_gets_independent_download_popup_registries() -> None:
+ """A fire-and-forget run copied via ``replace(parent)`` must own EMPTY, independent download-popup
+ lifecycle registries. Otherwise the shallow copy aliases the parent's dicts, so a reset/cleanup on
+ either context destructively detaches the other live run's listeners and clears its reservations."""
+
+ class _FakeBrowserContext:
+ def __init__(self) -> None:
+ self.callbacks: list[Any] = []
+
+ def on(self, event: str, cb: Any) -> None:
+ if event == "page":
+ self.callbacks.append(cb)
+
+ def remove_listener(self, event: str, cb: Any) -> None:
+ if event == "page" and cb in self.callbacks:
+ self.callbacks.remove(cb)
+
+ parent = SkyvernContext(organization_id="org_1", task_id="tsk_parent")
+ parent_browser_context = _FakeBrowserContext()
+ parent_page = object()
+ parent.arm_download_popup_context_listener("tsk_parent", parent_browser_context, lambda page: None)
+ parent.record_download_popup_claim(
+ "tsk_parent",
+ parent_page,
+ baseline_files=["/d/parent.pdf"],
+ session_observed=True,
+ session_baseline_files=["s3://b/parent-session.pdf"],
+ )
+ parent.record_download_popup_late_candidate("tsk_parent", object())
+ parent.stash_pending_download_reservation_release("tsk_parent", ((parent_page,), ()))
+ parent_sibling = object()
+ parent.mark_download_popup_claim_delta_siblings("tsk_parent", [parent_page, parent_sibling])
+ parent.anchor_download_popup_recovery_grace("tsk_parent", parent_page, 0.0)
+
+ child_holder: list[SkyvernContext] = []
+
+ async def work() -> None:
+ child = skyvern_context.current()
+ assert child is not None
+ child_holder.append(child)
+
+ # Assert inside the scope: scoped()'s exit runs _cleanup_outgoing_context on the parent.
+ with skyvern_context.scoped(parent):
+ BackgroundTaskExecutor()._schedule(None, work)
+ for _ in range(100):
+ if child_holder:
+ break
+ await asyncio.sleep(0)
+
+ assert child_holder, "the scheduled child run never executed"
+ child = child_holder[0]
+ assert child is not parent
+
+ # All PR-owned popup lifecycle registries (incl. the recovery-grace anchor) are independent
+ # objects, empty in the child. The parent recorded a claim and anchored recovery grace.
+ assert parent.download_popup_recovery_grace_started_at, "parent should hold a recovery-grace anchor"
+ assert parent.download_popup_claim_baseline, "parent should hold a claim baseline snapshot"
+ assert parent.download_popup_claim_session_observed, "parent should hold a session-observed flag"
+ assert parent.download_popup_claim_session_baseline, "parent should hold a session baseline"
+ assert parent.download_popup_claim_delta_siblings, "parent should hold sibling markers"
+ for attr in (
+ "download_popup_claims",
+ "download_popup_context_listeners",
+ "download_popup_late_candidates",
+ "pending_download_reservation_release",
+ "download_popup_recovery_grace_started_at",
+ "download_popup_claim_baseline",
+ "download_popup_claim_session_observed",
+ "download_popup_claim_session_baseline",
+ "download_popup_claim_delta_siblings",
+ ):
+ assert getattr(child, attr) is not getattr(parent, attr), f"{attr} must not alias the parent's dict"
+ assert getattr(child, attr) == {}, f"{attr} must be empty in the copied child"
+
+ # Mutating the child's own sibling markers must not bleed into the parent's (would fail if the
+ # child aliased the parent's dict for lack of an independent reset).
+ child.mark_download_popup_claim_delta_siblings("tsk_child_sib", [object()])
+ assert "tsk_parent" in parent.download_popup_claim_delta_siblings, "child mutation dropped parent's marker"
+ assert "tsk_child_sib" not in parent.download_popup_claim_delta_siblings, "child marker leaked to the parent"
+
+ # A destructive teardown on the child must leave the parent's live ownership state untouched.
+ child.detach_all_download_popup_context_listeners()
+ assert parent.has_download_popup_claim("tsk_parent", parent_page), "child teardown cleared the parent's claim"
+ assert parent_browser_context.callbacks, "child teardown detached the parent's live listener"
+ assert "tsk_parent" in parent.pending_download_reservation_release, "child teardown cleared parent's pending"
+ assert parent.download_popup_recovery_grace_started_at, "child teardown cleared the parent's recovery anchor"
+ assert parent.download_popup_claim_baseline, "child teardown cleared the parent's claim baseline"
+ assert parent.download_popup_claim_session_observed, "child teardown cleared the parent's session flag"
+ assert parent.download_popup_claim_session_baseline, "child teardown cleared the parent's session baseline"
+ assert parent.download_popup_claim_delta_siblings, "child teardown cleared the parent's sibling markers"
+
+ # ...and the symmetric direction: a parent teardown must not touch the child's own state.
+ child_page = object()
+ child.record_download_popup_claim("tsk_child", child_page)
+ parent.detach_all_download_popup_context_listeners()
+ assert child.has_download_popup_claim("tsk_child", child_page), "parent teardown cleared the child's claim"
+
+
@pytest.mark.asyncio
async def test_execute_workflow_stamps_org_llm_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
organization = SimpleNamespace(
diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.py
index 84434cb3c..8e0943506 100644
--- a/tests/unit/test_browser_effect_sink_enumeration.py
+++ b/tests/unit/test_browser_effect_sink_enumeration.py
@@ -50,6 +50,8 @@ _DISCOVERED_BROWSER_API_CALLS = {
"skyvern/webeye/actions/handler_utils.py": Counter(
{"dispatch_event": 1, "down": 3, "evaluate": 1, "fill": 3, "press": 1, "up": 3}
),
+ # The stale-iframe id read routes through the common SkyvernFrame.evaluate abstraction.
+ "skyvern/webeye/actions/multi_field_totp.py": Counter({"evaluate": 1}),
"skyvern/webeye/dialog_handler.py": Counter({"accept": 3, "dismiss": 1}),
"skyvern/webeye/dom_inspection.py": Counter({"evaluate": 6}),
"skyvern/webeye/utils/dom.py": Counter(
@@ -83,6 +85,8 @@ _EVALUATE_CALLERS = {
# rendering as settled (SKY-14657).
"skyvern/forge/agent.py": Counter({"_page_fingerprint": 2, "_page_probe": 1}),
"skyvern/webeye/actions/handler_utils.py": Counter({"_uses_native_value_set_fill": 1}),
+ # The stale-iframe id read routes through the common SkyvernFrame.evaluate abstraction.
+ "skyvern/webeye/actions/multi_field_totp.py": Counter({"_multi_field_totp_frame_gone": 1}),
"skyvern/webeye/actions/handler.py": Counter(
{
"_blob_iframe_src_titles": 1,
@@ -227,21 +231,21 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:
}
assert observed == _DISCOVERED_BROWSER_API_CALLS
- assert sum(sum(methods.values()) for methods in observed.values()) == 173
+ assert sum(sum(methods.values()) for methods in observed.values()) == 174
handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)
classified_non_browser = Counter(
{signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES}
)
assert classified_non_browser == _NON_BROWSER_CANDIDATES
assert sum(_NON_BROWSER_CANDIDATES.values()) == 7
- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 166
+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 167
def test_every_raw_evaluate_call_is_classified() -> None:
observed = {path: callers for path in _owned_source_paths() if (callers := _callers_for_method(path, "evaluate"))}
assert observed == _EVALUATE_CALLERS
- assert sum(sum(callers.values()) for callers in observed.values()) == 31
+ assert sum(sum(callers.values()) for callers in observed.values()) == 32
def test_every_cdp_dispatch_is_classified_by_exact_command() -> None:
diff --git a/tests/unit/test_code_block_authorized_files.py b/tests/unit/test_code_block_authorized_files.py
index 49c0dca72..2e7eab1fd 100644
--- a/tests/unit/test_code_block_authorized_files.py
+++ b/tests/unit/test_code_block_authorized_files.py
@@ -1,24 +1,50 @@
from __future__ import annotations
+import asyncio
+import hashlib
import os
+import time
+from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
+from contextlib import asynccontextmanager, suppress
from dataclasses import replace
from datetime import UTC, datetime
from pathlib import Path
+from types import MappingProxyType, SimpleNamespace
+from typing import Any, TypedDict
+from unittest.mock import AsyncMock, MagicMock
import pytest
+from playwright.async_api import Download
+from structlog.testing import capture_logs
from skyvern.config import settings
+from skyvern.forge import app
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage import base as storage_base_module
+from skyvern.forge.sdk.artifact.storage import local as local_storage_module
+from skyvern.forge.sdk.artifact.storage.local import LocalStorage
+from skyvern.forge.sdk.schemas.files import FileInfo
+from skyvern.forge.sdk.workflow import code_block_authorized_files
from skyvern.forge.sdk.workflow.code_block_authorized_files import (
AuthorizedFileAccessError,
AuthorizedFileMaterializationFailure,
+ BlockDownloadLog,
+ RegisteredDownloadIdentity,
+ RegisteredDownloadSource,
bind_inline_attach_authorized_file,
capture_authorized_file,
+ capture_claimed_download,
read_authorized_file,
)
-from skyvern.forge.sdk.workflow.models.block import CodeBlock
+from skyvern.forge.sdk.workflow.models.block import CodeBlock, _registered_download_source
from skyvern.forge.sdk.workflow.models.code_block_recorder import RecordingPage
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
from skyvern.webeye.actions.action_types import ActionType
+from skyvern.webeye.browser_artifacts import DownloadBinding
+from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptor
+from tests.unit.conftest import SESSION_DOWNLOAD_BYTES as _SESSION_BYTES
+from tests.unit.conftest import make_claimed_download_mock
+from tests.unit.conftest import registered_download_row as _registered_row
@pytest.fixture
@@ -265,6 +291,108 @@ async def test_rebinding_page_locator_after_bind_cannot_capture_the_file_bytes(a
assert page.attached[0][1]["buffer"] == b"retained authorized bytes"
+async def test_inline_helper_accepts_a_claimed_download_but_not_its_path_or_a_lookalike(
+ authorized_file, tmp_path: Path
+) -> None:
+ """A download this run claimed is a handle; the worker path it happens to sit at stays refused."""
+ path, materialized = authorized_file
+ run_dir = path.parent
+ outside = tmp_path / "elsewhere.pdf"
+ outside.write_bytes(b"not this run")
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {"resume": materialized},
+ {"resume": str(path)},
+ download_root=path.parents[1],
+ workflow_run_id="wr_authorized",
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ delivered = run_dir / "1f0c9b2e-4a7d-guid"
+ delivered.write_bytes(b"certificate bytes")
+
+ receipt = await attach(
+ page,
+ started(make_claimed_download_mock(path=delivered, suggested_filename="../Vendor Certificate.pdf")),
+ "#file",
+ )
+
+ assert receipt == {"filename": "Vendor Certificate.pdf", "size": len(b"certificate bytes")}
+ assert page.attached == [("#file", page.attached[0][1])]
+ assert page.attached[0][1]["name"] == "Vendor Certificate.pdf"
+ assert page.attached[0][1]["buffer"] == b"certificate bytes"
+
+ class LooksLikeADownload:
+ suggested_filename = "certificate.pdf"
+
+ async def path(self) -> str:
+ return str(delivered)
+
+ with pytest.raises(AuthorizedFileAccessError, match="accepts only a materialized file"):
+ await attach(page, str(delivered), "#file")
+ with pytest.raises(AuthorizedFileAccessError, match="accepts only a materialized file"):
+ await attach(page, LooksLikeADownload(), "#file") # type: ignore[arg-type]
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(
+ page, started(make_claimed_download_mock(path=outside, suggested_filename="elsewhere.pdf")), "#file"
+ )
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, started(make_claimed_download_mock(path=None, suggested_filename="cancelled.pdf")), "#file")
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(
+ page,
+ started(
+ make_claimed_download_mock(
+ path=delivered, suggested_filename="x.pdf", path_error=RuntimeError("cancelled")
+ )
+ ),
+ "#file",
+ )
+ assert len(page.attached) == 1
+
+
+async def test_a_claimed_download_is_contained_by_the_directory_the_run_downloads_into(tmp_path: Path) -> None:
+ """A run whose downloads land under its own download id must be read there, and only there."""
+ root = tmp_path / "downloads"
+ download_dir = root / "dl_run"
+ download_dir.mkdir(parents=True)
+ workflow_dir = root / "wr_workflow"
+ workflow_dir.mkdir()
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=root,
+ workflow_run_id="wr_workflow",
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_run_id="dl_run",
+ download_log=log,
+ )
+ delivered = download_dir / "guid-file"
+ delivered.write_bytes(b"claimed bytes")
+ neighbor = workflow_dir / "guid-file"
+ neighbor.write_bytes(b"another run's bytes")
+
+ receipt = await attach(
+ page, started(make_claimed_download_mock(path=delivered, suggested_filename="certificate.pdf")), "#file"
+ )
+
+ assert receipt == {"filename": "certificate.pdf", "size": len(b"claimed bytes")}
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(
+ page, started(make_claimed_download_mock(path=neighbor, suggested_filename="certificate.pdf")), "#file"
+ )
+ assert len(page.attached) == 1
+
+
class _RawLocator:
def __init__(self, page: _RawPage, selector: str) -> None:
self.page, self._selector = page, selector
@@ -355,3 +483,1126 @@ def test_an_oversized_file_is_materialized_but_its_capability_is_refused_on_size
organization_id="org_authorized",
max_bytes=4,
)
+
+
+@asynccontextmanager
+async def _quiet_settle() -> AsyncIterator[None]:
+ yield
+
+
+class _SettlingInterceptor:
+ """Stands in for the interceptor whose drain finishes writing the file the claim is about."""
+
+ def __init__(self, target: Path, payload: bytes) -> None:
+ self._target, self._payload = target, payload
+
+ @asynccontextmanager
+ async def settle_browser_downloads(self) -> AsyncIterator[None]:
+ self._target.write_bytes(self._payload)
+ yield
+
+
+def _context_with(interceptor: object) -> SimpleNamespace:
+ return SimpleNamespace(_skyvern_cdp_download_interceptor=interceptor)
+
+
+def _browser_download_log() -> tuple[BlockDownloadLog, Callable[[Any], Any]]:
+ """A log over a fake tab, and a hook that emits a download on it the way the browser does."""
+ tab = _EventSource()
+ log = BlockDownloadLog(_EventContext(tab))
+
+ def started(download: Any) -> Any:
+ tab.emit("download", download)
+ return download
+
+ return log, started
+
+
+def _bind_claimed_download_attach(page: _FakePage, run_dir: Path) -> Callable[..., Awaitable[dict[str, str | int]]]:
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+
+ async def attach_started(target: Any, file: Any, selector: str) -> dict[str, str | int]:
+ return await attach(target, started(file), selector)
+
+ return attach_started
+
+
+async def test_a_claimed_download_is_found_where_the_browser_settled_it(tmp_path: Path) -> None:
+ """Production binds downloads with setDownloadBehavior, so Chrome writes the suggested name into the
+ run directory itself and Playwright's own path points at a launch-directory guid that never exists."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ settled = run_dir / "vendor-certificate.pdf"
+ settled.write_bytes(b"settled certificate bytes")
+
+ absent_guid = await attach(
+ page,
+ make_claimed_download_mock(
+ path=tmp_path / "launch-dir" / "1f0c9b2e-4a7d-guid",
+ suggested_filename="vendor-certificate.pdf",
+ ),
+ "#file",
+ )
+ no_path = await attach(
+ page,
+ make_claimed_download_mock(path=None, suggested_filename="vendor-certificate.pdf"),
+ "#file",
+ )
+
+ assert absent_guid == no_path == {"filename": settled.name, "size": len(b"settled certificate bytes")}
+ assert [files["buffer"] for _, files in page.attached] == [b"settled certificate bytes"] * 2
+ assert [files["name"] for _, files in page.attached] == [settled.name] * 2
+
+
+async def test_a_claimed_download_is_captured_once_the_interceptor_drain_has_written_it(tmp_path: Path) -> None:
+ """The file can still be in flight when the block claims it; the capture settles the context first."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ settled = run_dir / "certificate.pdf"
+
+ receipt = await attach(
+ page,
+ make_claimed_download_mock(
+ path=None,
+ suggested_filename="certificate.pdf",
+ context=_context_with(_SettlingInterceptor(settled, b"drained bytes")),
+ ),
+ "#file",
+ )
+
+ assert receipt == {"filename": "certificate.pdf", "size": len(b"drained bytes")}
+ assert page.attached[0][1]["buffer"] == b"drained bytes"
+
+
+async def test_a_run_directory_file_is_only_taken_for_a_download_the_browser_completed(tmp_path: Path) -> None:
+ """Without Playwright's own path the file is located by name, so every other signal has to hold."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ stale = run_dir / "earlier.pdf"
+ stale.write_bytes(b"from before this block")
+ an_hour_ago = time.time_ns() - 3_600_000_000_000
+ os.utime(stale, ns=(an_hour_ago, an_hour_ago))
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ fresh = run_dir / "certificate.pdf"
+ fresh.write_bytes(b"settled certificate bytes")
+ monitor = MagicMock(spec=CDPDownloadInterceptor)
+ monitor.is_monitoring_browser_downloads.return_value = True
+ monitor.settle_browser_downloads.side_effect = _quiet_settle
+
+ for download in (
+ make_claimed_download_mock(path=None, suggested_filename="certificate.pdf", failure="canceled"),
+ make_claimed_download_mock(path=None, suggested_filename="certificate.pdf", failure_error=RuntimeError("gone")),
+ make_claimed_download_mock(path=None, suggested_filename="earlier.pdf"),
+ make_claimed_download_mock(path=None, suggested_filename="unrelated.pdf"),
+ make_claimed_download_mock(path=None, suggested_filename=""),
+ make_claimed_download_mock(path=None, suggested_filename="certificate.pdf", context=_context_with(monitor)),
+ ):
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, download, "#file")
+
+ assert page.attached == []
+ assert fresh.is_file()
+
+
+async def test_a_collision_suffixed_copy_of_the_suggested_name_is_the_one_that_uploads(tmp_path: Path) -> None:
+ """A binding that uniquifies a collision writes "name (1).ext" beside an earlier block's file; only
+ the fresh copy is this block's, so the stale original is not a second candidate."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ stale = run_dir / "certificate.pdf"
+ stale.write_bytes(b"an earlier block's copy")
+ before_block = stale.stat().st_mtime_ns - 1_000_000
+ os.utime(stale, ns=(before_block, before_block))
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ uniquified = run_dir / "certificate (1).pdf"
+ uniquified.write_bytes(b"this block's copy")
+
+ receipt = await attach(page, make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"), "#file")
+
+ assert receipt == {"filename": "certificate.pdf", "size": len(b"this block's copy")}
+ assert page.attached[0][1]["buffer"] == b"this block's copy"
+
+
+async def test_a_download_stamped_before_the_block_started_is_still_this_block_s_file(tmp_path: Path) -> None:
+ """Linux stamps files from a coarse clock, so a download that settles moments after the block
+ starts can carry an earlier mtime. Freshness is decided by what the run directory already held."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ settled = run_dir / "certificate.pdf"
+ settled.write_bytes(b"settled after the block began")
+ backdated = time.time_ns() - 5_000_000
+ os.utime(settled, ns=(backdated, backdated))
+
+ receipt = await attach(page, make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"), "#file")
+
+ assert receipt == {"filename": "certificate.pdf", "size": len(b"settled after the block began")}
+
+
+async def test_a_stalled_download_is_refused_when_the_settlement_window_closes(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A transfer that fires its download event and then stalls must not hold the runner past the
+ settlement window: path() and failure() never return here, and the attach still refuses in time."""
+ monkeypatch.setattr(code_block_authorized_files, "SAVE_DOWNLOADED_FILES_TIMEOUT", 0.2)
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ stalled = make_claimed_download_mock(path=None, suggested_filename="certificate.pdf")
+ never = asyncio.Event()
+
+ async def hang(*_: object) -> None:
+ await never.wait()
+
+ stalled.path.side_effect = hang
+ stalled.failure.side_effect = hang
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await asyncio.wait_for(attach(page, stalled, "#file"), timeout=5)
+ assert page.attached == []
+
+
+async def test_a_lookalike_download_cannot_upload_an_earlier_block_s_file(tmp_path: Path) -> None:
+ """Authored code can build an object with every download attribute. Only an object the browser
+ itself emitted is proof of a claim, and a file the run already held is never this block's."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ earlier = run_dir / "payroll.pdf"
+ earlier.write_bytes(b"an earlier block's download")
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+
+ fresh = run_dir / "this-block.pdf"
+ fresh.write_bytes(b"a file this block holds")
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, make_claimed_download_mock(path=fresh, suggested_filename="this-block.pdf"), "#file")
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, started(make_claimed_download_mock(path=earlier, suggested_filename="payroll.pdf")), "#file")
+ assert page.attached == []
+
+
+async def test_a_same_name_download_that_starts_during_capture_refuses_the_earlier_claim(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The supersession check before the scan leaves a window: a second same-name download can start and
+ overwrite the file while it is being captured. The check runs again once the bytes are held."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ first = started(make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"))
+ (run_dir / "certificate.pdf").write_bytes(b"first copy")
+ real_capture = code_block_authorized_files.capture_authorized_file
+
+ def capture_while_a_second_download_lands(path: Path, **kwargs: Any) -> Any:
+ started(make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"))
+ (run_dir / "certificate.pdf").write_bytes(b"second copy")
+ return real_capture(path, **kwargs)
+
+ monkeypatch.setattr(code_block_authorized_files, "capture_authorized_file", capture_while_a_second_download_lands)
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, first, "#file")
+ assert page.attached == []
+
+
+async def test_closing_the_log_releases_a_stalled_download_s_tracker() -> None:
+ """A stalled transfer never resolves failure(). Closing the log must end its tracker, which otherwise
+ holds the log and its browser context past the block, on a persistent context for the session."""
+ log, started = _browser_download_log()
+ never = asyncio.Event()
+ stalled = make_claimed_download_mock(path=None, suggested_filename="report.pdf")
+ stalled.failure.side_effect = never.wait
+ started(stalled)
+ await asyncio.sleep(0.01)
+ assert not any(completion.done() for completion in log._completions)
+
+ log.close()
+ await asyncio.sleep(0.01)
+
+ assert all(completion.done() for completion in log._completions)
+
+
+class _EventSource:
+ def __init__(self) -> None:
+ self.handlers: dict[str, list[Callable[..., None]]] = {}
+
+ def on(self, event: str, handler: Callable[..., None]) -> None:
+ self.handlers.setdefault(event, []).append(handler)
+
+ def remove_listener(self, event: str, handler: Callable[..., None]) -> None:
+ self.handlers[event].remove(handler)
+
+ def emit(self, event: str, value: object) -> None:
+ for handler in list(self.handlers.get(event, [])):
+ handler(value)
+
+
+class _EventContext(_EventSource):
+ def __init__(self, *pages: _EventSource) -> None:
+ super().__init__()
+ self.pages = list(pages)
+
+
+async def test_a_download_overwritten_by_a_later_same_name_download_is_refused(tmp_path: Path) -> None:
+ """Chrome overwrites a same-name download in place under the run-scoped binding. When the first has
+ finished before the second starts, the file holds the second's bytes: only the second may attach."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ tab = _EventSource()
+ context = _EventContext(tab)
+ log = BlockDownloadLog(context)
+ page = _FakePage()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ # A finished Playwright download reports its launch-directory guid, which never exists here.
+ first = make_claimed_download_mock(path=tmp_path / "launch-dir" / "guid-1", suggested_filename="certificate.pdf")
+ second = make_claimed_download_mock(path=tmp_path / "launch-dir" / "guid-2", suggested_filename="certificate.pdf")
+ tab.emit("download", first)
+ await asyncio.sleep(0.01)
+ tab.emit("download", second)
+ await asyncio.sleep(0.01)
+ (run_dir / "certificate.pdf").write_bytes(b"second copy")
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, first, "#file")
+ receipt = await attach(page, second, "#file")
+
+ assert receipt == {"filename": "certificate.pdf", "size": len(b"second copy")}
+ assert [files["buffer"] for _, files in page.attached] == [b"second copy"]
+ log.close()
+ assert tab.handlers["download"] == [] and context.handlers["page"] == []
+
+
+async def test_a_download_whose_wait_timed_out_still_counts_as_in_flight(tmp_path: Path) -> None:
+ """The raw-CDP engine's failure() gives up after a fixed wait and reports no failure while the transfer
+ keeps running. Such a download is not finished, so a same-name download started meanwhile overlaps it."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ # failure() and path() both come back empty, exactly as they do once the engine's wait expires.
+ started(make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"))
+ await asyncio.sleep(0.01)
+ later = started(
+ make_claimed_download_mock(path=tmp_path / "launch-dir" / "guid", suggested_filename="certificate.pdf")
+ )
+ await asyncio.sleep(0.01)
+ (run_dir / "certificate.pdf").write_bytes(b"the slow download's bytes")
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, later, "#file")
+ assert page.attached == []
+ log.close()
+
+
+async def test_a_lookalike_is_refused_at_the_proof_of_claim_gate(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The capability check is structural, so authored code can build an object that satisfies it. Only the
+ log proves the browser emitted this one, and that refusal lands before the object is read: the
+ supersession rules also reject an unknown object today, and must not be the only thing holding this."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ started(make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"))
+ await asyncio.sleep(0.01)
+ (run_dir / "certificate.pdf").write_bytes(b"this block's download")
+ lookalike = make_claimed_download_mock(path=run_dir / "certificate.pdf", suggested_filename="certificate.pdf")
+ decisions: list[tuple[str, object]] = []
+ monkeypatch.setattr(
+ code_block_authorized_files.LOG,
+ "info",
+ lambda event, **fields: decisions.append((event, fields.get("outcome"))),
+ )
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, lookalike, "#file")
+
+ assert ("codeblock.download_authorize_decision", "refused_unclaimed_download_object") in decisions
+ assert lookalike.path.await_count == 0
+ assert page.attached == []
+
+
+async def test_rebinding_path_to_a_sibling_download_cannot_swap_its_bytes(tmp_path: Path) -> None:
+ """In-process code can rebind path() on the genuine object it was handed. The log keeps the path()
+ the browser's object had when emitted, so the claim still resolves to its own download."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ (run_dir / "a.pdf").write_bytes(b"a's own bytes")
+ (run_dir / "b.pdf").write_bytes(b"b's bytes")
+ a = started(make_claimed_download_mock(path=tmp_path / "launch-dir" / "guid-a", suggested_filename="a.pdf"))
+ b = started(make_claimed_download_mock(path=run_dir / "b.pdf", suggested_filename="b.pdf"))
+ await asyncio.sleep(0.01)
+ a.path = b.path
+
+ receipt = await attach(page, a, "#file")
+
+ assert receipt == {"filename": "a.pdf", "size": len(b"a's own bytes")}
+ assert page.attached[0][1]["buffer"] == b"a's own bytes"
+
+
+async def test_a_redirected_path_cannot_reach_an_inherited_file_in_a_subdirectory(tmp_path: Path) -> None:
+ """In-process code can reassign path() on the genuine download object, which passes the log check.
+ An earlier block's file nested under the run directory must still read as inherited."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ (run_dir / "earlier").mkdir(parents=True)
+ nested = run_dir / "earlier" / "payroll.pdf"
+ nested.write_bytes(b"an earlier block's download")
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ genuine = started(make_claimed_download_mock(path=None, suggested_filename="receipt.pdf"))
+ genuine.path.return_value = str(nested)
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, genuine, "#file")
+ assert page.attached == []
+
+
+async def test_same_name_downloads_in_flight_together_are_both_refused(tmp_path: Path) -> None:
+ """The file holds whichever same-name download finishes last, not whichever started last. Here the
+ earlier one is still transferring when the later starts and finishes last, so the file is its bytes:
+ neither claim can prove the file is its own."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ )
+ still_transferring = asyncio.Event()
+
+ async def unfinished() -> None:
+ await still_transferring.wait()
+
+ earlier = make_claimed_download_mock(path=None, suggested_filename="certificate.pdf")
+ earlier.failure.side_effect = unfinished
+ started(earlier)
+ await asyncio.sleep(0.01)
+ later = started(make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"))
+ await asyncio.sleep(0.01)
+ (run_dir / "certificate.pdf").write_bytes(b"earlier download's bytes")
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, later, "#file")
+ assert page.attached == []
+ still_transferring.set()
+
+
+async def test_a_percent_encoded_name_is_matched_on_disk_as_the_browser_wrote_it(tmp_path: Path) -> None:
+ """The browser saves a literal "%20"; matching the URL-decoded upload name would miss it."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ (run_dir / "cert%20copy.pdf").write_bytes(b"literal percent bytes")
+
+ await attach(page, make_claimed_download_mock(path=None, suggested_filename="cert%20copy.pdf"), "#file")
+
+ assert page.attached[0][1]["buffer"] == b"literal percent bytes"
+
+
+async def test_two_same_name_downloads_in_one_block_refuse_rather_than_upload_either(tmp_path: Path) -> None:
+ """Where a binding uniquifies instead of overwriting, two fresh same-name files are indistinguishable
+ to the worker, so the attach refuses rather than guess; uploading the wrong document is the harm."""
+ run_dir = tmp_path / "downloads" / "wr_claimed"
+ run_dir.mkdir(parents=True)
+ page = _FakePage()
+ attach = _bind_claimed_download_attach(page, run_dir)
+ first = run_dir / "certificate.pdf"
+ first.write_bytes(b"first invoice")
+ second = run_dir / "certificate (1).pdf"
+ second.write_bytes(b"second invoice")
+
+ with pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, make_claimed_download_mock(path=None, suggested_filename="certificate.pdf"), "#file")
+
+ assert page.attached == []
+
+
+RegistrationRead = list[FileInfo] | BaseException | None
+
+
+class _SourceOverrides(TypedDict, total=False):
+ baseline: Mapping[RegisteredDownloadIdentity, str] | None
+ stored: bytes
+ artifact_run_id: str
+ retrieve_error: BaseException
+
+
+def _registered_downloads(
+ monkeypatch: pytest.MonkeyPatch,
+ *reads: RegistrationRead,
+ baseline: Mapping[RegisteredDownloadIdentity, str] | None = MappingProxyType({}),
+ stored: bytes = _SESSION_BYTES,
+ artifact_run_id: str = "wr_session",
+ retrieve_error: BaseException | None = None,
+) -> RegisteredDownloadSource:
+ """The run's registration as the worker reads it: one probe result per poll, the last one repeating."""
+ monkeypatch.setattr(code_block_authorized_files, "_REGISTERED_DOWNLOAD_POLL_SECONDS", 0)
+ remaining = list(reads)
+
+ async def probe() -> tuple[list[FileInfo] | None, set[str]]:
+ read = remaining.pop(0) if len(remaining) > 1 else remaining[0]
+ if isinstance(read, BaseException):
+ raise read
+ return read, set()
+
+ artifact = SimpleNamespace(artifact_type=ArtifactType.DOWNLOAD, run_id=artifact_run_id)
+ monkeypatch.setattr(app.DATABASE.artifacts, "get_artifact_by_id", AsyncMock(return_value=artifact))
+ retrieve = AsyncMock(side_effect=retrieve_error) if retrieve_error is not None else AsyncMock(return_value=stored)
+ monkeypatch.setattr(app.STORAGE, "retrieve_artifact", retrieve)
+ return RegisteredDownloadSource(
+ probe=probe, organization_id="org_authorized", run_id="wr_session", baseline=baseline
+ )
+
+
+def _remote_download(*, failure: str | None = None, context: object | None = None) -> Download:
+ """A download on a remote browser: its path() cannot be read from this worker."""
+ return make_claimed_download_mock(
+ path=None,
+ suggested_filename="certificate.pdf",
+ path_error=RuntimeError("remote"),
+ failure=failure,
+ context=context,
+ )
+
+
+SessionAttach = Callable[[_FakePage, str | Download, str], Awaitable[dict[str, str | int]]]
+
+
+def _session_attach(
+ page: _FakePage, run_dir: Path, registered: RegisteredDownloadSource
+) -> tuple[SessionAttach, Callable[[Download], Download]]:
+ log, started = _browser_download_log()
+ attach = bind_inline_attach_authorized_file(
+ page,
+ {},
+ {},
+ download_root=run_dir.parent,
+ workflow_run_id=run_dir.name,
+ organization_id="org_authorized",
+ max_bytes=1024,
+ download_log=log,
+ registered_downloads=registered,
+ )
+
+ async def attach_started(target: _FakePage, file: str | Download, selector: str) -> dict[str, str | int]:
+ return await attach(target, file if isinstance(file, str) else started(file), selector)
+
+ return attach_started, started
+
+
+def _decisions(logs: list[dict[str, Any]]) -> list[str]:
+ return [log["outcome"] for log in logs if log["event"] == "codeblock.download_authorize_decision"]
+
+
+async def _download_rows_registration_adds(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run_dir: Path) -> int:
+ """Run the real local registration over the run directory and count the DOWNLOAD rows it creates."""
+ create_download_artifact = AsyncMock()
+ monkeypatch.setattr(
+ local_storage_module,
+ "app",
+ SimpleNamespace(
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=create_download_artifact),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=AsyncMock(return_value=[]))
+ ),
+ ),
+ )
+ monkeypatch.setattr(local_storage_module, "get_download_dir", lambda run_id: str(run_dir))
+ monkeypatch.setattr(
+ storage_base_module, "resolve_download_attempt", AsyncMock(return_value=("wr_session", 1, None))
+ )
+ await LocalStorage(str(tmp_path / "artifacts")).save_downloaded_files(
+ organization_id="org_authorized", run_id="wr_session"
+ )
+ return create_download_artifact.await_count
+
+
+async def test_a_session_download_uploads_from_the_registered_artifact_not_the_local_disk(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A persistent remote browser never writes the bytes to this worker, so the upload is resolved from the
+ one DOWNLOAD artifact the claim registered, checked against its checksum."""
+ run_dir = tmp_path / "downloads" / "wr_session"
+ inherited = _registered_row("earlier.pdf", b"an earlier block's file", artifact_id="a_earlier")
+ registered = _registered_downloads(
+ monkeypatch,
+ [inherited],
+ [inherited, _registered_row()],
+ baseline={(inherited.filename, inherited.checksum): inherited.filename},
+ )
+ page = _FakePage()
+ attach, _ = _session_attach(page, run_dir, registered)
+
+ with capture_logs() as logs:
+ receipt = await attach(page, _remote_download(), "#file")
+
+ assert receipt == {"filename": "certificate.pdf", "size": len(_SESSION_BYTES)}
+ assert page.attached == [
+ ("#file", {"name": "certificate.pdf", "mimeType": "application/pdf", "buffer": _SESSION_BYTES})
+ ]
+ app.DATABASE.artifacts.get_artifact_by_id.assert_awaited_once_with("a_session", "org_authorized")
+ assert _decisions(logs) == ["authorized_registered_artifact"]
+ assert await _download_rows_registration_adds(tmp_path, monkeypatch, run_dir) == 0
+ (private_copy,) = run_dir.glob(".authorized-*/*")
+ with pytest.raises(AuthorizedFileAccessError, match="accepts only a materialized file"):
+ await attach(page, str(private_copy), "#file")
+ assert len(page.attached) == 1
+
+
+ ("failure", "outcome"),
+ [
+ ("canceled", "authorized_registered_artifact"),
+ (None, "authorized_registered_artifact"),
+ ("network failed", "refused_browser_reported_failure"),
+ ],
+)
+async def test_a_monitor_owned_download_uploads_from_its_registered_artifact_unless_it_failed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str | None, outcome: str
+) -> None:
+ """The monitor denies the browser's own transfer, so Playwright calls it cancelled even when it arrived."""
+ run_dir = tmp_path / "downloads" / "wr_session"
+ run_dir.mkdir(parents=True)
+ (run_dir / "certificate.pdf").write_bytes(b"a monitor-saved file this download cannot be tied to")
+ monitor = MagicMock(spec=CDPDownloadInterceptor)
+ monitor.is_monitoring_browser_downloads.return_value = True
+ monitor.settle_browser_downloads.side_effect = _quiet_settle
+ page = _FakePage()
+ attach, _ = _session_attach(page, run_dir, _registered_downloads(monkeypatch, [_registered_row()]))
+
+ with capture_logs() as logs, suppress(AuthorizedFileAccessError):
+ await attach(page, _remote_download(failure=failure, context=_context_with(monitor)), "#file")
+
+ assert _decisions(logs) == [outcome]
+ expected = [_SESSION_BYTES] if outcome == "authorized_registered_artifact" else []
+ assert [files["buffer"] for _, files in page.attached] == expected
+
+
+ ("reads", "source", "failure", "outcome"),
+ [
+ ([[_registered_row(checksum="0" * 64)]], {}, None, "refused_registered_checksum_mismatch"),
+ ([[_registered_row()]], {"stored": b"bytes storage changed"}, None, "refused_registered_checksum_mismatch"),
+ ([[]], {}, None, "refused_no_registered_download"),
+ (
+ [[_registered_row()]],
+ {"baseline": {("certificate.pdf", hashlib.sha256(_SESSION_BYTES).hexdigest()): "certificate.pdf"}},
+ None,
+ "refused_no_registered_download",
+ ),
+ (
+ [[_registered_row(), _registered_row(content=b"a second copy", artifact_id="a_other")]],
+ {},
+ None,
+ "refused_ambiguous_registered_download",
+ ),
+ (
+ [[_registered_row(), _registered_row("certificate (1).pdf", b"a collision copy", artifact_id="a_copy")]],
+ {},
+ None,
+ "refused_ambiguous_registered_download",
+ ),
+ ([[_registered_row(artifact_id=None)]], {}, None, "refused_registered_download_without_artifact"),
+ ([[_registered_row(checksum="")]], {}, None, "refused_registered_download_without_checksum"),
+ ([[_registered_row(file_size=4096)]], {}, None, "refused_registered_download_too_large"),
+ (
+ [[_registered_row().model_copy(update={"file_size": None})]],
+ {},
+ None,
+ "refused_registered_download_without_size",
+ ),
+ ([[_registered_row()]], {"artifact_run_id": "wr_other"}, None, "refused_registered_artifact_unavailable"),
+ ([None], {}, None, "refused_registration_unreadable"),
+ ([RuntimeError("database down")], {}, None, "refused_registration_unreadable"),
+ ([TimeoutError()], {}, None, "refused_no_registered_download"),
+ ([[_registered_row()]], {"retrieve_error": OSError("storage down")}, None, "refused_registration_unreadable"),
+ ([[_registered_row()]], {"baseline": None}, None, "refused_registration_baseline_unreadable"),
+ ([[_registered_row()]], {}, "network failed", "refused_browser_reported_failure"),
+ ],
+ ids=[
+ "row-checksum-mismatch",
+ "stored-bytes-mismatch",
+ "nothing-registered",
+ "row-already-in-baseline",
+ "two-matching-rows",
+ "exact-and-collision-copy-rows",
+ "row-without-artifact-id",
+ "row-without-checksum",
+ "known-oversize",
+ "row-without-size",
+ "artifact-of-another-run",
+ "registration-unreadable",
+ "probe-raises",
+ "every-read-times-out",
+ "storage-raises",
+ "baseline-unreadable",
+ "session-transfer-failed",
+ ],
+)
+async def test_a_session_download_is_refused_unless_exactly_one_verified_registered_row_is_its_own(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ reads: list[RegistrationRead],
+ source: _SourceOverrides,
+ failure: str | None,
+ outcome: str,
+) -> None:
+ monkeypatch.setattr(code_block_authorized_files, "SAVE_DOWNLOADED_FILES_TIMEOUT", 0.2)
+ run_dir = tmp_path / "downloads" / "wr_session"
+ page = _FakePage()
+ attach, _ = _session_attach(page, run_dir, _registered_downloads(monkeypatch, *reads, **source))
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, _remote_download(failure=failure), "#file")
+
+ assert page.attached == []
+ assert _decisions(logs) == [outcome]
+
+
+async def test_a_registration_read_that_outlasts_its_cap_is_polled_again_not_refused(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A read can wait on the download still in flight, so one slow read must not refuse a download that registers."""
+ monkeypatch.setattr(code_block_authorized_files, "_REGISTERED_DOWNLOAD_PROBE_TIMEOUT_SECONDS", 0.05)
+ registered = _registered_downloads(monkeypatch, [_registered_row()])
+ reads = 0
+
+ async def slow_first_read() -> tuple[list[FileInfo] | None, set[str]]:
+ nonlocal reads
+ reads += 1
+ if reads == 1:
+ await asyncio.sleep(1)
+ return await registered.probe()
+
+ page = _FakePage()
+ attach, _ = _session_attach(page, tmp_path / "downloads" / "wr_session", replace(registered, probe=slow_first_read))
+
+ with capture_logs() as logs:
+ await attach(page, _remote_download(), "#file")
+
+ assert _decisions(logs) == ["authorized_registered_artifact"]
+ assert [files["buffer"] for _, files in page.attached] == [_SESSION_BYTES]
+
+
+async def test_a_session_download_uploads_from_a_registered_collision_copy(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A binding that uniquifies registers the claim as "name (1).ext"; it still uploads under the suggested name."""
+ registered = _registered_downloads(monkeypatch, [_registered_row("certificate (1).pdf")])
+ page = _FakePage()
+ attach, _ = _session_attach(page, tmp_path / "downloads" / "wr_session", registered)
+
+ with capture_logs() as logs:
+ await attach(page, _remote_download(), "#file")
+
+ assert _decisions(logs) == ["authorized_registered_artifact"]
+ assert page.attached == [
+ ("#file", {"name": "certificate.pdf", "mimeType": "application/pdf", "buffer": _SESSION_BYTES})
+ ]
+
+
+async def test_a_session_download_without_a_block_download_log_is_refused(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Without the block's log no earlier same-name download can be ruled out as the owner of the row."""
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await capture_claimed_download(
+ _remote_download(),
+ download_root=tmp_path / "downloads",
+ download_run_id="wr_session",
+ organization_id="org_authorized",
+ max_bytes=1024,
+ inherited_files=frozenset(),
+ registered=_registered_downloads(monkeypatch, [_registered_row()]),
+ )
+
+ assert _decisions(logs) == ["refused_no_download_log"]
+
+
+async def test_a_session_download_is_refused_when_an_earlier_same_name_download_in_the_block_could_own_its_row(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The block-start baseline predates both downloads, so the one new row cannot be told apart."""
+ run_dir = tmp_path / "downloads" / "wr_session"
+ page = _FakePage()
+ attach, started = _session_attach(page, run_dir, _registered_downloads(monkeypatch, [_registered_row()]))
+ started(_remote_download())
+ await asyncio.sleep(0.01)
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, _remote_download(), "#file")
+
+ assert page.attached == []
+ assert _decisions(logs) == ["refused_same_name_download_in_block"]
+
+
+async def test_the_same_session_download_attached_twice_is_fetched_and_copied_once(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A block can attach one download to several inputs, and each registered-artifact capture writes a private
+ copy, so repeating the attach must reuse the first capture rather than fill the run directory."""
+ run_dir = tmp_path / "downloads" / "wr_session"
+ registered = _registered_downloads(monkeypatch, [_registered_row()])
+ page = _FakePage()
+ attach, _ = _session_attach(page, run_dir, registered)
+ download = _remote_download()
+
+ first = await attach(page, download, "#file")
+ second = await attach(page, download, "#second-file")
+
+ assert first == second == {"filename": "certificate.pdf", "size": len(_SESSION_BYTES)}
+ assert [selector for selector, _ in page.attached] == ["#file", "#second-file"]
+ assert [files["buffer"] for _, files in page.attached] == [_SESSION_BYTES, _SESSION_BYTES]
+ assert len(list(run_dir.glob(".authorized-*"))) == 1
+ app.STORAGE.retrieve_artifact.assert_awaited_once()
+
+
+async def test_a_session_download_whose_name_really_contains_an_escape_matches_its_row(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A session directory keeps the escaping the site sent, so the row is spelled literally; decoding the
+ claim's name before matching would miss it and refuse a download that did arrive."""
+ registered = _registered_downloads(monkeypatch, [_registered_row("report%20final.pdf")])
+ page = _FakePage()
+ attach, _ = _session_attach(page, tmp_path / "downloads" / "wr_session", registered)
+ claimed = make_claimed_download_mock(
+ path=None, suggested_filename="report%20final.pdf", path_error=RuntimeError("remote")
+ )
+
+ with capture_logs() as logs:
+ await attach(page, claimed, "#file")
+
+ assert _decisions(logs) == ["authorized_registered_artifact"]
+ assert [files["buffer"] for _, files in page.attached] == [_SESSION_BYTES]
+
+
+async def test_an_extensionless_claim_shares_the_name_of_a_sibling_that_carries_one(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A bare name can select a row that carries a monitor-derived extension, so a sibling spelled with one is
+ a collision too: the claim refuses rather than upload that sibling's bytes under its own name."""
+ registered = _registered_downloads(monkeypatch, [_registered_row("2026.csv", b"the sibling's rows")])
+ page = _FakePage()
+ attach, started = _session_attach(page, tmp_path / "downloads" / "wr_session", registered)
+ started(make_claimed_download_mock(path=None, suggested_filename="2026.csv", path_error=RuntimeError("remote")))
+ await asyncio.sleep(0.01)
+ claimed = make_claimed_download_mock(path=None, suggested_filename="2026", path_error=RuntimeError("remote"))
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, claimed, "#file")
+
+ assert page.attached == []
+ assert _decisions(logs) == ["refused_same_name_download_in_block"]
+
+
+async def test_a_download_registered_under_a_monitor_derived_extension_still_matches(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A site can send a name with no extension; the monitor adds one from the response type before it
+ registers, so matching the bare name alone would refuse a download that did arrive."""
+ registered = _registered_downloads(monkeypatch, [_registered_row("2026.pdf")])
+ page = _FakePage()
+ attach, _ = _session_attach(page, tmp_path / "downloads" / "wr_session", registered)
+ claimed = make_claimed_download_mock(path=None, suggested_filename="2026", path_error=RuntimeError("remote"))
+
+ with capture_logs() as logs:
+ await attach(page, claimed, "#file")
+
+ assert _decisions(logs) == ["authorized_registered_artifact"]
+ assert [files["buffer"] for _, files in page.attached] == [_SESSION_BYTES]
+
+
+async def test_a_refused_claim_leaves_no_private_copy_behind(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The bytes are fetched and copied before the last checks run, so a claim refused there must discard its
+ copy: the block can lose that race again under a name that never repeats."""
+ run_dir = tmp_path / "downloads" / "wr_session"
+ registered = _registered_downloads(monkeypatch, [], [_registered_row()])
+ page = _FakePage()
+ read = registered.probe
+ sibling: list[Download] = []
+
+ async def start_sibling_then_read() -> tuple[list[FileInfo] | None, set[str]]:
+ rows = await read()
+ if not sibling:
+ sibling.append(
+ started(
+ make_claimed_download_mock(
+ path=None, suggested_filename="certificate (1).pdf", path_error=RuntimeError("remote")
+ )
+ )
+ )
+ return rows
+
+ attach, started = _session_attach(page, run_dir, replace(registered, probe=start_sibling_then_read))
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, _remote_download(), "#file")
+
+ assert _decisions(logs) == ["refused_same_name_download_during_capture"]
+ assert list(run_dir.glob(".authorized-*")) == []
+
+
+async def test_a_percent_escaped_sibling_shares_the_name_the_monitor_saves_under(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The monitor percent-decodes before saving, so "report%20final.pdf" and "report final.pdf" land on one
+ file. The claim cannot tell whose row it found, so it refuses rather than upload the sibling's bytes."""
+ saved_name = "report final.pdf"
+ registered = _registered_downloads(monkeypatch, [_registered_row(saved_name)])
+ page = _FakePage()
+ attach, started = _session_attach(page, tmp_path / "downloads" / "wr_session", registered)
+ started(
+ make_claimed_download_mock(
+ path=None, suggested_filename="report%20final.pdf", path_error=RuntimeError("remote")
+ )
+ )
+ await asyncio.sleep(0.01)
+ claimed = make_claimed_download_mock(path=None, suggested_filename=saved_name, path_error=RuntimeError("remote"))
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, claimed, "#file")
+
+ assert page.attached == []
+ assert _decisions(logs) == ["refused_same_name_download_in_block"]
+
+
+async def test_a_collision_equivalent_download_started_while_polling_is_refused(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The poll waits up to 30s, and a row is matched by collision-equivalent name while supersession compares
+ names exactly, so a sibling that starts mid-poll could own the row this claim takes."""
+ registered = _registered_downloads(monkeypatch, [], [_registered_row()])
+ page = _FakePage()
+ read = registered.probe
+ sibling: list[Download] = []
+
+ async def start_sibling_then_read() -> tuple[list[FileInfo] | None, set[str]]:
+ rows = await read()
+ if not sibling:
+ sibling.append(
+ started(
+ make_claimed_download_mock(
+ path=None, suggested_filename="certificate (1).pdf", path_error=RuntimeError("remote")
+ )
+ )
+ )
+ return rows
+
+ attach, started = _session_attach(
+ page, tmp_path / "downloads" / "wr_session", replace(registered, probe=start_sibling_then_read)
+ )
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await attach(page, _remote_download(), "#file")
+
+ assert page.attached == []
+ assert _decisions(logs) == ["refused_same_name_download_during_capture"]
+
+
+async def test_a_superseded_session_download_is_refused_even_with_a_registered_row(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ log, started = _browser_download_log()
+ first = started(_remote_download())
+ started(_remote_download())
+
+ with capture_logs() as logs, pytest.raises(AuthorizedFileAccessError, match="could not be materialized"):
+ await capture_claimed_download(
+ first,
+ download_root=tmp_path / "downloads",
+ download_run_id="wr_session",
+ organization_id="org_authorized",
+ max_bytes=1024,
+ inherited_files=frozenset(),
+ download_log=log,
+ registered=_registered_downloads(monkeypatch, [_registered_row()]),
+ )
+
+ assert _decisions(logs) == ["refused_superseded_same_name_download"]
+
+
+async def test_a_registered_copy_changed_after_capture_is_refused_at_redemption(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_dir = tmp_path / "downloads" / "wr_session"
+ log, started = _browser_download_log()
+
+ materialized = await capture_claimed_download(
+ started(_remote_download()),
+ download_root=run_dir.parent,
+ download_run_id="wr_session",
+ organization_id="org_authorized",
+ max_bytes=1024,
+ inherited_files=frozenset(),
+ download_log=log,
+ registered=_registered_downloads(monkeypatch, [_registered_row()]),
+ )
+ (private_copy,) = run_dir.glob(".authorized-*/*")
+ private_copy.write_bytes(b"swapped after capture")
+
+ with pytest.raises(AuthorizedFileAccessError, match="unavailable or changed"):
+ read_authorized_file(
+ materialized,
+ download_root=run_dir.parent,
+ workflow_run_id="wr_session",
+ organization_id="org_authorized",
+ max_bytes=1024,
+ )
+
+
+async def test_only_a_signed_remote_binding_snapshots_the_registered_downloads(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A run-scoped binding resolves from its own directory, and an unsigned listing has no artifact ids to
+ resolve, so neither pays for a registration read."""
+ probe = AsyncMock(return_value=([_registered_row()], set()))
+ local_page = SimpleNamespace(context=SimpleNamespace())
+
+ async def source(binding: DownloadBinding) -> RegisteredDownloadSource | None:
+ return await _registered_download_source(
+ probe, local_page, download_binding=binding, organization_id="org_1", download_run_id="wr_1"
+ )
+
+ monkeypatch.setattr(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", None)
+ assert await source(DownloadBinding.SESSION_DIR) is None
+ monkeypatch.setattr(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", "k1:secret")
+ assert await source(DownloadBinding.RUN_DIR) is None
+ session_source = await source(DownloadBinding.SESSION_DIR)
+
+ assert session_source is not None
+ assert session_source.baseline == {
+ ("certificate.pdf", hashlib.sha256(_SESSION_BYTES).hexdigest()): "certificate.pdf"
+ }
+ assert probe.await_count == 1
diff --git a/tests/unit/test_code_block_captcha.py b/tests/unit/test_code_block_captcha.py
index 455b591a5..fae63ffe2 100644
--- a/tests/unit/test_code_block_captcha.py
+++ b/tests/unit/test_code_block_captcha.py
@@ -39,10 +39,12 @@ class FakeLocator:
input_values: list[str] | None = None,
visible: bool = True,
box: dict[str, float] | None = None,
+ raises: bool = False,
) -> None:
self._count = count
self._checked = checked
self._visible = visible
+ self._raises = raises
self._box = box if box is not None else {"x": 10.0, "y": 10.0, "width": 300.0, "height": 80.0}
self._input_values = list(input_values or [])
self._input_value_calls = 0
@@ -55,6 +57,8 @@ class FakeLocator:
return self._count
async def is_visible(self) -> bool:
+ if self._raises:
+ raise PlaywrightError("Element is not attached to the DOM")
return self._visible
async def bounding_box(self) -> dict[str, float]:
@@ -974,6 +978,57 @@ async def test_nested_visible_marker_after_many_hidden_ones_is_detected(monkeypa
agent_function.auto_solve_captchas.assert_awaited_once_with(page)
+async def test_page_marker_that_raises_does_not_hide_a_presented_one(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+ page = FakePage()
+ page.marker = _MatchList([FakeLocator(count=1, raises=True), FakeLocator(count=1)]) # type: ignore[assignment]
+
+ assert await solve_challenge_ladder(page) is True, "an unreadable marker must not read as no challenge"
+
+ agent_function.auto_solve_captchas.assert_awaited_once_with(page)
+
+
+async def test_page_checkbox_that_raises_does_not_hide_a_presented_one(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+ page = FakePage()
+ page.checkbox = _MatchList([FakeLocator(count=1, raises=True), FakeLocator(count=1)]) # type: ignore[assignment]
+
+ assert await solve_challenge_ladder(page) is True, "an unreadable checkbox must not read as no challenge"
+
+ agent_function.auto_solve_captchas.assert_awaited_once_with(page)
+
+
+async def test_nested_marker_that_raises_does_not_hide_a_presented_one(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+ child_frame = FakeFrame(url="https://app.example/challenge-frame", visible=True)
+ child_frame.nested_marker = _MatchList([FakeLocator(count=1, raises=True), FakeLocator(count=1)]) # type: ignore[assignment]
+ page = FakePage(frames=[child_frame])
+
+ assert await solve_challenge_ladder(page, probe_child_frames=True) is True, (
+ "an unreadable nested marker must not read as no challenge"
+ )
+
+ agent_function.auto_solve_captchas.assert_awaited_once_with(page)
+
+
+async def test_hidden_checkbox_only_page_is_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+ page = FakePage(checkbox=True)
+ page.checkbox = FakeLocator(count=1, visible=False)
+
+ assert await solve_challenge_ladder(page) is False
+
+ agent_function.auto_solve_captchas.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_nested_offscreen_marker_is_not_detected(monkeypatch: pytest.MonkeyPatch) -> None:
# An embedded widget parked outside the viewport still reports is_visible(); it is not a gate the user sees.
@@ -1337,28 +1392,37 @@ async def _fulfill_challenge(route: Route) -> None:
@asynccontextmanager
-async def _challenge_browser_page(html: str) -> AsyncIterator[Page]:
+async def _challenge_browser_page(
+ html: str | None = None, *, url: str | None = None, expect_challenge_frame: bool = True
+) -> AsyncIterator[Page]:
async with async_playwright() as playwright:
- browser = await playwright.chromium.launch(headless=True)
+ # Production runs headful chromium, where a cross-origin widget frame is an out-of-process iframe;
+ # without site isolation a headless probe would never exercise that path.
+ browser = await playwright.chromium.launch(headless=True, args=["--site-per-process"])
try:
context = await browser.new_context()
await context.route("https://challenges.cloudflare.com/**", _fulfill_challenge)
page = await context.new_page()
- await page.set_content(html, wait_until="load")
- assert any(urlparse(frame.url).hostname == "challenges.cloudflare.com" for frame in page.frames), (
- "challenge frame did not commit"
- )
+ if url is not None:
+ await page.goto(url, wait_until="load")
+ else:
+ assert html is not None
+ await page.set_content(html, wait_until="load")
+ if expect_challenge_frame:
+ assert any(urlparse(frame.url).hostname == "challenges.cloudflare.com" for frame in page.frames), (
+ "challenge frame did not commit"
+ )
yield page
finally:
await browser.close()
-def _stub_solver_agent() -> AgentFunction:
+def _stub_solver_agent(*, solves: bool = True) -> AgentFunction:
return type(
"AgentFunctionStub",
(AgentFunction,),
{
- "auto_solve_captchas": AsyncMock(return_value=True),
+ "auto_solve_captchas": AsyncMock(return_value=solves),
"solve_recaptcha_token": AsyncMock(return_value=False),
},
)()
@@ -1585,3 +1649,180 @@ async def test_visible_challenge_frame_keeps_the_turnstile_extension_budget(
assert await solve_challenge_ladder(page, probe_child_frames=True) is True
assert resolve_calls == [captcha_solver_module._EXTENSION_ARM_TIMEOUT_SECONDS]
+
+
+_FAKE_CAPTCHA_SITE = Path(__file__).resolve().parents[2] / "dev_scripts" / "fake_captcha_site"
+
+_UNRENDERED_RECAPTCHA_HTML = """<!DOCTYPE html>
+<html><body>
+ <form>
+ <input id="email" type="email" />
+ <div class="g-recaptcha" data-sitekey="6LcFixtureKey"></div>
+ <button type="submit">Submit</button>
+ </form>
+</body></html>
+"""
+
+_HIDDEN_V3_BADGE_HTML = """<!DOCTYPE html>
+<html><body>
+ <form>
+ <input id="email" type="email" />
+ <button type="submit">Submit</button>
+ </form>
+ <div class="grecaptcha-badge" style="visibility:hidden;position:fixed;right:0;bottom:14px">
+ <iframe title="reCAPTCHA" width="256" height="60"></iframe>
+ </div>
+</body></html>
+"""
+
+_BELOW_THE_FOLD_RECAPTCHA_HTML = """<!DOCTYPE html>
+<html><body>
+ <form>
+ <input id="email" type="email" />
+ <div style="height:3000px"></div>
+ <div class="g-recaptcha" data-sitekey="6LcFixtureKey" style="width:304px;height:78px;background:#eee"></div>
+ <button type="submit">Submit</button>
+ </form>
+</body></html>
+"""
+
+_HIDDEN_THEN_RENDERED_RECAPTCHA_HTML = """<!DOCTYPE html>
+<html><body>
+ <form>
+ <div class="g-recaptcha" data-sitekey="6LcStaleKey" style="display:none"></div>
+ <div class="g-recaptcha" data-sitekey="6LcLiveKey" style="width:304px;height:78px;background:#eee"></div>
+ <button type="submit">Submit</button>
+ </form>
+</body></html>
+"""
+
+_RENDERED_TURNSTILE_WITH_HIDDEN_HCAPTCHA_HTML = """<!DOCTYPE html>
+<html><body>
+ <form>
+ <div class="cf-turnstile" data-sitekey="0xTESTKEY" style="width:300px;height:65px;background:#eee"></div>
+ <div class="h-captcha" data-sitekey="10000000-ffff-ffff-ffff-000000000001" style="display:none"></div>
+ <button type="submit">Submit</button>
+ </form>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_browser_invisible_hcaptcha_is_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An hCaptcha the site loaded in invisible mode and has not executed is not a gate the run must clear."""
+ agent_function = _stub_solver_agent(solves=False)
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+
+ async with _challenge_browser_page(
+ url=(_FAKE_CAPTCHA_SITE / "invisible_hcaptcha.html").as_uri(), expect_challenge_frame=False
+ ) as page:
+ assert await page.locator(captcha_solver_module._CAPTCHA_MARKER_SELECTOR).count() > 0
+
+ assert await solve_challenge_ladder(page) is False
+
+ agent_function.auto_solve_captchas.assert_not_awaited()
+ agent_function.solve_recaptcha_token.assert_not_awaited()
+
+
+@_skip_no_browser
+async def test_browser_invisible_hcaptcha_page_submits_after_the_absent_verdict(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The point of the absent verdict: the run goes on to Submit, and the site runs its own invisible
+ challenge from there."""
+ monkeypatch.setattr(app, "AGENT_FUNCTION", _stub_solver_agent(solves=False))
+
+ async with _challenge_browser_page(
+ url=(_FAKE_CAPTCHA_SITE / "invisible_hcaptcha.html").as_uri(), expect_challenge_frame=False
+ ) as page:
+ await page.fill("#full-name", "Sample Applicant")
+ assert await solve_challenge_ladder(page) is False
+
+ await page.click("#apply-submit")
+ await page.wait_for_url("**/invisible_hcaptcha_results.html*")
+
+ assert "h-captcha-response=fixture-invisible-token" in page.url
+ assert "Application received" in await page.locator("#confirmation").inner_text()
+
+
+@_skip_no_browser
+async def test_browser_unrendered_recaptcha_container_is_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = _stub_solver_agent(solves=False)
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+
+ async with _challenge_browser_page(_UNRENDERED_RECAPTCHA_HTML, expect_challenge_frame=False) as page:
+ assert await page.locator(captcha_solver_module._CAPTCHA_MARKER_SELECTOR).count() > 0
+
+ assert await solve_challenge_ladder(page) is False
+
+ agent_function.auto_solve_captchas.assert_not_awaited()
+ agent_function.solve_recaptcha_token.assert_not_awaited()
+
+
+@_skip_no_browser
+async def test_browser_hidden_recaptcha_badge_is_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A hidden v3 badge is a marker the site never shows, so it reads absent and the solver arms stay
+ unused; the run goes on to Submit and the site scores it itself."""
+ agent_function = _stub_solver_agent(solves=False)
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+
+ async with _challenge_browser_page(_HIDDEN_V3_BADGE_HTML, expect_challenge_frame=False) as page:
+ assert await page.locator(captcha_solver_module._CAPTCHA_MARKER_SELECTOR).count() > 0
+
+ assert await solve_challenge_ladder(page, probe_child_frames=True) is False
+
+ agent_function.auto_solve_captchas.assert_not_awaited()
+ agent_function.solve_recaptcha_token.assert_not_awaited()
+
+
+@_skip_no_browser
+async def test_browser_marker_below_the_fold_is_present(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A widget a long form scrolls to is a real gate, so page-level presence must not require the viewport."""
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+
+ async with _challenge_browser_page(_BELOW_THE_FOLD_RECAPTCHA_HTML, expect_challenge_frame=False) as page:
+ assert await solve_challenge_ladder(page) is True
+
+ agent_function.auto_solve_captchas.assert_awaited_once()
+
+
+@_skip_no_browser
+async def test_browser_rendered_marker_after_a_hidden_one_is_present(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+
+ async with _challenge_browser_page(_HIDDEN_THEN_RENDERED_RECAPTCHA_HTML, expect_challenge_frame=False) as page:
+ assert await solve_challenge_ladder(page) is True
+
+ agent_function.auto_solve_captchas.assert_awaited_once()
+
+
+@_skip_no_browser
+async def test_browser_hidden_hcaptcha_beside_a_rendered_turnstile_keeps_the_hcaptcha_budget(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Arm selection reads raw marker counts on purpose: once presence is settled, a page carrying any
+ hCaptcha still needs the longer image-challenge bound."""
+ agent_function = _stub_solver_agent()
+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)
+ resolve_calls: list[float] = []
+ monkeypatch.setattr(
+ agent_function,
+ "resolve_captcha_solver_extension_timeout",
+ lambda _page, default_timeout: resolve_calls.append(default_timeout) or default_timeout,
+ )
+
+ async with _challenge_browser_page(
+ _RENDERED_TURNSTILE_WITH_HIDDEN_HCAPTCHA_HTML, expect_challenge_frame=False
+ ) as page:
+ assert await solve_challenge_ladder(page) is True
+
+ assert resolve_calls == [captcha_solver_module._HCAPTCHA_ARM_TIMEOUT_SECONDS]
diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.py
index 8ba7760ce..18628de42 100644
--- a/tests/unit/test_code_block_downloads.py
+++ b/tests/unit/test_code_block_downloads.py
@@ -22,6 +22,7 @@ from unittest.mock import AsyncMock
import pytest
import structlog
+from playwright.async_api import Download
from structlog.testing import capture_logs
from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX
@@ -33,6 +34,7 @@ from skyvern.exceptions import (
)
from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.api.files import classify_download_visibility, observe_download_dir
+from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.artifact.storage import s3 as s3_module
from skyvern.forge.sdk.artifact.storage.s3 import S3Storage
from skyvern.forge.sdk.browser_network_egress_monitor import BrowserNetworkEgressMonitor
@@ -46,6 +48,7 @@ from skyvern.forge.sdk.core.http_request_authorization import RunScopedRedirectH
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.utils import downloaded_file_count_from_output
from skyvern.forge.sdk.schemas.files import FileInfo
+from skyvern.forge.sdk.workflow import code_block_authorized_files
from skyvern.forge.sdk.workflow.code_block_authorized_files import (
AuthorizedFileMaterializationFailure,
MaterializedAuthorizedFile,
@@ -62,6 +65,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (
from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding
from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptor
+from tests.unit.conftest import SESSION_DOWNLOAD_BYTES, make_claimed_download_mock, registered_download_row
from tests.unit.copilot_test_helpers import make_copilot_ctx
from tests.unit.scoped_asyncio import ScopedAsyncio
@@ -116,6 +120,7 @@ def _copilot_workflow() -> SimpleNamespace:
edited_by=None,
workflow_permanent_id="wpid_test",
organization_id="o_1",
+ workflow_definition=None,
)
@@ -849,6 +854,163 @@ async def test_two_file_inputs_sharing_a_basename_each_keep_their_own_bytes_and_
assert result.output_parameter_value["receipt"]["filename"] == "resume.pdf"
+async def test_a_setup_failure_stops_the_block_download_log_listening(
+ monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
+) -> None:
+ """The log starts before the setup awaits, and a page in a persistent session outlives the block, so a
+ setup failure has to stop it listening rather than leave it recording on that page."""
+ skyvern_context.set(SkyvernContext(organization_id="o_1", workflow_run_id="wr_1", run_id="wr_1"))
+ _fake_storage_app(monkeypatch, save=AsyncMock(), get=AsyncMock(return_value=[]))
+ _wire_block_runtime(monkeypatch)
+ listeners: list[Callable[[Download], None]] = []
+ registered: list[Callable[[Download], None]] = []
+
+ def on(event: str, handler: Callable[[Download], None]) -> None:
+ listeners.append(handler)
+ registered.append(handler)
+
+ context = SimpleNamespace(
+ pages=[],
+ on=on,
+ remove_listener=lambda event, handler: listeners.remove(handler) if handler in listeners else None,
+ )
+ monkeypatch.setattr(
+ CodeBlock,
+ "get_or_create_browser_state",
+ AsyncMock(
+ return_value=SimpleNamespace(
+ get_working_page=AsyncMock(return_value=SimpleNamespace(context=context, url="https://example.test/")),
+ browser_artifacts=BrowserArtifacts(download_binding=DownloadBinding.SESSION_DIR),
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ CodeBlock, "_ensure_run_recording_artifact", AsyncMock(side_effect=RuntimeError("setup failed"))
+ )
+ block = CodeBlock(label="code", code="result = 1", output_parameter=_output_parameter("code_out"))
+
+ with pytest.raises(BaseException):
+ await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+
+ assert registered, "the log never started listening, so this proves nothing"
+ assert listeners == []
+
+
+ "download_during", [None, "baseline-read", "secure-attempt"], ids=["alone", "baseline-read", "secure-attempt"]
+)
+async def test_an_inline_session_block_uploads_the_download_it_claimed_from_the_registered_artifact(
+ monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str, download_during: str | None
+) -> None:
+ """A persistent remote browser never writes the bytes to this worker, so the inline attach must be handed the
+ run's registered downloads to resolve the claim from. Block setup and the baseline read both await, so a
+ download that starts in either window is still logged and can still be the row's owner: refused, not
+ uploaded."""
+ skyvern_context.set(SkyvernContext(organization_id="o_1", workflow_run_id="wr_1", run_id="wr_1"))
+ monkeypatch.setattr(block_module.settings, "ARTIFACT_CONTENT_HMAC_KEYRING", "k1:secret")
+ session_bytes = SESSION_DOWNLOAD_BYTES
+ registered_row = registered_download_row()
+ registrations: list[list[FileInfo]] = [[]]
+ baseline_reads = 0
+
+ def read_registrations(**_: object) -> list[FileInfo]:
+ nonlocal baseline_reads
+ baseline_reads += 1
+ if download_during == "baseline-read" and baseline_reads == 2:
+ page.start_download("certificate (1).pdf")
+ return registrations[-1]
+
+ fake_app = _fake_storage_app(monkeypatch, save=AsyncMock(), get=AsyncMock(side_effect=read_registrations))
+ _wire_block_runtime(monkeypatch)
+ monkeypatch.setattr(
+ code_block_authorized_files,
+ "app",
+ SimpleNamespace(
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(
+ get_artifact_by_id=AsyncMock(
+ return_value=SimpleNamespace(artifact_type=ArtifactType.DOWNLOAD, run_id="wr_1")
+ )
+ )
+ ),
+ STORAGE=SimpleNamespace(retrieve_artifact=AsyncMock(return_value=session_bytes)),
+ ),
+ )
+ uploads: list[dict[str, str | bytes]] = []
+
+ class UploadTarget:
+ async def set_input_files(self, files: dict[str, str | bytes]) -> None:
+ uploads.append(files)
+
+ class SessionPage:
+ url = "https://example.test/"
+
+ def __init__(self) -> None:
+ self.download_handlers: list[Callable[[Download], None]] = []
+ self.context = SimpleNamespace(pages=[self], on=lambda *_: None, remove_listener=lambda *_: None)
+
+ def on(self, event: str, handler: Callable[[Download], None]) -> None:
+ if event == "download":
+ self.download_handlers.append(handler)
+
+ def remove_listener(self, event: str, handler: Callable[[Download], None]) -> None:
+ if handler in self.download_handlers:
+ self.download_handlers.remove(handler)
+
+ def locator(self, selector: str) -> UploadTarget:
+ return UploadTarget()
+
+ def start_download(self, suggested_filename: str) -> Download:
+ download = make_claimed_download_mock(
+ path=None, suggested_filename=suggested_filename, path_error=RuntimeError("remote browser")
+ )
+ for handler in list(self.download_handlers):
+ handler(download)
+ return download
+
+ async def download_certificate(self) -> Download:
+ download = self.start_download("certificate.pdf")
+ registrations.append([registered_row])
+ return download
+
+ page = SessionPage()
+ if download_during == "secure-attempt":
+
+ async def secure_attempt_then_downgrade(**_: object) -> None:
+ page.start_download("certificate (1).pdf")
+ return None
+
+ fake_app.AGENT_FUNCTION.should_use_codeblock_runner = AsyncMock(return_value=True)
+ fake_app.AGENT_FUNCTION.execute_code_block_override = secure_attempt_then_downgrade
+ monkeypatch.setattr(
+ CodeBlock,
+ "get_or_create_browser_state",
+ AsyncMock(
+ return_value=SimpleNamespace(
+ get_working_page=AsyncMock(return_value=page),
+ browser_artifacts=BrowserArtifacts(download_binding=DownloadBinding.SESSION_DIR),
+ )
+ ),
+ )
+
+ block = CodeBlock(
+ label="code_upload",
+ code='receipt = await attach_authorized_file(page, await page.download_certificate(), "#file")',
+ output_parameter=_output_parameter("code_out"),
+ )
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+
+ if download_during is not None:
+ assert result.success is False
+ assert uploads == []
+ return
+ assert result.success is True, result.failure_reason
+ assert result.output_parameter_value["receipt"] == {"filename": "certificate.pdf", "size": len(session_bytes)}
+ assert [(upload["name"], upload["buffer"]) for upload in uploads] == [("certificate.pdf", session_bytes)]
+
+
@pytest.mark.asyncio
async def test_a_parameter_named_after_the_attach_helper_still_wins(
monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 9ce31c9e5..b1cd24561 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -32,6 +32,7 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutError
import skyvern.forge.sdk.workflow.models.block as block_module
from skyvern.config import settings
from skyvern.forge.sdk.copilot.code_block_security import rendering_introduced_security_errors
+from skyvern.forge.sdk.schemas.totp_codes import OTPType
from skyvern.forge.sdk.workflow.code_block_safety import (
ALWAYS_DENIED_BUILTINS,
SANDBOX_ONLY_BUILTINS,
@@ -47,7 +48,10 @@ from skyvern.forge.sdk.workflow.models.block import (
CODE_BLOCK_TAB_OPEN_FAILURE_REASON,
BranchEvaluationContext,
CodeBlock,
+ CodeBlockOTPError,
_bind_code_block_set_dialog_policy,
+ _resolve_code_block_otp,
+ _resolve_code_block_otp_for_identifier,
)
from skyvern.forge.sdk.workflow.models.credential_release import (
CodeBlockCredentialReleaseError,
@@ -61,6 +65,13 @@ from skyvern.forge.sdk.workflow.models.parameter import (
WorkflowParameterType,
)
from skyvern.schemas.workflows import BlockStatus
+from skyvern.services.otp_email import (
+ MAX_SEEN_EMAIL_MESSAGE_IDS,
+ EmailOTPVerificationContext,
+ GmailOTPSource,
+ OutlookOTPSource,
+)
+from skyvern.services.otp_service import RawOTPVerificationContext
from skyvern.webeye import dialog_handler
from skyvern.webeye.browser_artifacts import BrowserArtifacts
from skyvern.webeye.skycdp.errors import CdpError
@@ -1998,6 +2009,9 @@ class TestCodeBlockOtpIdentifierFetch:
assert link in set(wrc.secrets.values())
+_FillContexts = Callable[[EmailOTPVerificationContext, RawOTPVerificationContext], None]
+
+
class TestCodeBlockOtpBudget:
"""AC2: the in-block poll budget raises a clear error, not the opaque 300s kill."""
@@ -2081,6 +2095,354 @@ class TestCodeBlockOtpBudget:
await _resolve_code_block_otp(_CREDENTIAL_KEY, _ORG_ID, _WORKFLOW_RUN_ID, budget_seconds=120)
assert "[email protected]" not in str(exc_info.value)
+ @staticmethod
+ async def _timeout_after(monkeypatch: pytest.MonkeyPatch, fill_contexts: _FillContexts, identifier: str) -> str:
+ _patch_context_resolution(monkeypatch, _build_wrc_with_identifier(identifier=identifier))
+
+ async def fake_get_workflow_run(*args: object, **kwargs: object) -> _FakeWorkflowRun:
+ return _FakeWorkflowRun()
+
+ async def fake_poll(**kwargs: object):
+ fill_contexts(kwargs["email_context"], kwargs["raw_context"])
+ raise asyncio.TimeoutError
+
+ monkeypatch.setattr(
+ block_module.app.DATABASE.workflow_runs, "get_workflow_run", fake_get_workflow_run, raising=False
+ )
+ monkeypatch.setattr(block_module.otp_service, "poll_otp_value", fake_poll)
+ with pytest.raises(CodeBlockOTPError) as exc_info:
+ await _resolve_code_block_otp(_CREDENTIAL_KEY, _ORG_ID, _WORKFLOW_RUN_ID, budget_seconds=120)
+ return str(exc_info.value)
+
+ @staticmethod
+ def _no_inboxes(email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext) -> None:
+ email_context.for_source(GmailOTPSource.name).credential_ids = []
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _gmail_never_loaded(email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext) -> None:
+ email_context.for_source(GmailOTPSource.name)
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _one_gmail_inbox_seven_messages(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ for index in range(7):
+ gmail.remember_message("cred_1", f"msg_{index}")
+ gmail.completed_credential_ids.add("cred_1")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _one_gmail_inbox_past_the_cap(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ for index in range(MAX_SEEN_EMAIL_MESSAGE_IDS + 5):
+ gmail.remember_message("cred_1", f"msg_{index}")
+ gmail.completed_credential_ids.add("cred_1")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _nothing_consulted(email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext) -> None:
+ return None
+
+ @staticmethod
+ def _one_gmail_inbox_search_failed(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ gmail.failed_credential_ids.add("cred_1")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _one_gmail_inbox_unreadable_message(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ gmail.unreadable_message_keys.update({("cred_1", "msg_a"), ("cred_1", "msg_b")})
+ gmail.completed_credential_ids.add("cred_1")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _one_gmail_inbox_search_cancelled(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _two_gmail_inboxes_one_still_searching(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_done", "cred_pending"]
+ gmail.completed_credential_ids.add("cred_done")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _two_gmail_inboxes_one_answered_one_pending(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_done", "cred_pending"]
+ gmail.completed_credential_ids.add("cred_done")
+ for index in range(3):
+ gmail.remember_message("cred_done", f"msg_{index}")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _one_gmail_inbox_read_some_and_refused_one(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ gmail.completed_credential_ids.add("cred_1")
+ for index in range(3):
+ gmail.remember_message("cred_1", f"msg_{index}")
+ gmail.unreadable_message_keys.add(("cred_1", "msg_refused"))
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _gmail_inbox_replaced_after_reading(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ for index in range(3):
+ gmail.remember_message("cred_gone", f"msg_{index}")
+ gmail.unreadable_message_keys.add(("cred_gone", "msg_refused"))
+ gmail.credential_ids = ["cred_new"]
+ gmail.completed_credential_ids.add("cred_new")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _gmail_list_went_stale(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = []
+ gmail.credential_list_refresh_failed = True
+ outlook = email_context.for_source(OutlookOTPSource.name)
+ outlook.credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _evicted_then_one_inbox_disconnected(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ for index in range(MAX_SEEN_EMAIL_MESSAGE_IDS):
+ gmail.remember_message("cred_kept", f"kept_{index}")
+ for index in range(100):
+ gmail.remember_message("cred_gone", f"gone_{index}")
+ gmail.credential_ids = ["cred_kept"]
+ gmail.completed_credential_ids.add("cred_kept")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _gmail_inbox_searched_then_failed(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ gmail.completed_credential_ids.add("cred_1")
+ gmail.failed_credential_ids.add("cred_1")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _one_gmail_inbox_one_message(
+ email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext
+ ) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ gmail.completed_credential_ids.add("cred_1")
+ gmail.remember_message("cred_1", "msg_only")
+ email_context.for_source(OutlookOTPSource.name).credential_ids = []
+ raw_context.store_queried = True
+
+ @staticmethod
+ def _store_queried_only(email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext) -> None:
+ raw_context.store_queried = True
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("identifier", "fill_contexts", "present", "absent"),
+ [
+ (
+ _no_inboxes,
+ ["No Gmail or Outlook inbox is connected", "no code has been stored"],
+ [],
+ ),
+ (
+ _gmail_never_loaded,
+ ["Gmail inbox list never loaded", "no Outlook inbox connected"],
+ ["no Gmail inbox"],
+ ),
+ ("[email protected]", _one_gmail_inbox_seven_messages, ["1 Gmail inbox connected, 7 messages checked"], []),
+ (
+ _one_gmail_inbox_past_the_cap,
+ ["1 Gmail inbox connected, 500+ messages checked"],
+ ["505 messages"],
+ ),
+ (
+ _one_gmail_inbox_search_failed,
+ ["0 of 1 Gmail inbox searched, search failed"],
+ ["no messages read", "messages checked"],
+ ),
+ (
+ _one_gmail_inbox_unreadable_message,
+ ["1 Gmail inbox connected, 2 messages could not be read"],
+ ["no messages read", "search failed"],
+ ),
+ (
+ _one_gmail_inbox_search_cancelled,
+ ["0 of 1 Gmail inbox searched, no messages read"],
+ ["1 Gmail inbox connected", "search failed"],
+ ),
+ (
+ _two_gmail_inboxes_one_still_searching,
+ ["1 of 2 Gmail inboxes searched, no messages read"],
+ ["2 Gmail inboxes connected"],
+ ),
+ (
+ _two_gmail_inboxes_one_answered_one_pending,
+ ["1 of 2 Gmail inboxes searched, 3 messages checked"],
+ ["2 Gmail inboxes connected"],
+ ),
+ (
+ _one_gmail_inbox_read_some_and_refused_one,
+ ["1 Gmail inbox connected, 3 of 4 messages read"],
+ ["3 messages checked"],
+ ),
+ (
+ _gmail_inbox_replaced_after_reading,
+ ["1 Gmail inbox connected, no messages read"],
+ ["3 messages", "of 4 messages", "could not be read"],
+ ),
+ (
+ _gmail_list_went_stale,
+ ["Gmail inbox list not refreshed", "no Outlook inbox connected"],
+ ["no Gmail inbox connected", "No Gmail or Outlook inbox is connected"],
+ ),
+ (
+ _evicted_then_one_inbox_disconnected,
+ ["1 Gmail inbox connected, 400+ messages checked"],
+ ["400 messages checked"],
+ ),
+ (
+ _gmail_inbox_searched_then_failed,
+ ["1 Gmail inbox connected, search failed"],
+ ["no messages read", "0 of 1"],
+ ),
+ (
+ _one_gmail_inbox_one_message,
+ ["1 Gmail inbox connected, 1 message checked"],
+ ["1 messages checked"],
+ ),
+ (
+ _nothing_consulted,
+ ["No delivery source was checked before the wait ended."],
+ ["No Gmail or Outlook inbox is connected", "no code has been stored"],
+ ),
+ (
+ "+15555550147",
+ _store_queried_only,
+ ["no code has been stored"],
+ ["Gmail", "Outlook", "inbox"],
+ ),
+ ],
+ ids=[
+ "zero-sources",
+ "never-loaded",
+ "one-inbox",
+ "capped-inbox",
+ "search-failed",
+ "unreadable",
+ "search-cancelled",
+ "one-of-two-pending",
+ "partial-with-messages",
+ "read-some-refused-one",
+ "inbox-replaced",
+ "list-stale",
+ "evicted-then-disconnected",
+ "searched-then-failed",
+ "one-message-singular",
+ "nothing-queried",
+ "sms-identifier",
+ ],
+ )
+ async def test_timeout_names_the_sources_it_checked(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ identifier: str,
+ fill_contexts: _FillContexts,
+ present: list[str],
+ absent: list[str],
+ ) -> None:
+ message = await self._timeout_after(monkeypatch, fill_contexts, identifier)
+
+ assert message != "OTP was not received within 120 seconds."
+ assert message.endswith("OTP was not received within 120 seconds.")
+ # Every downstream cap slices a prefix, the shortest being 120 chars in copilot turn
+ # compaction, applied after a ~45-char platform frame. The facts have to fit what is left.
+ for fact in present:
+ assert message.index(fact) + len(fact) <= 75
+ for fact in present:
+ assert fact in message
+ for fact in absent:
+ assert fact not in message
+
+ @pytest.mark.asyncio
+ async def test_timeout_sources_render_counts_only(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def fill_contexts(email_context: EmailOTPVerificationContext, raw_context: RawOTPVerificationContext) -> None:
+ gmail = email_context.for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_redact_91c2"]
+ gmail.remember_message("cred_redact_91c2", "msg_redact_44d0")
+ gmail.provider_state["cred_redact_91c2"] = {"last_code": "918273"}
+ raw_context.seen_row_ids.add("otp_row_redact_5e1b")
+ raw_context.misses.add(("otp_row_redact_5e1b", OTPType.TOTP))
+ raw_context.store_queried = True
+
+ message = await self._timeout_after(monkeypatch, fill_contexts, "[email protected]")
+
+ assert "1 stored OTP message found" in message
+ for secret in ("[email protected]", "cred_redact_91c2", "msg_redact_44d0", "918273", "otp_row"):
+ assert secret not in message
+
class TestCodeBlockOtpNoSource:
"""A credential with neither a seed nor an identifier raises a clear error."""
@@ -2319,6 +2681,25 @@ class TestCodeBlockOtpForIdentifier:
assert result == "445566"
assert result.strip() == "445566"
+ @pytest.mark.asyncio
+ async def test_sms_identifier_timeout_names_no_mailbox(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ wrc = _build_wrc_with_identifier(identifier="+15555550147")
+ self._patch_poll(monkeypatch, wrc, None)
+
+ async def timing_out_poll(**kwargs: object) -> NoReturn:
+ kwargs["raw_context"].store_queried = True
+ raise asyncio.TimeoutError
+
+ monkeypatch.setattr(block_module.otp_service, "poll_otp_value", timing_out_poll)
+
+ with pytest.raises(CodeBlockOTPError) as exc_info:
+ await _resolve_code_block_otp_for_identifier("+15555550147", _ORG_ID, _WORKFLOW_RUN_ID, budget_seconds=120)
+
+ message = str(exc_info.value)
+ assert "no code has been stored" in message
+ for mailbox_word in ("Gmail", "Outlook", "inbox"):
+ assert mailbox_word not in message
+
@pytest.mark.asyncio
async def test_builtin_routes_a_string_to_the_identifier_path(self, monkeypatch: pytest.MonkeyPatch) -> None:
from skyvern.forge.sdk.workflow.models.block import CodeBlock as _CB
@@ -2753,6 +3134,37 @@ class TestCodeBlockMagicLink:
assert "totp" in message
assert "otp()" in message
+ @pytest.mark.asyncio
+ async def test_an_unqueried_store_names_the_link_it_was_waiting_for(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ import asyncio
+
+ from skyvern.forge.sdk.workflow.models import block as block_module
+ from skyvern.forge.sdk.workflow.models.block import CodeBlockOTPError, _bind_code_block_magic_link
+
+ wrc = _build_wrc_with_identifier()
+ _patch_context_resolution(monkeypatch, wrc)
+
+ async def fake_get_workflow_run(*args: object, **kwargs: object) -> _FakeWorkflowRun:
+ return _FakeWorkflowRun()
+
+ async def fake_poll(**kwargs: object):
+ gmail = kwargs["email_context"].for_source(GmailOTPSource.name)
+ gmail.credential_ids = ["cred_1"]
+ gmail.completed_credential_ids.add("cred_1")
+ raise asyncio.TimeoutError
+
+ monkeypatch.setattr(
+ block_module.app.DATABASE.workflow_runs, "get_workflow_run", fake_get_workflow_run, raising=False
+ )
+ monkeypatch.setattr(block_module.otp_service, "poll_otp_value", fake_poll)
+
+ with pytest.raises(CodeBlockOTPError) as excinfo:
+ await _bind_code_block_magic_link(_CREDENTIAL_KEY, _ORG_ID, _WORKFLOW_RUN_ID)(_fake_code_block_page())
+
+ message = str(excinfo.value)
+ assert "stored sign-in links not checked" in message
+ assert "stored codes not checked" not in message
+
@pytest.mark.asyncio
async def test_code_verb_against_a_link_mailbox_reports_the_mismatch_too(
self, monkeypatch: pytest.MonkeyPatch
@@ -2800,6 +3212,7 @@ class TestCodeBlockMagicLink:
return _FakeWorkflowRun()
async def fake_poll(**kwargs: object):
+ kwargs["raw_context"].store_queried = True
raise asyncio.TimeoutError
monkeypatch.setattr(
@@ -2809,9 +3222,13 @@ class TestCodeBlockMagicLink:
page = _fake_code_block_page()
- with pytest.raises(CodeBlockOTPError, match="was not received within"):
+ with pytest.raises(CodeBlockOTPError, match="was not received within") as exc_info:
await _bind_code_block_magic_link(_CREDENTIAL_KEY, _ORG_ID, _WORKFLOW_RUN_ID)(page)
+ message = str(exc_info.value)
+ assert "no sign-in link has been stored" in message
+ assert "code has been stored" not in message
+
@pytest.mark.asyncio
async def test_a_page_of_the_blocks_own_making_is_refused_before_polling(
self, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/test_codeblock_machinery_exception_reason.py b/tests/unit/test_codeblock_machinery_exception_reason.py
new file mode 100644
index 000000000..5de8556b5
--- /dev/null
+++ b/tests/unit/test_codeblock_machinery_exception_reason.py
@@ -0,0 +1,136 @@
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from structlog.testing import capture_logs
+
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.workflow.models.block import Block, CodeBlock, ForLoopBlock
+from skyvern.forge.sdk.workflow.models.code_block_recorder import CODE_BLOCK_FILENAME, CODE_LINE_OFFSET
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
+from tests.unit.test_block_description_caching import _setup_mocks
+
+SENTINEL = "secret-param-value"
+USER_SOURCE_MARKER = "user_source_marker_line"
+USER_CODE_LINE = 3
+LEAKY_NAME = "LeakyUnboundError"
+
+
+class SecretError(Exception):
+ __module__ = "skyvern.code_block"
+
+
+def _output_parameter() -> OutputParameter:
+ now = datetime.now(UTC)
+ return OutputParameter(output_parameter_id="op_1", key="out", workflow_id="wf_1", created_at=now, modified_at=now)
+
+
+async def _raise_from_user_code_frame(*args: object, **kwargs: object) -> None:
+ source = "\n".join(
+ [f"{USER_SOURCE_MARKER} = 1", *[""] * (CODE_LINE_OFFSET + USER_CODE_LINE - 2), f"raise KeyError({SENTINEL!r})"]
+ )
+ exec(compile(source, CODE_BLOCK_FILENAME, "exec"), {})
+
+
+async def _raise_user_defined(*args: object, **kwargs: object) -> None:
+ raise SecretError(SENTINEL)
+
+
+async def _raise_index_error(*args: object, **kwargs: object) -> None:
+ raise IndexError(SENTINEL)
+
+
+async def _raise_unbound_class(*args: object, **kwargs: object) -> None:
+ raise type(LEAKY_NAME, (RuntimeError,), {})(SENTINEL)
+
+
+def _code_block() -> Block:
+ return CodeBlock(label="code_1", code="return 1", output_parameter=_output_parameter())
+
+
+def _loop_block() -> Block:
+ return ForLoopBlock(label="loop_1", output_parameter=_output_parameter(), loop_over=None, loop_blocks=[])
+
+
+ ("make_block", "target", "raiser", "expected_reason", "expected_class", "expected_line", "withheld_name"),
+ [
+ (
+ _code_block,
+ (CodeBlock, "_execute"),
+ _raise_from_user_code_frame,
+ f"CodeBlock failed with KeyError inside Skyvern while running line {USER_CODE_LINE}.",
+ "builtins.KeyError",
+ USER_CODE_LINE,
+ None,
+ ),
+ (
+ _code_block,
+ (CodeBlock, "_execute"),
+ _raise_user_defined,
+ "CodeBlock failed inside Skyvern.",
+ None,
+ None,
+ "SecretError",
+ ),
+ (
+ _loop_block,
+ (ForLoopBlock, "execute"),
+ _raise_index_error,
+ "Loop block failed with IndexError.",
+ "builtins.IndexError",
+ None,
+ None,
+ ),
+ (
+ _code_block,
+ (CodeBlock, "_execute"),
+ _raise_unbound_class,
+ "CodeBlock failed inside Skyvern.",
+ None,
+ None,
+ LEAKY_NAME,
+ ),
+ ],
+ ids=["builtin-with-user-code-frame", "user-defined-class-withheld", "loop-block", "unbound-class-withheld"],
+)
+async def test_machinery_failure_reason_and_log_fields(
+ make_block, target, raiser, expected_reason, expected_class, expected_line, withheld_name
+) -> None:
+ block = make_block()
+ with (
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ patch.object(*target, new=raiser),
+ patch.object(Block, "record_output_parameter_value", new_callable=AsyncMock),
+ patch.object(Block, "_generate_workflow_run_block_description", new_callable=AsyncMock),
+ capture_logs() as logs,
+ ):
+ _setup_mocks(mock_app)
+ mock_app.AGENT_FUNCTION.prepare_codeblock_control_flow_exception.side_effect = (
+ AgentFunction().prepare_codeblock_control_flow_exception
+ )
+ mock_app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled.return_value = False
+ mock_app.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts.return_value = []
+
+ result = await block.execute_safe(workflow_run_id="wr_1")
+
+ assert result.success is False
+ assert result.failure_reason == expected_reason
+
+ events = [e for e in logs if e["event"].endswith("execution failed")]
+ assert len(events) == 1
+ event = events[0]
+ assert "exc_info" not in event
+ assert event["exception_class"] == expected_class
+ assert event["failing_line"] == expected_line
+ assert event["stack"]
+ if expected_line is not None:
+ assert f"{CODE_BLOCK_FILENAME}:{expected_line}" in event["stack"]
+ assert any("block.py" in frame for frame in event["stack"])
+
+ leaked = repr(logs) + result.failure_reason
+ assert SENTINEL not in leaked
+ assert USER_SOURCE_MARKER not in leaked
+ if withheld_name:
+ assert withheld_name not in leaked
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index a3828770d..eb64e9301 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -36,8 +36,10 @@ from skyvern.forge.sdk.copilot.agent import (
_SKYVERN_EGRESS_FOLLOW_UP,
_build_goal_satisfied_exit_result,
_format_chat_history,
+ _last_recorded_run_id,
_resolve_wrapped_exception_exit_result,
_rewrite_failed_test_response,
+ _run_to_inherit,
_verified_workflow_or_none,
)
from skyvern.forge.sdk.copilot.blocker_signal import (
@@ -152,6 +154,7 @@ from skyvern.services import workflow_service as workflow_service_module
from skyvern.utils.yaml_loader import safe_load_no_dates
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus
+from tests.unit.copilot_route_test_support import narrative_payload_with_run
from tests.unit.copilot_test_helpers import failed_second_factor_run
from tests.unit.copilot_test_helpers import make_copilot_ctx as _ctx
from tests.unit.copilot_test_helpers import make_verified_goal_contract as _verified_goal_contract
@@ -219,6 +222,48 @@ def _history(*pairs: tuple[str, str]) -> list[WorkflowCopilotChatHistoryMessage]
]
+def _ai_turn_with_run(run_id: str | None) -> WorkflowCopilotChatHistoryMessage:
+ return WorkflowCopilotChatHistoryMessage(
+ sender=WorkflowCopilotChatSender("ai"),
+ content="ran the draft",
+ created_at=_HISTORY_SENTINEL_TS,
+ narrative_payload=narrative_payload_with_run(run_id), # type: ignore[arg-type]
+ )
+
+
+def test_the_last_recorded_run_survives_the_prompt_window() -> None:
+ """The prompt slice is not the source: a run further back is still the chat's last run."""
+ messages = [_ai_turn_with_run("wr_older"), *_history(*[("user", "keep going")] * 20)]
+
+ assert _last_recorded_run_id(messages) == "wr_older"
+
+
+def test_the_newest_recorded_run_wins_and_a_user_turn_records_none() -> None:
+ messages = [_ai_turn_with_run("wr_older"), _ai_turn_with_run("wr_newer"), _ai_turn_with_run(None)]
+
+ assert _last_recorded_run_id(messages) == "wr_newer"
+ assert _last_recorded_run_id(_history(("user", "hello"))) is None
+
+
+ ("requested", "proposal", "recorded", "expected"),
+ [
+ pytest.param("wr_named", "wr_proposal", ["wr_proposal", "wr_fresh"], "wr_named", id="caller-named-run-wins"),
+ pytest.param(None, "wr_proposal", ["wr_proposal", "wr_fresh"], "wr_fresh", id="later-fresh-test-wins"),
+ pytest.param(None, "wr_proposal", ["wr_older", "wr_proposal"], "wr_proposal", id="proposal-is-newest"),
+ pytest.param(None, "wr_proposal", ["wr_other"], "wr_proposal", id="unrecorded-proposal-keeps-claim"),
+ pytest.param(None, None, ["wr_older", "wr_fresh"], "wr_fresh", id="no-proposal"),
+ pytest.param(None, None, [], None, id="nothing-recorded"),
+ ],
+)
+def test_last_run_inherits_the_most_recent_test(
+ requested: str | None, proposal: str | None, recorded: list[str], expected: str | None
+) -> None:
+ messages = [_ai_turn_with_run(run_id) for run_id in recorded]
+
+ assert _run_to_inherit(requested, proposal, messages) == expected
+
+
def test_a_product_row_speaks_as_the_user_in_the_formatted_history() -> None:
formatted = _format_chat_history(
_history(
@@ -308,6 +353,7 @@ def _challenge_failure_ctx() -> CopilotContext:
@pytest.mark.asyncio
[email protected]("later_fresh_test", [False, True], ids=["no-later-test", "later-fresh-test"])
@pytest.mark.parametrize(
(
"product_action",
@@ -364,6 +410,7 @@ async def test_interrupted_draft_turn_restoration_and_run_hydration_stay_coheren
expected_workflow_yaml: str,
expected_run_id: str,
expected_proposal_run_id: str | None,
+ later_fresh_test: bool,
) -> None:
class FakeMCPServerManager:
def __init__(self, servers: list[object]) -> None:
@@ -422,6 +469,9 @@ async def test_interrupted_draft_turn_restoration_and_run_hydration_stay_coheren
product_action=product_action,
),
chat_history=[],
+ prior_user_messages=[_ai_turn_with_run("wr_candidate"), _ai_turn_with_run("wr_fresh")]
+ if later_fresh_test
+ else [],
global_llm_context=None,
llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),
raw_secret_safety_handler=AsyncMock(
@@ -431,9 +481,10 @@ async def test_interrupted_draft_turn_restoration_and_run_hydration_stay_coheren
config=CopilotConfig(),
)
+ expected_seed_run_id = "wr_fresh" if later_fresh_test and request_run_id is None else expected_run_id
assert result.user_response == "ok"
assert restored_run_ids == [expected_restore_run_id]
- assert seeded == [(expected_run_id, expected_workflow_yaml, expected_proposal_run_id)]
+ assert seeded == [(expected_seed_run_id, expected_workflow_yaml, expected_proposal_run_id)]
assert hydrated == [(expected_run_id, expected_workflow_yaml, expected_proposal_run_id)]
assert build_context.call_args.kwargs["workflow_yaml"] == expected_workflow_yaml
@@ -7942,6 +7993,7 @@ def test_rewrite_names_the_sandbox_outage_when_the_runner_was_unreachable() -> N
last_failure_category_top="UNRECOVERABLE_TOOL_ERROR",
last_run_blocks_workflow_run_id="wr_runner",
)
+ ctx.dispatched_run_ids_this_turn.add("wr_runner")
rewritten = _rewrite_failed_test_response("All set — the workflow is ready.", ctx)
@@ -7951,6 +8003,21 @@ def test_rewrite_names_the_sandbox_outage_when_the_runner_was_unreachable() -> N
)
+def test_an_inherited_run_id_does_not_claim_this_turn_executed() -> None:
+ """The run the turn inherited is not a run it started, so the reply still says nothing ran."""
+ ctx = _ctx(
+ last_update_block_count=1,
+ last_test_ok=False,
+ last_test_failure_reason="Secure CodeBlock runner is unavailable. Please retry.",
+ last_failure_category_top="UNRECOVERABLE_TOOL_ERROR",
+ last_run_blocks_workflow_run_id="wr_prior_turn",
+ )
+
+ rewritten = _rewrite_failed_test_response("All set — the workflow is ready.", ctx)
+
+ assert "Nothing was executed" in rewritten
+
+
class _ShapeBlock:
def __init__(self, label: str, code: str) -> None:
self.label = label
diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.py
index 0247958c5..dec6e5053 100644
--- a/tests/unit/test_copilot_banned_block_policy.py
+++ b/tests/unit/test_copilot_banned_block_policy.py
@@ -84,6 +84,7 @@ def _ctx(prior_yaml: str | None = None) -> MagicMock:
ctx.code_authoring_guardrail_reject_count = 0
ctx.recorded_build_test_outcome_history = []
ctx.request_policy = RequestPolicy(allow_update_workflow=True, allow_run_blocks=True)
+ ctx.credential_origin_recovery = None
return ctx
@@ -552,6 +553,7 @@ def test_code_schema_guidance_advertises_only_the_authorized_file_attachment_hel
guidance = " ".join(_code_only_browser_schema_guidance())
assert "attach_authorized_file(page, <file_parameter>, <observed_selector>)" in guidance
+ assert "pass await info.value to the same helper" in guidance
assert "set_input_files" not in guidance
diff --git a/tests/unit/test_copilot_candidate_navigation_guard.py b/tests/unit/test_copilot_candidate_navigation_guard.py
index 490f323d7..47dba260e 100644
--- a/tests/unit/test_copilot_candidate_navigation_guard.py
+++ b/tests/unit/test_copilot_candidate_navigation_guard.py
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock
import pytest
-from skyvern.forge.sdk.copilot import mcp_adapter
+from skyvern.forge.sdk.copilot import mcp_adapter, runtime
from skyvern.forge.sdk.copilot.mcp_adapter import SkyvernOverlayMCPServer
from skyvern.webeye.real_browser_state import RealBrowserState
@@ -178,6 +178,97 @@ def _server() -> SkyvernOverlayMCPServer:
)
+async def test_candidate_guard_serializes_session_provisioning_with_source_promotion(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recovery_lock = asyncio.Lock()
+ ctx = SimpleNamespace(
+ browser_session_id=None,
+ browser_session_recovery_lock=recovery_lock,
+ browser_session_recovery_owner=None,
+ browser_session_recovery_depth=0,
+ organization_id="org",
+ )
+ ensure_started = asyncio.Event()
+ browser_context = _BrowserContext()
+
+ async def provision(_ctx):
+ ensure_started.set()
+ return None
+
+ async def resolve(_ctx):
+ return _BrowserState(browser_context)
+
+ monkeypatch.setattr(runtime, "_provision_browser_session", provision)
+ monkeypatch.setattr(mcp_adapter, "ensure_browser_session", runtime.ensure_browser_session)
+ monkeypatch.setattr(mcp_adapter, "resolve_browser_state_for_context", resolve)
+ monkeypatch.setattr(mcp_adapter.app, "AGENT_FUNCTION", _AgentFunction())
+ server = _server()
+ server._context_provider = lambda: ctx
+
+ await recovery_lock.acquire()
+
+ async def enter_guard() -> None:
+ async with server.evidence_candidate_navigation_guard("https://public.test"):
+ pass
+
+ guard_task = asyncio.create_task(enter_guard())
+ await asyncio.sleep(0)
+ assert not ensure_started.is_set()
+
+ recovery_lock.release()
+ await guard_task
+ assert ensure_started.is_set()
+
+
+async def test_candidate_guard_serializes_direct_session_retirement_with_source_promotion(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recovery_lock = asyncio.Lock()
+ ctx = SimpleNamespace(
+ browser_session_id="session",
+ browser_session_recovery_lock=recovery_lock,
+ browser_session_recovery_owner=None,
+ browser_session_recovery_depth=0,
+ organization_id="org",
+ )
+ resolve_started = asyncio.Event()
+ allow_resolve = asyncio.Event()
+
+ async def ensure(_ctx):
+ return None
+
+ async def resolve(_ctx):
+ resolve_started.set()
+ await allow_resolve.wait()
+ return None
+
+ monkeypatch.setattr(mcp_adapter, "ensure_browser_session", ensure)
+ monkeypatch.setattr(mcp_adapter, "resolve_browser_state_for_context", resolve)
+ monkeypatch.setattr(mcp_adapter, "retire_browser_session_id", runtime.retire_browser_session_id)
+ server = _server()
+ server._context_provider = lambda: ctx
+
+ async def enter_guard() -> None:
+ async with server.evidence_candidate_navigation_guard("https://public.test"):
+ pass
+
+ guard_task = asyncio.create_task(enter_guard())
+ await resolve_started.wait()
+ await recovery_lock.acquire()
+ allow_resolve.set()
+ await asyncio.sleep(0)
+ assert ctx.browser_session_id == "session"
+ assert not guard_task.done()
+
+ recovery_lock.release()
+ with pytest.raises(RuntimeError, match="requires a browser context"):
+ await guard_task
+ assert ctx.browser_session_id is None
+
+
@pytest.mark.asyncio
async def test_candidate_guard_uses_disposable_service_worker_blocked_context_for_attached_cdp(
monkeypatch: pytest.MonkeyPatch,
@@ -561,6 +652,9 @@ async def test_real_adapter_internal_call_drains_candidate_network_before_return
server._context_provider = lambda: SimpleNamespace(
browser_session_id="session",
browser_session_continuity_generation=0,
+ browser_session_recovery_lock=asyncio.Lock(),
+ browser_session_recovery_owner=None,
+ browser_session_recovery_depth=0,
organization_id="org",
turn_origin=mcp_adapter.TurnOrigin.interactive,
)
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index b21f9bcea..f2616c5c7 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -24,8 +24,10 @@ from skyvern.forge.sdk.copilot.request_policy import (
CompletionCriterion,
RequestPolicy,
)
+from skyvern.forge.sdk.copilot.runtime import CredentialOriginRecovery, CredentialOriginRecoveryState
from skyvern.forge.sdk.copilot.secret_scrub import REDACTED_SECRET_PLACEHOLDER, register_secret_scrub_value
from skyvern.forge.sdk.copilot.tools import workflow_update as workflow_update_module
+from skyvern.forge.sdk.copilot.tools.guardrails import _authority_tool_error
from skyvern.forge.sdk.copilot.tools.workflow_update import (
READINESS_WAIT_ADVISORY_REASON_CODE,
WRAPPER_SCOPE_ADVISORY_REASON_CODE,
@@ -170,6 +172,25 @@ async def test_concurrent_writes_stash_their_diffs_under_their_own_call_id(
assert [d["label"] for d in ctx.pending_code_write_diffs["c2"]] == ["beta"]
[email protected]("state", ["pending", "asked", "declined"])
+async def test_origin_recovery_withdraws_neither_the_save_nor_the_run(
+ monkeypatch: pytest.MonkeyPatch, state: CredentialOriginRecoveryState
+) -> None:
+ persisted: list[str] = []
+ _stub_successful_update(monkeypatch, persisted)
+ ctx = _ctx()
+ ctx.credential_origin_recovery = CredentialOriginRecovery("https://idp.example.test", state, "cred_service")
+ submitted = _code_yaml('return {"output": {"ok": True}}')
+
+ result = await _update_workflow({"workflow_yaml": submitted, "code_artifact_metadata": []}, ctx)
+
+ assert result["ok"] is True
+ assert persisted == [submitted]
+ for tool_name in ("run_blocks_and_collect_debug", "edit_block_and_run", "update_and_run_blocks"):
+ assert _authority_tool_error(ctx, tool_name) is None
+
+
@pytest.mark.asyncio
async def test_accept_path_persists_model_yaml_and_code_exactly(monkeypatch: pytest.MonkeyPatch) -> None:
persisted: list[str] = []
@@ -735,6 +756,57 @@ async def test_registered_live_secret_is_redacted_at_hard_safety_boundary(monkey
assert secret not in json.dumps(result["data"])
+async def test_exact_source_promotion_persists_when_the_code_is_unchanged(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ persisted: list[str] = []
+ _stub_successful_update(monkeypatch, persisted)
+ ctx = _ctx()
+ source = 'await page.locator("#submit").click()\n'
+ submitted = _code_yaml(source)
+
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "_expected_exact_code_by_label": {"submit_search": source},
+ },
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is True
+ assert len(persisted) == 1
+ assert _single_code(persisted[0]) == source
+ assert _single_code(ctx.workflow_yaml) == source
+
+
+async def test_exact_source_promotion_rejects_a_persistence_scrub_that_would_change_code(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ persisted: list[str] = []
+ _stub_successful_update(monkeypatch, persisted)
+ ctx = _ctx()
+ source = 'await page.locator("#password").click()\n'
+ register_secret_scrub_value(ctx, "password")
+ submitted = _code_yaml(source)
+
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "_expected_exact_code_by_label": {"submit_search": source},
+ },
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is False
+ assert result["error_code"] == "executed_source_changed_before_persistence"
+ assert persisted == []
+ assert ctx.workflow_yaml == ""
+
+
@pytest.mark.asyncio
async def test_run_path_rejects_changed_raw_load_balancer_webhook(monkeypatch: pytest.MonkeyPatch) -> None:
ctx = _ctx()
@@ -970,3 +1042,35 @@ async def test_oss_base_hook_yields_no_scanner_findings(monkeypatch: pytest.Monk
assert result["ok"] is True
assert persisted == [submitted]
assert all(f["reason_code"] != "code_block_scanner_advisory" for f in result["data"].get("findings", []))
+
+
[email protected]("placeholder", ['""', "|"], ids=["empty string", "empty block scalar"])
+async def test_executed_source_fills_an_empty_code_block_byte_for_byte(
+ monkeypatch: pytest.MonkeyPatch, placeholder: str
+) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _ctx()
+ executed = 'rows = await page.locator("tr").count()\nreturn {"rows": rows}'
+ draft = (
+ "title: Search\n"
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: count_rows\n"
+ f" code: {placeholder}\n"
+ )
+ promoted = apply_block_edit(draft, "count_rows", expected_code="", replacement_code=executed)
+
+ result = await _update_workflow(
+ {
+ "workflow_yaml": promoted,
+ "code_artifact_metadata": [],
+ "_expected_exact_code_by_label": {"count_rows": executed},
+ },
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is True, result
+ assert _single_code(ctx.workflow_yaml) == executed
diff --git a/tests/unit/test_copilot_context.py b/tests/unit/test_copilot_context.py
index 3ee37e1a5..bae1c8ccc 100644
--- a/tests/unit/test_copilot_context.py
+++ b/tests/unit/test_copilot_context.py
@@ -345,6 +345,7 @@ def _policy_ctx(
seeded_proposal_credential_ids=set(),
carry_cited_credential_ids=set(),
current_turn_named_credential_ids=set(),
+ origin_recovery_kept_named_credential_ids=set(),
persisted_workflow_credential_ids=set(),
selected_connected_account_id=selected_connected_account_id,
),
diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.py
index d28dcf2c9..a054e0ee8 100644
--- a/tests/unit/test_copilot_credential_pause.py
+++ b/tests/unit/test_copilot_credential_pause.py
@@ -22,22 +22,34 @@ from __future__ import annotations
import asyncio
import json
import time
+from collections.abc import Awaitable, Callable
+from copy import deepcopy
+from dataclasses import replace
from datetime import datetime, timedelta, timezone
+from itertools import count
from types import SimpleNamespace
-from typing import Any
+from typing import Any, Literal
from unittest.mock import AsyncMock, MagicMock
import pytest
from agents import RunConfig
from fastapi import HTTPException, status
+from structlog.testing import capture_logs
from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.cache.base import NoopLock
from skyvern.forge.sdk.copilot import credential_pause as credential_pause_module
from skyvern.forge.sdk.copilot import tools as tools_module
+from skyvern.forge.sdk.copilot.agent import _finalize_result_with_blocker_override
+from skyvern.forge.sdk.copilot.blocker_signal import (
+ CREDENTIAL_ORIGIN_RECOVERY_DECLINED_REASON_CODE,
+ CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE,
+ CopilotToolBlockerSignal,
+)
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
from skyvern.forge.sdk.copilot.context import (
+ AgentResult,
ApprovedCredential,
CopilotContext,
StructuredContext,
@@ -76,16 +88,37 @@ from skyvern.forge.sdk.copilot.request_policy import (
_seed_prior_approved_credentials,
credential_prompt_reason,
)
+from skyvern.forge.sdk.copilot.runtime import CredentialOriginRecovery, CredentialOriginRecoveryState
+from skyvern.forge.sdk.copilot.tools import credential_fill as credential_fill_module
from skyvern.forge.sdk.copilot.tools._shared import TOTAL_TIMEOUT_SECONDS, _copilot_seconds_remaining
from skyvern.forge.sdk.copilot.tools.credential_fill import _request_credential
+from skyvern.forge.sdk.copilot.tools.guardrails import _authority_tool_error
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
+from skyvern.forge.sdk.core.event_source_stream import EventSourceStream
from skyvern.forge.sdk.routes.workflow_copilot import (
WorkflowCopilotCredentialResponseRequest,
workflow_copilot_credential_response,
)
-from skyvern.forge.sdk.schemas.credentials import Credential, CredentialType, CredentialVaultType
-from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotStreamMessageType
+from skyvern.forge.sdk.schemas.credentials import (
+ Credential,
+ CredentialType,
+ CredentialVaultType,
+ PasswordCredential,
+ TotpType,
+)
+from skyvern.forge.sdk.schemas.workflow_copilot import (
+ WorkflowCopilotCredentialRequiredUpdate,
+ WorkflowCopilotStreamMessageType,
+)
from tests.unit.conftest import make_copilot_context
+from tests.unit.copilot_test_helpers import wire_credential_vault
+
+
[email protected](autouse=True)
+def _sequential_resume_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Each card gets tok-1, tok-2, ... so a test can pre-seed the answer for the card it expects."""
+ tokens = (f"tok-{n}" for n in count(1))
+ monkeypatch.setattr(credential_pause_module, "_new_resume_token", lambda: next(tokens))
def _repair_contract(
@@ -308,7 +341,7 @@ async def test_a_run_that_hits_a_login_still_gets_a_card_after_an_unanswered_too
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(
- "connected", "cred_1"
+ "connected", "cred_1", "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(
@@ -350,7 +383,7 @@ async def test_connected_action_mutates_policy_and_resolves(monkeypatch: pytest.
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(
- "connected", "cred_1"
+ "connected", "cred_1", "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
credential = _make_credential()
@@ -397,7 +430,7 @@ async def test_connected_action_unlatches_test_after_update_done(monkeypatch: py
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(
- "connected", "cred_1"
+ "connected", "cred_1", "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(
@@ -431,7 +464,9 @@ async def test_skip_action_leaves_policy_untouched(monkeypatch: pytest.MonkeyPat
ctx.request_policy = RequestPolicy()
cache = _FakeCache()
- cache.store[credential_response_cache_key("org-1", "chat-1", "turn-2")] = encode_credential_response("skip", None)
+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-2")] = encode_credential_response(
+ "skip", None, "tok-1"
+ )
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
@@ -466,7 +501,7 @@ async def test_skip_clears_stale_last_test_ok_from_the_diagnosed_failure(monkeyp
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-skip-clears")] = encode_credential_response(
- "skip", None
+ "skip", None, "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
@@ -520,10 +555,12 @@ async def test_response_racing_in_at_the_timeout_instant_is_rescued(monkeypatch:
cache = _FakeCache()
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
- async def fake_wait_races_in_a_response(response_key: str, ctx: Any, stream: Any, timeout_seconds: int) -> None:
+ async def fake_wait_races_in_a_response(
+ response_key: str, ctx: CopilotContext, stream: EventSourceStream, timeout_seconds: int, resume_token: str
+ ) -> None:
# Simulates resolve_credential_pause's lock-protected write landing in
# the same instant the waiter's own poll loop concludes None.
- cache.store[response_key] = encode_credential_response("skip", None)
+ cache.store[response_key] = encode_credential_response("skip", None, "tok-1")
return None
monkeypatch.setattr(credential_pause_module, "_wait_for_credential_response", fake_wait_races_in_a_response)
@@ -772,7 +809,7 @@ async def test_invalid_credential_id_degrades_instead_of_crashing(monkeypatch: p
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-3")] = encode_credential_response(
- "connected", "cred_foreign"
+ "connected", "cred_foreign", "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(
@@ -911,7 +948,7 @@ async def test_loop_pauses_at_finalize_and_resumes_same_turn(monkeypatch: pytest
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-loop")] = encode_credential_response(
- "skip", None
+ "skip", None, "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
@@ -987,7 +1024,7 @@ async def test_paused_loop_does_not_trip_total_timeout_on_resume(monkeypatch: py
async def _populate_after_first_poll() -> None:
await asyncio.sleep(4.5)
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-credit")] = encode_credential_response(
- "skip", None
+ "skip", None, "tok-1"
)
stream = _make_stream()
@@ -1067,9 +1104,9 @@ async def test_route_204_writes_flag_for_skip_without_credential_id(monkeypatch:
assert result is None
expected_key = credential_response_cache_key("org-1", "chat-1", "turn-1")
- assert cache.store[expected_key] == encode_credential_response("skip", None)
+ assert cache.store[expected_key] == encode_credential_response("skip", None, "tok-1")
response_set = next(call for call in cache.set_calls if call[0] == expected_key)
- assert response_set[1] == encode_credential_response("skip", None)
+ assert response_set[1] == encode_credential_response("skip", None, "tok-1")
assert response_set[2] == timedelta(seconds=settings.WORKFLOW_COPILOT_CREDENTIAL_PAUSE_TIMEOUT_SECONDS + 300)
@@ -1128,7 +1165,7 @@ async def test_route_204_writes_flag_for_connected_with_valid_credential(monkeyp
assert result is None
expected_key = credential_response_cache_key("org-1", "chat-1", "turn-1")
- assert cache.store[expected_key] == encode_credential_response("connected", "cred_1")
+ assert cache.store[expected_key] == encode_credential_response("connected", "cred_1", "tok-1")
@pytest.mark.asyncio
@@ -1288,7 +1325,7 @@ async def test_missing_credential_run_failure_pauses_the_loop(monkeypatch: pytes
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-nudge-race")] = encode_credential_response(
- "skip", None
+ "skip", None, "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
@@ -1434,7 +1471,7 @@ async def test_connect_clears_credential_draft_deferred_explicitly(monkeypatch:
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-connect-clear")] = encode_credential_response(
- "connected", "cred_1"
+ "connected", "cred_1", "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
credential = _make_credential()
@@ -1467,7 +1504,7 @@ async def test_skip_leaves_credential_draft_deferred_explicitly_untouched(monkey
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-skip-keep")] = encode_credential_response(
- "skip", None
+ "skip", None, "tok-1"
)
monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
@@ -1507,7 +1544,7 @@ async def test_poller_resolves_before_checking_disconnect(monkeypatch: pytest.Mo
async def _populate_during_sleep() -> None:
await asyncio.sleep(0.02)
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-race")] = encode_credential_response(
- "skip", None
+ "skip", None, "tok-1"
)
stream = MagicMock()
@@ -1773,16 +1810,23 @@ def test_page_only_admission_does_not_become_durable_approval(already_approved:
def _answered_cache(action: str, credential_id: str | None = None) -> _FakeCache:
cache = _FakeCache()
cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(
- action, credential_id
+ action, credential_id, "tok-1"
)
return cache
-def _stub_credential_lookup(monkeypatch: pytest.MonkeyPatch, credential: Credential) -> None:
+def _stub_credential_lookup(
+ monkeypatch: pytest.MonkeyPatch, credential: Credential, vault_row: AsyncMock | None = None
+) -> None:
monkeypatch.setattr(
credential_pause_module.app,
"DATABASE",
- SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=AsyncMock(return_value=[credential]))),
+ SimpleNamespace(
+ credentials=SimpleNamespace(
+ get_credentials_by_ids=AsyncMock(return_value=[credential]),
+ get_credential=vault_row or AsyncMock(return_value=None),
+ )
+ ),
)
@@ -1908,7 +1952,7 @@ class _SlowAnswerCache(_FakeCache):
async def get(self, key: str) -> Any:
if key == self._response_key and time.monotonic() >= self._ready_at:
- return encode_credential_response(self._action, "cred_1" if self._action == "connected" else None)
+ return encode_credential_response(self._action, "cred_1" if self._action == "connected" else None, "tok-1")
return await super().get(key)
@@ -2098,3 +2142,455 @@ async def test_raw_secret_turn_cannot_open_the_credential_card(monkeypatch: pyte
result = await _ask(ctx)
assert result["ok"] is False
ctx.stream.send.assert_not_awaited()
+
+
+_CardAnswer = tuple[Literal["connected", "skip"], str | None]
+
+
+def _answer_each_card(
+ cache: _FakeCache, answers: list[_CardAnswer]
+) -> Callable[[WorkflowCopilotCredentialRequiredUpdate], Awaitable[bool]]:
+ """Answer each card through the resume route's own writer as it is sent."""
+ pending = list(answers)
+
+ async def send(card: WorkflowCopilotCredentialRequiredUpdate) -> bool:
+ action, credential_id = pending.pop(0)
+ await resolve_credential_pause(
+ cache,
+ organization_id="org-1",
+ workflow_copilot_chat_id="chat-1",
+ turn_id=card.turn_id,
+ resume_token=card.resume_token,
+ action=action,
+ credential_id=credential_id,
+ )
+ return True
+
+ return send
+
+
+async def _call_ask_tool(ctx: CopilotContext, **arguments: str) -> dict[str, Any]:
+ raw = await tools_module.request_credential_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="request_credential"), # type: ignore[arg-type]
+ json.dumps({"login_page_url": "https://portal.example.com/login", "reason": "Needs 2FA.", **arguments}),
+ )
+ return json.loads(raw)
+
+
+def _sent_cards(ctx: CopilotContext) -> list[WorkflowCopilotCredentialRequiredUpdate]:
+ return [call.args[0] for call in ctx.stream.send.await_args_list]
+
+
+ ("totp_after_save", "expected_status"),
+ [(None, "saved_without_authenticator"), ("fake-seed", "authenticator_added")],
+)
+async def test_a_credential_with_no_authenticator_raises_an_update_card_naming_it(
+ monkeypatch: pytest.MonkeyPatch, totp_after_save: str | None, expected_status: str
+) -> None:
+ """The update answer grants nothing, and success is read from the saved record, not from the answer."""
+ cache = _FakeCache()
+ ctx = _tool_ctx(monkeypatch, cache)
+ credential = wire_credential_vault(monkeypatch, PasswordCredential(username="u", password="p", totp=None))
+ app.CREDENTIAL_VAULT_SERVICES[CredentialVaultType.SKYVERN].get_credential_item.side_effect = [
+ SimpleNamespace(name="authtest simple", credential=PasswordCredential(username="u", password="p", totp=None)),
+ SimpleNamespace(
+ name="authtest simple", credential=PasswordCredential(username="u", password="p", totp=totp_after_save)
+ ),
+ ]
+ ctx.request_policy.resolved_credentials = [credential]
+ ctx.request_policy.live_page_admitted_urls = {"cred_1": "https://app.example.org/signin"}
+ ctx.request_policy.credential_ask_login_page_urls = ["https://app.example.org/signin"]
+ ctx.request_policy.allow_run_blocks = False
+ policy_before = deepcopy(ctx.request_policy)
+ ctx.stream.send = AsyncMock(side_effect=_answer_each_card(cache, [("connected", "cred_1")]))
+
+ result = await _call_ask_tool(ctx, credential_id="cred_1")
+
+ [card] = _sent_cards(ctx)
+ assert (card.reason, card.credential_refs, card.login_page_urls) == (
+ "credential_missing_totp",
+ ["cred_1"],
+ ["https://portal.example.com/login"],
+ )
+ assert (result["status"], result["credential_id"]) == (expected_status, "cred_1")
+ assert ctx.request_policy == policy_before
+ assert ctx.credential_pause_outcome is None
+
+
+async def test_an_update_card_answered_with_another_credential_is_not_honored(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ cache = _FakeCache()
+ ctx = _tool_ctx(monkeypatch, cache)
+ credential = wire_credential_vault(monkeypatch, PasswordCredential(username="u", password="p", totp=None))
+ ctx.request_policy.resolved_credentials = [credential]
+ policy_before = deepcopy(ctx.request_policy)
+ app.DATABASE.credentials.get_credentials_by_ids = AsyncMock(return_value=[_make_credential("cred_2")])
+ ctx.stream.send = AsyncMock(side_effect=_answer_each_card(cache, [("connected", "cred_2")]))
+
+ result = await _call_ask_tool(ctx, credential_id="cred_1")
+
+ assert result["status"] == "unanswered"
+ assert "credential_id" not in result
+ assert ctx.request_policy == policy_before
+
+
+async def test_an_update_ask_waits_out_a_card_already_on_screen(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _tool_ctx(monkeypatch)
+ credential = wire_credential_vault(monkeypatch, PasswordCredential(username="u", password="p", totp=None))
+ ctx.request_policy.resolved_credentials = [credential]
+ ctx.credential_ask_in_flight = True
+
+ result = await _request_credential("https://portal.example.com/login", "Needs 2FA.", ctx, "cred_1")
+
+ assert result["status"] == "already_asked"
+ ctx.stream.send.assert_not_awaited()
+
+
+async def test_the_update_card_after_a_pick_waits_for_its_own_answer(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Both cards share the turn's response key, so the update card must not read the pick's answer."""
+ cache = _FakeCache()
+ ctx = _tool_ctx(monkeypatch, cache)
+ wire_credential_vault(monkeypatch, PasswordCredential(username="u", password="p", totp=None))
+ ctx.stream.send = AsyncMock(side_effect=_answer_each_card(cache, [("connected", "cred_1"), ("skip", None)]))
+
+ picked = await _call_ask_tool(ctx)
+ ctx.last_test_ok = False
+ update = await _call_ask_tool(ctx, credential_id="cred_1")
+ repeat = await _call_ask_tool(ctx, credential_id="cred_1")
+
+ assert [picked["status"], update["status"], repeat["status"]] == ["connected", "skipped", "already_asked"]
+ assert "outcome" not in repeat
+ assert [card.reason for card in _sent_cards(ctx)] == ["login_credentials_unresolved", "credential_missing_totp"]
+ assert (ctx.credential_pause_outcome, ctx.credential_pause_connected_credential_id) == ("connected", "cred_1")
+ assert ctx.credential_pause_reaskable_by_run is False
+ assert ctx.last_test_ok is False
+
+
+async def test_an_update_ask_leaves_the_pick_budget_for_a_later_card(monkeypatch: pytest.MonkeyPatch) -> None:
+ cache = _FakeCache()
+ ctx = _tool_ctx(monkeypatch, cache)
+ credential = wire_credential_vault(monkeypatch, PasswordCredential(username="u", password="p", totp=None))
+ ctx.request_policy.resolved_credentials = [credential]
+ ctx.stream.send = AsyncMock(side_effect=_answer_each_card(cache, [("skip", None), ("connected", "cred_1")]))
+
+ update = await _call_ask_tool(ctx, credential_id="cred_1")
+ run_card_ready = credential_pause_module.credential_pause_transport_ready(ctx, ctx.copilot_config)
+ picked = await _call_ask_tool(ctx)
+
+ assert [update["status"], picked["status"]] == ["skipped", "connected"]
+ assert run_card_ready is True
+ assert [card.reason for card in _sent_cards(ctx)] == ["credential_missing_totp", "login_credentials_unresolved"]
+
+
+async def test_an_answer_without_a_resume_token_resolves_no_card(monkeypatch: pytest.MonkeyPatch) -> None:
+ cache = _FakeCache()
+ key = credential_response_cache_key("org-1", "chat-1", "turn-1")
+ cache.store[key] = json.dumps({"action": "connected", "credential_id": "cred_1"})
+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
+
+ assert await credential_pause_module._try_resolve_credential_response(key, "org-1", "tok-1") == "pending"
+
+
+ ("secrets", "resolved", "expected"),
+ [
+ pytest.param(
+ PasswordCredential(username="u", password="p", totp="fake-seed"),
+ True,
+ {"ok": True, "status": "has_code_method", "method": "authenticator"},
+ id="authenticator",
+ ),
+ pytest.param(
+ PasswordCredential(
+ username="u", password="p", totp=None, totp_type=TotpType.EMAIL, totp_identifier="[email protected]"
+ ),
+ True,
+ {"ok": True, "status": "has_code_method", "method": "email_or_text"},
+ id="email-otp",
+ ),
+ pytest.param(
+ PasswordCredential(username="u", password="p", totp=None),
+ False,
+ {"ok": False},
+ id="not-resolved-for-this-request",
+ ),
+ ],
+)
+async def test_no_update_card_for_a_credential_with_a_code_method_or_outside_the_request(
+ monkeypatch: pytest.MonkeyPatch, secrets: PasswordCredential, resolved: bool, expected: dict[str, Any]
+) -> None:
+ ctx = _tool_ctx(monkeypatch)
+ credential = wire_credential_vault(monkeypatch, secrets)
+ ctx.request_policy.resolved_credentials = [credential] if resolved else []
+
+ result = await _call_ask_tool(ctx, credential_id="cred_1")
+
+ assert {key: result[key] for key in expected} == expected
+ ctx.stream.send.assert_not_awaited()
+
+
+_IDP_ORIGIN = "https://idp.example.test"
+
+
+_PENDING = CredentialOriginRecovery(_IDP_ORIGIN, "pending", refused_credential_id="cred_service")
+
+
+def _idp_credential(credential_id: str = "cred_idp") -> Credential:
+ return _make_credential(credential_id, "Provider Login").model_copy(update={"tested_url": f"{_IDP_ORIGIN}/login"})
+
+
+def _recovery_ctx(monkeypatch: pytest.MonkeyPatch, cache: _FakeCache) -> CopilotContext:
+ ctx = _tool_ctx(monkeypatch, cache)
+ ctx.credential_pause_used = True
+ ctx.credential_pause_outcome = "connected"
+ ctx.credential_origin_recovery = _PENDING
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="authority_denied",
+ agent_steering_text="Ask for a login on the provider.",
+ user_facing_reason="The sign-in continues on another site.",
+ recovery_hint="ask_user_clarifying",
+ internal_reason_code=CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE,
+ renders_final_reply=False,
+ )
+ return ctx
+
+
+def _assert_declined(ctx: CopilotContext, result: dict[str, Any], status: str) -> None:
+ assert result["status"] == status
+ assert ctx.credential_origin_recovery == replace(_PENDING, state="declined")
+ declined = ctx.blocker_signal
+ assert declined.internal_reason_code == CREDENTIAL_ORIGIN_RECOVERY_DECLINED_REASON_CODE
+ assert CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE not in {
+ signal.internal_reason_code for signal in ctx.tool_blocker_signals
+ }
+ assert declined.preserves_workflow_draft is True
+ for tool_name in ("update_workflow", "run_blocks_and_collect_debug", "edit_block_and_run", "update_and_run_blocks"):
+ assert _authority_tool_error(ctx, tool_name) is None
+ models_own_report = AgentResult(user_response="Ran it; it failed.", updated_workflow=None, global_llm_context=None)
+ assert _finalize_result_with_blocker_override(ctx, models_own_report) is models_own_report
+ assert _IDP_ORIGIN in result["next"] # nosemgrep: incomplete-url-substring-sanitization
+
+
+async def test_origin_recovery_gets_one_card_after_an_earlier_card_and_clears_on_a_same_origin_connect(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache("connected", "cred_idp"))
+ _stub_credential_lookup(monkeypatch, _idp_credential())
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login?state=opaque-state#fragment")
+
+ assert result["status"] == "connected"
+ assert result["credential_id"] == "cred_idp"
+ ctx.stream.send.assert_awaited_once()
+ card = ctx.stream.send.await_args.args[0]
+ assert card.login_page_urls == [f"{_IDP_ORIGIN}/login"]
+ assert ctx.request_policy.live_page_admitted_urls["cred_idp"] == f"{_IDP_ORIGIN}/login"
+ assert ctx.credential_origin_recovery is None
+ assert ctx.blocker_signal is None
+
+ ctx.credential_origin_recovery = _PENDING
+ again = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ ctx.stream.send.assert_awaited_once()
+ _assert_declined(ctx, again, "already_asked")
+
+
+async def test_a_connected_credential_whose_own_site_differs_is_not_rebound_to_the_recovery_origin(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache("connected", "cred_1"))
+ ctx.request_policy.current_turn_named_credential_ids = {"cred_1"}
+ service = _make_credential().model_copy(update={"tested_url": "https://portal.example.com/login"})
+ _stub_credential_lookup(monkeypatch, service)
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ ctx.stream.send.assert_awaited_once()
+ assert "cred_1" not in ctx.request_policy.live_page_admitted_urls
+ assert ctx.credential_pause_connected_credential_id is None
+ assert ctx.credential_pause_outcome == "not_admitted"
+ _assert_declined(ctx, result, "connected_other_site")
+
+
+ ("connected", "vault_row"),
+ [
+ (_idp_credential("cred_service"), None),
+ (_make_credential("cred_blank"), None),
+ (_idp_credential(), AsyncMock(side_effect=RuntimeError("vault unavailable"))),
+ ],
+ ids=["refused_credential", "no_site_evidence", "vault_read_error"],
+)
+async def test_origin_recovery_admits_no_credential_it_cannot_place_on_the_provider(
+ monkeypatch: pytest.MonkeyPatch, connected: Credential, vault_row: AsyncMock | None
+) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache("connected", connected.credential_id))
+ _stub_credential_lookup(monkeypatch, connected, vault_row)
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ assert connected.credential_id not in ctx.request_policy.live_page_admitted_urls
+ assert ctx.credential_pause_outcome == "not_admitted"
+ _assert_declined(ctx, result, "connected_other_site")
+
+
+async def test_a_recovery_connect_keeps_the_named_service_login_approved_beside_the_provider_login(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache("connected", "cred_idp"))
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ service = _make_credential("cred_service").model_copy(update={"tested_url": "https://portal.example.com/login"})
+ policy = ctx.request_policy
+ policy.resolved_credentials = [service]
+ policy.current_turn_named_credential_ids = {"cred_service"}
+ policy.persisted_workflow_credential_ids = ["cred_service"]
+ _stub_credential_lookup(monkeypatch, _idp_credential())
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ assert result["status"] == "connected"
+ assert credential_fill_module._request_settled_credential(policy, "cred_idp")
+ grants = {
+ credential_id: (await credential_fill_module._credential_fill_origin_grant(ctx, credential_id))[0]
+ for credential_id in ("cred_service", "cred_idp")
+ }
+ assert grants["cred_service"].intended_url == "https://portal.example.com/login"
+ assert grants["cred_idp"].intended_url == f"{_IDP_ORIGIN}/login"
+ approved = StructuredContext.from_json_str(record_approved_credentials_in_global_llm_context(ctx, None))
+ assert {record.credential_id for record in approved.approved_credentials} == {"cred_service", "cred_idp"}
+
+
+async def test_a_card_that_raises_declines_origin_recovery(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _recovery_ctx(monkeypatch, _FakeCache())
+ monkeypatch.setattr(
+ credential_fill_module, "request_credential_pause", AsyncMock(side_effect=RuntimeError("stream closed"))
+ )
+
+ with pytest.raises(RuntimeError, match="stream closed"):
+ await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ assert ctx.credential_origin_recovery == replace(_PENDING, state="declined")
+ assert ctx.blocker_signal.internal_reason_code == CREDENTIAL_ORIGIN_RECOVERY_DECLINED_REASON_CODE
+
+
+async def test_a_connect_that_resolves_no_credential_declines_origin_recovery(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _recovery_ctx(monkeypatch, _FakeCache())
+ monkeypatch.setattr(
+ credential_fill_module,
+ "request_credential_pause",
+ AsyncMock(return_value=CredentialPauseResolution(action="connected")),
+ )
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ _assert_declined(ctx, result, "connected_unresolved")
+
+
+async def test_origin_recovery_declines_when_the_card_cannot_be_shown(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _recovery_ctx(monkeypatch, _FakeCache())
+ ctx.client_supports_credential_pause = False
+
+ with capture_logs() as logs:
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ assert "copilot_credential_card_unavailable" in {entry["event"] for entry in logs}
+ ctx.stream.send.assert_not_awaited()
+ assert ctx.credential_pause_used is True
+ _assert_declined(ctx, result, "unavailable")
+
+
+async def test_a_card_for_another_origin_leaves_origin_recovery_pending(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache("connected", "cred_1"))
+ ctx.credential_pause_used = False
+ _stub_credential_lookup(monkeypatch, _make_credential())
+
+ result = await _ask(ctx, "https://portal.example.com/login")
+
+ assert result["status"] == "connected"
+ assert ctx.credential_origin_recovery == _PENDING
+ assert ctx.blocker_signal.internal_reason_code == CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE
+
+
+async def test_origin_recovery_raises_no_second_card_while_one_is_in_flight(monkeypatch: pytest.MonkeyPatch) -> None:
+ cache = _FakeCache()
+ ctx = _recovery_ctx(monkeypatch, cache)
+ _stub_credential_lookup(monkeypatch, _idp_credential())
+ ctx.stream.send = AsyncMock(side_effect=_answer_each_card(cache, [("connected", "cred_idp")]))
+ ctx.credential_ask_in_flight = True
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ assert result["status"] == "already_asked"
+ ctx.stream.send.assert_not_awaited()
+ assert ctx.credential_origin_recovery == _PENDING
+ assert _IDP_ORIGIN not in ctx.credential_origin_recovery_carded
+
+
+async def test_an_authenticator_update_ask_neither_spends_nor_resolves_origin_recovery(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ cache = _FakeCache()
+ ctx = _recovery_ctx(monkeypatch, cache)
+ service = wire_credential_vault(
+ monkeypatch, PasswordCredential(username="u", password="p", totp=None), credential_id="cred_service"
+ )
+ ctx.request_policy.resolved_credentials = [service]
+ ctx.stream.send = AsyncMock(side_effect=_answer_each_card(cache, [("skip", None)]))
+
+ await _request_credential(f"{_IDP_ORIGIN}/login", "Add 2FA.", ctx, credential_id="cred_service")
+
+ ctx.stream.send.assert_awaited_once()
+ assert ctx.credential_origin_recovery == _PENDING
+ assert _IDP_ORIGIN not in ctx.credential_origin_recovery_carded
+
+
[email protected](("answer", "status"), [("skip", "skipped"), (None, "unanswered")])
+async def test_a_declined_origin_recovery_ends_the_turn_naming_the_missing_login(
+ monkeypatch: pytest.MonkeyPatch, answer: str | None, status: str
+) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache(answer) if answer else _FakeCache())
+ ctx.copilot_config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=1)
+
+ result = await _ask(ctx, f"{_IDP_ORIGIN}/login")
+
+ ctx.stream.send.assert_awaited_once()
+ _assert_declined(ctx, result, status)
+
+
[email protected]("state", ["pending", "declined"])
+async def test_a_run_derived_pause_does_not_reopen_the_card_during_origin_recovery(
+ monkeypatch: pytest.MonkeyPatch, state: CredentialOriginRecoveryState
+) -> None:
+ ctx = _recovery_ctx(monkeypatch, _answered_cache("connected", "cred_1"))
+ ctx.credential_origin_recovery = replace(_PENDING, state=state)
+ ctx.credential_pause_reaskable_by_run = True
+ ctx.last_run_skipped_unbound_credentials = True
+ ctx.request_policy.login_page_urls = [f"{_IDP_ORIGIN}/login"]
+ _stub_credential_lookup(monkeypatch, _make_credential())
+
+ resume = await maybe_credential_pause(ctx, _fake_result(), ctx.stream, ctx.copilot_config)
+
+ assert resume is None
+ ctx.stream.send.assert_not_awaited()
+ assert "cred_1" not in ctx.request_policy.live_page_admitted_urls
diff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.py
index c3a84ff0b..fa2272e50 100644
--- a/tests/unit/test_copilot_fill_credential_field.py
+++ b/tests/unit/test_copilot_fill_credential_field.py
@@ -23,6 +23,7 @@ from structlog.testing import capture_logs
from skyvern.forge import app
from skyvern.forge.sdk.copilot import tools as tools_module
+from skyvern.forge.sdk.copilot.blocker_signal import CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.request_policy import (
RequestPolicy,
@@ -33,8 +34,10 @@ from skyvern.forge.sdk.copilot.request_policy import (
)
from skyvern.forge.sdk.copilot.runtime import (
SENSITIVE_ORIGIN_PAGE_ERROR,
+ CredentialOriginRecovery,
OriginRunRedactionRegistry,
browser_page_custody_lock,
+ browser_session_recovery,
)
from skyvern.forge.sdk.copilot.secret_scrub import (
REDACTED_SECRET_PLACEHOLDER,
@@ -53,6 +56,7 @@ from tests.unit.copilot_test_helpers import (
SENSITIVE_DISCLOSURE_WITHHOLDING_ARMS,
remove_sensitive_disclosure_prerequisite,
taint_by_terminal_run,
+ wire_credential_vault,
)
_FAKE_PASSWORD = "fake-test-password-7x9"
@@ -82,6 +86,9 @@ def _ctx(**overrides: Any) -> SimpleNamespace:
request_policy=_policy(),
block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
browser_session_id="pbs_1",
+ browser_session_recovery_lock=asyncio.Lock(),
+ browser_session_recovery_owner=None,
+ browser_session_recovery_depth=0,
last_run_blocks_workflow_run_id=None,
scouted_interactions=[],
scout_trajectory=[],
@@ -109,6 +116,8 @@ def _ctx(**overrides: Any) -> SimpleNamespace:
vault_login_uris_by_credential_id={},
signed_out_page_observations=[],
signed_out_page_observation_attempts=[],
+ credential_origin_recovery=None,
+ blocker_signal=None,
)
for key, value in overrides.items():
setattr(ns, key, value)
@@ -174,28 +183,13 @@ class TestResolveCredentialFillValue:
def _wire_vault(
self,
monkeypatch: pytest.MonkeyPatch,
- credential: Any,
+ credential: PasswordCredential,
*,
name: str = "authtest simple",
) -> None:
- db_credential = SimpleNamespace(vault_type=CredentialVaultType.BITWARDEN)
- monkeypatch.setattr(
- app.DATABASE,
- "credentials",
- SimpleNamespace(get_credential=AsyncMock(return_value=db_credential)),
- raising=False,
- )
- vault = SimpleNamespace(
- get_credential_item=AsyncMock(return_value=SimpleNamespace(name=name, credential=credential))
- )
- # `app` is an AppHolder proxy without __delattr__; patch the underlying instance
- # so monkeypatch teardown can delete the attribute it set.
- app_instance = object.__getattribute__(app, "_inst")
- monkeypatch.setattr(
- app_instance, "CREDENTIAL_VAULT_SERVICES", {CredentialVaultType.BITWARDEN: vault}, raising=False
- )
+ wire_credential_vault(monkeypatch, credential, credential_id="cred_123", name=name)
monkeypatch.setattr(
- app_instance,
+ object.__getattribute__(app, "_inst"),
"AGENT_FUNCTION",
SimpleNamespace(parse_enterprise_totp_secret=AsyncMock(return_value=None)),
raising=False,
@@ -314,9 +308,7 @@ class TestResolveCredentialFillValue:
async def test_totp_without_seed_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:
self._wire_vault(monkeypatch, PasswordCredential(username=_FAKE_USERNAME, password=_FAKE_PASSWORD, totp=None))
value, _, error = await tools_module._resolve_credential_fill_value(_ctx(), "cred_123", "totp")
- assert value is None
- assert error is not None
- assert "TOTP" in error
+ assert value is None and isinstance(error, credential_fill_module.MissingAuthenticator)
@pytest.mark.asyncio
@pytest.mark.parametrize(
@@ -1425,6 +1417,52 @@ class TestPublicToolCall:
assert not pages[idle_session].fill_calls and not pages[idle_session].click_calls
assert provisioned == ([True] if target == "debug" else [])
+ @pytest.mark.asyncio
+ async def test_missing_authenticator_points_to_the_update_ask_in_the_browser_the_call_named(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ real_resolve = credential_fill_module._resolve_credential_fill_value
+ page = _FakePage()
+ _wire_impl(monkeypatch, page)
+ monkeypatch.setattr(credential_fill_module, "_resolve_credential_fill_value", real_resolve)
+ wire_credential_vault(
+ monkeypatch,
+ PasswordCredential(username=_FAKE_USERNAME, password=_FAKE_PASSWORD, totp=None),
+ credential_id="cred_123",
+ name="authtest simple",
+ )
+ ctx = RunContextWrapper(_ctx(browser_session_id="pbs_debug", last_run_blocks_browser_session_id="pbs_run"))
+ ctx.tool_name = "fill_credential_field"
+
+ tool = next(t for t in tools_module.NATIVE_TOOLS if t.name == "fill_credential_field")
+ payload = await tool.on_invoke_tool(
+ ctx,
+ json.dumps({"selector": "#totpCode", "credential_id": "cred_123", "field": "totp", "target": "last_run"}),
+ )
+
+ result = json.loads(payload)
+ assert (result["ok"], result["status"], result["browser_target"]) == (
+ False,
+ credential_fill_module.MISSING_AUTHENTICATOR,
+ "last_run",
+ )
+ assert result["data"] == {
+ "credential_id": "cred_123",
+ "credential_name": "authtest simple",
+ "credential_field": "totp",
+ }
+ assert result["update_ask"] == "available"
+ assert not page.fill_calls
+
+ @pytest.mark.parametrize("already_asked", [False, True])
+ def test_missing_authenticator_steers_to_the_update_ask_only_once(self, already_asked: bool) -> None:
+ ctx = make_copilot_context()
+ ctx.credential_totp_update_asked = already_asked
+
+ result = credential_fill_module._missing_authenticator_fill_error(ctx, "cred_123", "authtest simple")
+
+ assert result["update_ask"] == ("already_asked" if already_asked else "available")
+
@pytest.mark.asyncio
async def test_a_credential_short_enough_to_sit_inside_an_outcome_word_cannot_forge_another_outcome(
self, monkeypatch: pytest.MonkeyPatch
@@ -1638,6 +1676,70 @@ class TestCredentialFillLivePageAdmission:
assert result["ok"] is False
assert page.fill_calls == []
+ @pytest.mark.asyncio
+ async def test_a_fill_refused_on_another_origin_opens_recovery_carrying_only_that_origin(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _FakePage(
+ url=_FIXTURE_LOGIN_URL,
+ release_url="https://idp.example.test/oauth/authorize?state=opaque-state#login_hint=someone",
+ )
+ _wire_impl(monkeypatch, page)
+ ctx = _ctx()
+
+ result = await tools_module._fill_credential_field_impl(ctx, "#passwordInput", "cred_123", "password")
+
+ assert result["ok"] is False
+ assert result["recovery"] == {
+ "observed_origin": "https://idp.example.test",
+ "next_action": "request_credential",
+ }
+ assert page.fill_calls == []
+ assert ctx.credential_origin_recovery == CredentialOriginRecovery(
+ "https://idp.example.test", "pending", refused_credential_id="cred_123"
+ )
+ signal = ctx.blocker_signal
+ assert signal.internal_reason_code == CREDENTIAL_ORIGIN_RECOVERY_PENDING_REASON_CODE
+ assert signal.recovery_hint == "ask_user_clarifying"
+ assert signal.renders_final_reply is False
+ assert dict(signal.extra) == {"observed_origin": "https://idp.example.test"}
+ serialized = json.dumps([signal.model_dump(mode="json"), result])
+ assert "opaque-state" not in serialized
+ assert "login_hint" not in serialized
+ assert "/oauth/authorize" not in serialized
+ assert _FAKE_PASSWORD not in serialized
+
+ @pytest.mark.asyncio
+ async def test_a_refusal_on_a_second_origin_keeps_the_pending_recovery(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ page = _FakePage(url=_FIXTURE_LOGIN_URL, release_url="https://idp.example.test/login")
+ _wire_impl(monkeypatch, page)
+ first = CredentialOriginRecovery("https://first-idp.example.test", "pending", refused_credential_id="cred_123")
+ ctx = _ctx(credential_origin_recovery=first)
+
+ result = await tools_module._fill_credential_field_impl(ctx, "#passwordInput", "cred_123", "password")
+
+ assert result["ok"] is False
+ assert result["error"] == credential_fill_module._credential_origin_recovery_error(first)
+ assert ctx.credential_origin_recovery == first
+ assert ctx.blocker_signal is None
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("release_url", ["about:blank", "https://sso.authenticationtest.com/login"])
+ async def test_a_refusal_off_another_site_keeps_the_retry_hint_and_opens_no_recovery(
+ self, monkeypatch: pytest.MonkeyPatch, release_url: str
+ ) -> None:
+ page = _FakePage(url=_FIXTURE_LOGIN_URL, release_url=release_url)
+ _wire_impl(monkeypatch, page)
+ ctx = _ctx()
+
+ result = await tools_module._fill_credential_field_impl(ctx, "#passwordInput", "cred_123", "password")
+
+ assert result == {"ok": False, "error": credential_fill_module._credential_fill_origin_mismatch_error()}
+ assert ctx.credential_origin_recovery is None
+ assert ctx.blocker_signal is None
+
@pytest.mark.asyncio
async def test_resolved_credential_without_a_user_provided_site_fails_closed(
self, monkeypatch: pytest.MonkeyPatch
@@ -2011,6 +2113,35 @@ class TestCredentialFillLivePageAdmission:
assert password["ok"] is True
assert maximum_active_resolutions == 1
+ @pytest.mark.asyncio
+ async def test_direct_credential_fill_waits_for_source_promotion_lock(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ ctx = _ctx(browser_session_recovery_lock=asyncio.Lock())
+ provisioning_started = asyncio.Event()
+
+ async def grant(*_args: object, **_kwargs: object) -> tuple[SimpleNamespace, None]:
+ return SimpleNamespace(), None
+
+ async def provision(provision_ctx: object, **_kwargs: object) -> dict[str, object]:
+ async with browser_session_recovery(provision_ctx):
+ provisioning_started.set()
+ return {"ok": False, "error": "stop after provisioning"}
+
+ monkeypatch.setattr(credential_fill_module, "_credential_fill_origin_grant", grant)
+ monkeypatch.setattr(credential_fill_module, "ensure_browser_session", provision)
+
+ async with ctx.browser_session_recovery_lock:
+ fill = asyncio.create_task(
+ tools_module._fill_credential_field_impl(ctx, "#password", "cred_123", "password")
+ )
+ await asyncio.sleep(0)
+ assert provisioning_started.is_set() is False
+ assert fill.done() is False
+
+ assert await fill == {"ok": False, "error": "stop after provisioning"}
+ assert provisioning_started.is_set() is True
+
@pytest.mark.asyncio
async def test_a_second_step_on_the_same_site_still_fills(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Real sign-ins walk email -> password -> one-time code across paths of the same site;
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index bba2f4c0d..70266e840 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -714,7 +714,9 @@ class TestMCPFailedStepLoopDetection:
ctx.gate_precedence_conflict_events = []
ctx.browser_session_id = None
ctx.browser_session_continuity_generation = 0
- ctx.browser_session_recovery_lock = None
+ ctx.browser_session_recovery_lock = asyncio.Lock()
+ ctx.browser_session_recovery_owner = None
+ ctx.browser_session_recovery_depth = 0
server = SkyvernOverlayMCPServer(
transport=MagicMock(),
overlays={"get_browser_screenshot": SchemaOverlay(requires_browser=True)},
diff --git a/tests/unit/test_copilot_make_agent_result_backfill.py b/tests/unit/test_copilot_make_agent_result_backfill.py
index 99ad45d1e..9205cd3db 100644
--- a/tests/unit/test_copilot_make_agent_result_backfill.py
+++ b/tests/unit/test_copilot_make_agent_result_backfill.py
@@ -606,6 +606,7 @@ def test_the_qualification_also_rides_the_narrative_terminal_message() -> None:
def _ran_blocks(ctx: CopilotContext) -> CopilotContext:
"""The turn executed the candidate, which is what makes the note eligible at all."""
ctx.last_run_blocks_workflow_run_id = "wr_2"
+ ctx.dispatched_run_ids_this_turn.add("wr_2")
return ctx
diff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.py
index 1eb7b4816..b32f39b59 100644
--- a/tests/unit/test_copilot_mcp_adapter.py
+++ b/tests/unit/test_copilot_mcp_adapter.py
@@ -1334,6 +1334,68 @@ class TestSharedBrowserCallOutcome:
records = _browser_outcome_records(captured)
assert records[-1]["completion_browser_session_id"] == "pbs_run"
+ @pytest.mark.asyncio
+ async def test_a_failed_debug_call_states_the_last_run_browser_without_moving_to_it(self) -> None:
+ async def _explode(_args: dict[str, Any], _ctx: AgentContext) -> dict[str, Any]:
+ raise RuntimeError("Browser CDP connection failed during state lookup.")
+
+ ctx = make_copilot_ctx(browser_session_id="pbs_debug")
+ ctx.last_run_blocks_browser_session_id = "pbs_run"
+ ctx.last_run_blocks_workflow_run_id = "wr_1"
+ server = _make_server(
+ ctx,
+ {"ok": True},
+ SchemaOverlay(requires_browser=True, pre_hook=_explode),
+ alias_map={"evaluate": "skyvern_evaluate"},
+ )
+
+ projected = await server.call_tool("evaluate", {})
+
+ payload = json.loads(projected.content[0].text)
+ continuity = payload["data"]["browser_call_continuity"]
+ assert payload["ok"] is False
+ assert continuity["browser_session_id"] == "pbs_debug"
+ assert continuity["browser_session_id_after"] == "pbs_debug"
+ assert continuity["last_run_browser_session_id"] == "pbs_run"
+ assert continuity["last_run_workflow_run_id"] == "wr_1"
+
+ @pytest.mark.asyncio
+ async def test_a_failed_call_does_not_offer_its_own_browser_as_the_last_run_browser(self) -> None:
+ async def _explode(_args: dict[str, Any], _ctx: AgentContext) -> dict[str, Any]:
+ raise RuntimeError("Browser CDP connection failed during state lookup.")
+
+ ctx = make_copilot_ctx(browser_session_id="pbs_debug")
+ ctx.last_run_blocks_browser_session_id = "pbs_debug"
+ ctx.last_run_blocks_workflow_run_id = "wr_1"
+ server = _make_server(
+ ctx,
+ {"ok": True},
+ SchemaOverlay(requires_browser=True, pre_hook=_explode),
+ alias_map={"evaluate": "skyvern_evaluate"},
+ )
+
+ projected = await server.call_tool("evaluate", {})
+
+ continuity = json.loads(projected.content[0].text)["data"]["browser_call_continuity"]
+ assert continuity["browser_session_id"] == "pbs_debug"
+ assert "last_run_browser_session_id" not in continuity
+
+ @pytest.mark.asyncio
+ async def test_a_successful_call_carries_no_last_run_facts(self) -> None:
+ ctx = make_copilot_ctx(browser_session_id="pbs_debug")
+ ctx.last_run_blocks_browser_session_id = "pbs_run"
+ ctx.last_run_blocks_workflow_run_id = "wr_1"
+ server = _make_server(
+ ctx,
+ {"ok": True, "data": {"result": 1}},
+ SchemaOverlay(requires_browser=True),
+ alias_map={"evaluate": "skyvern_evaluate"},
+ )
+
+ projected = await server.call_tool("evaluate", {})
+
+ assert "pbs_run" not in projected.content[0].text
+
def test_a_protocol_failure_does_not_borrow_the_session_loss_continuity_block(self) -> None:
"""The session is not known to be lost here; reusing the loss block would tell the model a
replacement browser is ready when nothing established that."""
@@ -1364,6 +1426,42 @@ class TestSharedBrowserCallOutcome:
assert loss["data"]["browser_session_continuity"]["disposition"] == "reestablished"
assert "browser_call_continuity" not in loss["data"]
+ def test_a_cancelled_call_still_names_the_last_run_browser(self) -> None:
+ """A caller that gives up projects no continuity block of its own, and that abandonment is
+ the shape the other browser matters most on."""
+ ctx = make_copilot_ctx(browser_session_id="pbs_debug")
+ ctx.last_run_blocks_browser_session_id = "pbs_run"
+ ctx.last_run_blocks_workflow_run_id = "wr_1"
+ cancelled = mcp_adapter._cancelled_browser_call_outcome(
+ raw_tool_name="skyvern_evaluate",
+ source_browser_session_id="pbs_debug",
+ source_browser_session_generation=0,
+ dispatch_started=False,
+ ctx=ctx,
+ )
+
+ projected = mcp_adapter._project_browser_call_outcome(
+ mcp_adapter._scrub_browser_call_outcome(ctx, cancelled), display_tool_name="evaluate"
+ )
+ succeeded = mcp_adapter._project_browser_call_outcome(
+ mcp_adapter._scrub_browser_call_outcome(
+ ctx,
+ mcp_adapter._browser_call_outcome_from_mapping(
+ raw_tool_name="skyvern_evaluate",
+ source_browser_session_id="pbs_debug",
+ source_browser_session_generation=0,
+ dispatched=True,
+ raw_result={"ok": True, "data": {"result": 1}},
+ ),
+ ),
+ display_tool_name="evaluate",
+ )
+
+ continuity = projected["data"]["browser_call_continuity"]
+ assert continuity["last_run_browser_session_id"] == "pbs_run"
+ assert continuity["last_run_workflow_run_id"] == "wr_1"
+ assert "pbs_run" not in json.dumps(succeeded)
+
@pytest.mark.usefixtures("_stub_browser_session")
class TestMCPToolTiming:
@@ -2515,11 +2613,14 @@ def test_reestablish_lock_budget_is_derived_from_the_managers_startup_bound(monk
assert not hasattr(mcp_adapter, "_SESSION_REESTABLISH_TIMEOUT_SECONDS")
-def _binding_ctx(*, debug: str | None, run: str | None, run_id: str | None = "wr_1") -> SimpleNamespace:
+def _binding_ctx(
+ *, debug: str | None, run: str | None, run_id: str | None = "wr_1", unavailable_reason: str | None = None
+) -> SimpleNamespace:
return SimpleNamespace(
browser_session_id=debug,
last_run_blocks_browser_session_id=run,
last_run_blocks_workflow_run_id=run_id,
+ last_run_binding_unavailable_reason=unavailable_reason,
)
@@ -2548,6 +2649,16 @@ def test_last_run_without_a_recorded_run_session_is_disclosed_not_silently_serve
assert "No test run" in binding.provenance()["browser_target_unavailable"]
+def test_a_refused_last_run_binding_states_why_rather_than_that_none_exists() -> None:
+ binding = resolve_browser_session_binding(
+ _binding_ctx(debug="pbs_debug", run=None, unavailable_reason="The last run this chat recorded is gone."),
+ {"target": "last_run"},
+ )
+
+ assert binding.session_id_override is None
+ assert binding.unavailable_reason == "The last run this chat recorded is gone."
+
+
def test_an_unknown_target_value_is_refused_rather_than_served_from_the_debug_browser() -> None:
# Coercing an off-enum target to the chat's browser would run a click or a fill in a browser the
# model did not name, and stamp the result as if it had landed where it was aimed.
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index bbec8b87e..d8f9326f6 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -2604,12 +2604,20 @@ class _CaptureSentinel(Exception):
def _run_id_only_ctx() -> CopilotContext:
ctx = _ctx()
ctx.last_run_blocks_workflow_run_id = "wr_discriminating"
+ ctx.dispatched_run_ids_this_turn.add("wr_discriminating")
ctx.last_update_block_count = None
ctx.last_test_ok = None
ctx.last_workflow = None
return ctx
+def test_an_inherited_run_id_is_not_a_genuine_workflow_attempt() -> None:
+ ctx = _run_id_only_ctx()
+ ctx.dispatched_run_ids_this_turn.clear()
+
+ assert ctx.has_genuine_workflow_attempt() is False
+
+
def test_build_exit_result_passes_genuine_predicate_as_workflow_attempted(monkeypatch) -> None:
ctx = _run_id_only_ctx()
assert ctx.has_genuine_workflow_attempt() is True
diff --git a/tests/unit/test_copilot_question_url_authority.py b/tests/unit/test_copilot_question_url_authority.py
index e71f4753f..b972d91f8 100644
--- a/tests/unit/test_copilot_question_url_authority.py
+++ b/tests/unit/test_copilot_question_url_authority.py
@@ -104,7 +104,8 @@ async def test_authenticated_question_url_reaches_the_real_card_and_rebuilds_fro
cache = _FakeCache()
cache.store[
credential_pause_module.credential_response_cache_key("org", ctx.workflow_copilot_chat_id, "turn")
- ] = credential_pause_module.encode_credential_response("connected", "cred_1")
+ ] = credential_pause_module.encode_credential_response("connected", "cred_1", "tok-card")
+ monkeypatch.setattr(credential_pause_module, "_new_resume_token", lambda: "tok-card")
monkeypatch.setattr(app._inst, "CACHE", cache, raising=False)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
monkeypatch.setattr(
diff --git a/tests/unit/test_copilot_repair_origin_run.py b/tests/unit/test_copilot_repair_origin_run.py
index f5e6517f0..49ae367ee 100644
--- a/tests/unit/test_copilot_repair_origin_run.py
+++ b/tests/unit/test_copilot_repair_origin_run.py
@@ -34,6 +34,7 @@ class _Ctx:
workflow_permanent_id: str | None = WPID
last_run_blocks_workflow_run_id: str | None = None
last_run_blocks_browser_session_id: str | None = None
+ last_run_binding_unavailable_reason: str | None = None
def _install_run(monkeypatch: pytest.MonkeyPatch, run: object | Exception) -> None:
@@ -267,3 +268,40 @@ async def test_a_packet_that_cannot_be_projected_leaves_the_turn_running(monkeyp
monkeypatch.setattr(run_execution, "finalize_build_test_result", explode)
assert await run_execution.hydrate_prior_run_packet(SimpleNamespace(), workflow_run_id=RUN) is None # type: ignore[arg-type]
+
+
+async def test_a_failed_run_lookup_leaves_the_turn_unseeded(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A turn that inherits a run id must not die because that run could not be read."""
+ _install_run(monkeypatch, RuntimeError("the run store is unreachable"))
+ ctx = _Ctx()
+
+ binding = await seed_repair_origin_run(ctx, workflow_run_id=RUN)
+
+ assert binding.refusal is RepairOriginRefusal.LOOKUP_FAILED
+ assert ctx.last_run_blocks_workflow_run_id is None
+ assert ctx.last_run_blocks_browser_session_id is None
+ assert ctx.last_run_binding_unavailable_reason == "The last run this chat recorded could not be looked up."
+
+
+async def test_a_refused_binding_names_the_fact_that_was_missing(monkeypatch: pytest.MonkeyPatch) -> None:
+ _install_run(monkeypatch, _run(browser_session_id=None))
+ ctx = _Ctx()
+
+ await seed_repair_origin_run(ctx, workflow_run_id=RUN)
+
+ assert (
+ ctx.last_run_binding_unavailable_reason == "The last run this chat recorded did not record a browser session."
+ )
+
+
+async def test_a_chat_with_no_recorded_run_carries_no_refusal(monkeypatch: pytest.MonkeyPatch) -> None:
+ _install_run(monkeypatch, _run())
+ ctx = _Ctx()
+
+ binding = await seed_repair_origin_run(ctx, workflow_run_id=None)
+
+ assert binding.refusal is RepairOriginRefusal.NOT_REQUESTED
+ assert ctx.last_run_binding_unavailable_reason is None
diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.py
index 137d19390..df3ac668c 100644
--- a/tests/unit/test_copilot_run_outcome_event.py
+++ b/tests/unit/test_copilot_run_outcome_event.py
@@ -352,6 +352,20 @@ def test_challenge_failure_records_observation_without_halting_agent() -> None:
assert ctx.turn_halt is None
+def test_a_run_this_turn_replaces_the_inherited_runs_refusal_sentence() -> None:
+ """The refusal described the run the pointers used to name; once this turn records its own run,
+ a ``last_run`` request must not be answered about the earlier one."""
+ result = _challenge_failure_result()
+ ctx = _ctx(result["data"]["blocks"])
+ ctx.last_run_blocks_workflow_run_id = "wr_inherited"
+ ctx.last_run_binding_unavailable_reason = "The last run this chat recorded is no longer readable."
+
+ _record_run_blocks_result(ctx, result, completion_verification=None)
+
+ assert ctx.last_run_blocks_workflow_run_id == "wr_challenge"
+ assert ctx.last_run_binding_unavailable_reason is None
+
+
def test_challenge_failure_sanitizes_model_observation_reason() -> None:
result = _challenge_failure_result()
raw_reason = (
@@ -584,6 +598,7 @@ def test_requested_output_judge_does_not_change_completed_run_record() -> None:
def test_run_outcome_trace_is_append_only_across_pointer_updates() -> None:
ctx = _ctx([_code_block("search_registry_person", {"records": []})])
ctx.last_run_blocks_workflow_run_id = "wr_test"
+ ctx.dispatched_run_ids_this_turn.add("wr_test")
committed = _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="not_evaluated"))
assert committed == RecordedRunOutcome(verdict="not_evaluated", workflow_run_id="wr_test")
@@ -602,6 +617,16 @@ def test_run_outcome_trace_is_append_only_across_pointer_updates() -> None:
assert ctx.run_outcome_trace == [committed, stashed]
+def test_an_inherited_run_id_is_not_stamped_onto_this_turns_outcome() -> None:
+ """A turn that dispatched nothing must not attribute its outcome to the run it inherited."""
+ ctx = _ctx([_code_block("search_registry_person", {"records": []})])
+ ctx.last_run_blocks_workflow_run_id = "wr_prior_turn"
+
+ stashed = _stash_recorded_run_outcome(ctx, RecordedRunOutcome(verdict="not_demonstrated"))
+
+ assert stashed.workflow_run_id is None
+
+
def test_recorded_outcome_for_new_run_uses_current_run_id() -> None:
ctx = _ctx([_code_block("search_registry_person", {"records": []})])
ctx.last_run_outcome = RecordedRunOutcome(verdict="not_evaluated", workflow_run_id="wr_prior")
diff --git a/tests/unit/test_copilot_runtime.py b/tests/unit/test_copilot_runtime.py
index 45bfe367f..55eabc385 100644
--- a/tests/unit/test_copilot_runtime.py
+++ b/tests/unit/test_copilot_runtime.py
@@ -20,6 +20,7 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
+from playwright._impl._errors import TargetClosedError as PlaywrightTargetClosedError
from playwright.async_api import Error as PlaywrightError
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from sqlalchemy.exc import TimeoutError as SQLATimeoutError
@@ -42,7 +43,12 @@ from skyvern.forge.sdk.copilot.unrecoverable_tool_error import _is_unrecoverable
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.schemas.browser_session_close import BrowserSessionCloseReason
-from skyvern.webeye.browser_errors import BrowserCdpConnectionError, BrowserTargetClosedError
+from skyvern.webeye.browser_errors import (
+ BrowserCdpConnectionError,
+ BrowserRetryableCdpError,
+ BrowserTargetClosedError,
+ BrowserTimeoutError,
+)
from skyvern.webeye.persistent_sessions_manager import (
BrowserOperation,
BrowserRetirement,
@@ -503,6 +509,180 @@ async def test_attach_retires_session_id_when_context_is_not_attachable(
assert ctx.browser_session_id is None
+async def test_attach_loss_waits_for_source_promotion_before_retiring_the_session(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The attach-loss oracle is a browser-session mutation spine, so it must share the
+ promotion lock instead of invalidating source provenance while persistence is in flight."""
+ lookup_started = asyncio.Event()
+
+ async def _report_dead(*_args: object, **_kwargs: object) -> None:
+ lookup_started.set()
+ return None
+
+ mock_manager = MagicMock()
+ mock_manager.get_browser_state = AsyncMock(side_effect=_report_dead)
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = mock_manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_validated_source"
+ await ctx.browser_session_recovery_lock.acquire()
+
+ async def _attach() -> None:
+ async with mcp_browser_context(ctx):
+ pass
+
+ attach = asyncio.create_task(_attach())
+ await asyncio.wait_for(lookup_started.wait(), timeout=1)
+ completed_while_promotion_held, _ = await asyncio.wait({attach}, timeout=0.05)
+ session_while_promotion_held = ctx.browser_session_id
+ attach_waited_for_promotion = not completed_while_promotion_held
+ ctx.browser_session_recovery_lock.release()
+
+ with pytest.raises(runtime.CopilotBrowserSessionUnavailable):
+ await attach
+ assert session_while_promotion_held == "bs_validated_source"
+ assert attach_waited_for_promotion
+ assert ctx.browser_session_id is None
+
+
+def _closed_report(cause: BaseException | None) -> BrowserTargetClosedError:
+ report = BrowserTargetClosedError("Browser session disconnected during the run and could not reconnect.")
+ report.__cause__ = cause
+ return report
+
+
+def _install_closed_report(monkeypatch: pytest.MonkeyPatch, report: BrowserTargetClosedError) -> None:
+ mock_manager = MagicMock()
+ mock_manager.get_browser_state = AsyncMock(side_effect=report)
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = mock_manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+
+
+ "cause",
+ [
+ pytest.param(None, id="probe-dead"),
+ pytest.param(
+ PlaywrightTargetClosedError("Target page, context or browser has been closed"), id="native-target-closed"
+ ),
+ ],
+)
+async def test_attach_retires_a_session_the_manager_reports_closed(
+ monkeypatch: pytest.MonkeyPatch, cause: BaseException | None
+) -> None:
+ _install_closed_report(monkeypatch, _closed_report(cause))
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_dead"
+
+ with pytest.raises(runtime.CopilotBrowserSessionUnavailable):
+ async with mcp_browser_context(ctx):
+ pass
+
+ assert ctx.browser_session_id is None
+
+
+ "cause",
+ [
+ pytest.param(PlaywrightTimeoutError("connect_over_cdp: Timeout 30000ms exceeded"), id="playwright-timeout"),
+ pytest.param(TimeoutError(), id="timeout"),
+ pytest.param(BrowserTimeoutError("deadline"), id="browser-timeout"),
+ pytest.param(BrowserRetryableCdpError("transient disconnect"), id="retryable-cdp"),
+ pytest.param(BrowserCdpConnectionError("CDP connection failed"), id="cdp-connection"),
+ pytest.param(PlaywrightError("connect ECONNREFUSED 127.0.0.1:9222"), id="refused-reconnect"),
+ pytest.param(OSError("[Errno 8] nodename nor servname provided"), id="name-resolution"),
+ pytest.param(PlaywrightError("WebSocket error: socket hang up"), id="websocket-dropped"),
+ ],
+)
+async def test_attach_keeps_a_session_whose_closed_report_came_from_a_timeout_or_transport_failure(
+ monkeypatch: pytest.MonkeyPatch, cause: BaseException
+) -> None:
+ _install_closed_report(monkeypatch, _closed_report(cause))
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ with pytest.raises(BrowserTargetClosedError):
+ async with mcp_browser_context(ctx):
+ pass
+
+ assert ctx.browser_session_id == "bs_live"
+
+
[email protected]("next_lookup_queued_behind", [False, True])
+ ("cause", "retires"),
+ [
+ pytest.param(None, True, id="positive-closed"),
+ pytest.param(TimeoutError(), False, id="timeout-closed"),
+ pytest.param(BrowserCdpConnectionError("CDP connection failed"), False, id="transport-closed"),
+ ],
+)
+async def test_a_closed_report_landing_after_its_caller_gave_up_reaches_the_next_attach_once(
+ monkeypatch: pytest.MonkeyPatch, cause: BaseException | None, retires: bool, next_lookup_queued_behind: bool
+) -> None:
+ """The manager drops its disconnected handle once it has answered closed, so every later lookup
+ of that session only sees an ambiguous connect error."""
+ monkeypatch.setattr(runtime, "_ABANDONED_CLOSED_FACTS", {})
+ monkeypatch.setattr(runtime, "_ABANDONED_BROWSER_STATE_RESOLVES", set())
+ determination_started, chrome_answered = asyncio.Event(), asyncio.Event()
+ calls = {"n": 0}
+
+ async def _get_browser_state(**_kwargs: object) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ determination_started.set()
+ await chrome_answered.wait()
+ raise _closed_report(cause)
+ await chrome_answered.wait()
+ raise BrowserCdpConnectionError("CDP connection failed")
+
+ mock_manager = MagicMock()
+ mock_manager.get_browser_state = AsyncMock(side_effect=_get_browser_state)
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = mock_manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_chat"
+
+ async def _attach() -> None:
+ async with mcp_browser_context(ctx):
+ pass
+
+ abandoned = asyncio.ensure_future(_attach())
+ await determination_started.wait()
+ abandoned.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await abandoned
+
+ if next_lookup_queued_behind:
+ next_attach = asyncio.ensure_future(_attach())
+ while calls["n"] < 2:
+ await asyncio.sleep(0)
+ chrome_answered.set()
+ else:
+ chrome_answered.set()
+ while runtime._ABANDONED_BROWSER_STATE_RESOLVES:
+ await asyncio.sleep(0)
+ next_attach = asyncio.ensure_future(_attach())
+ expected_error = runtime.CopilotBrowserSessionUnavailable if retires else BrowserCdpConnectionError
+ with pytest.raises(expected_error):
+ await next_attach
+ assert ctx.browser_session_id == (None if retires else "bs_chat")
+
+ ctx.browser_session_id = "bs_chat"
+ with pytest.raises(BrowserCdpConnectionError):
+ await _attach()
+ assert ctx.browser_session_id == "bs_chat", "the kept fact answers one lookup, not every later one"
+
+
@pytest.mark.asyncio
async def test_attach_keeps_session_id_when_state_lookup_raises(monkeypatch: pytest.MonkeyPatch) -> None:
"""A lookup that could not complete is not evidence the browser is gone, so the id survives."""
@@ -1043,7 +1223,7 @@ async def test_the_verified_caller_attaches_once_and_reports_what_the_attach_sai
@asynccontextmanager
async def _attach(ctx: AgentContext) -> AsyncIterator[None]:
if isinstance(attach_effect, runtime.CopilotBrowserSessionUnavailable):
- runtime.retire_browser_session_id(ctx, ctx.browser_session_id)
+ await runtime.retire_browser_session_id(ctx, ctx.browser_session_id)
if attach_effect is not None:
raise attach_effect
yield
@@ -1102,6 +1282,9 @@ async def test_attach_verification_follows_one_concurrent_generation_replacement
[
pytest.param(runtime.CopilotBrowserSessionUnavailable("bs_live"), "already_closed", id="closed"),
pytest.param(BrowserTargetClosedError("browser closed"), "already_closed", id="target-closed"),
+ pytest.param(
+ _closed_report(PlaywrightTimeoutError("attach timed out")), "cdp_connect_failed", id="timed-out-closed"
+ ),
pytest.param(BrowserCdpConnectionError("connect failed"), "cdp_connect_failed", id="cdp"),
],
)
@@ -1119,7 +1302,7 @@ async def test_build_test_attach_records_typed_failure_without_replacement(
@asynccontextmanager
async def _attach(ctx: AgentContext) -> AsyncIterator[None]:
if isinstance(attach_effect, runtime.CopilotBrowserSessionUnavailable):
- runtime.retire_browser_session_id(ctx, ctx.browser_session_id)
+ await runtime.retire_browser_session_id(ctx, ctx.browser_session_id)
raise attach_effect
yield
diff --git a/tests/unit/test_copilot_sensitive_origin_disclosure.py b/tests/unit/test_copilot_sensitive_origin_disclosure.py
index 9aac894f8..f0c2508ca 100644
--- a/tests/unit/test_copilot_sensitive_origin_disclosure.py
+++ b/tests/unit/test_copilot_sensitive_origin_disclosure.py
@@ -193,3 +193,13 @@ async def test_concurrent_navigations_on_two_tainted_browsers_judge_each_by_its_
assert hop["ok"] is False and "pbs_other" in ctx.sensitive_origin_browser_session_ids
assert left["ok"] is True and "pbs_run" not in ctx.sensitive_origin_browser_session_ids
assert ctx.pending_taint_source_urls == {}
+
+
+def test_a_run_id_inherited_without_its_registry_keeps_the_page_withheld() -> None:
+ """The registry a run binds while dispatching is what licenses disclosure, never the id alone."""
+ ctx = _ctx_after_run()
+ ctx.origin_run_redaction_registry = None
+
+ assert sensitive_origin_page_facts_withheld(ctx, "wr_credential") is True
+ assert origin_runs_bound_to_scrubber(ctx) == set()
+ assert PASSWORD not in registered_scrub_values(ctx)
diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.py
index d642a65e2..88153c16c 100644
--- a/tests/unit/test_copilot_streaming_adapter.py
+++ b/tests/unit/test_copilot_streaming_adapter.py
@@ -827,6 +827,15 @@ def test_tool_result_workflow_run_id_only_for_block_running_tools() -> None:
assert _tool_result_workflow_run_id("update_and_run_blocks", {"data": {"workflow_run_id": 42}}) is None
+def test_tool_result_executed_source_reference_only_for_browser_code() -> None:
+ from skyvern.forge.sdk.copilot.streaming_adapter import _tool_result_executed_source_reference
+
+ payload = {"ok": True, "executed_source_reference": "browser-code-source:opaque"}
+ assert _tool_result_executed_source_reference("run_browser_code", payload) == "browser-code-source:opaque"
+ assert _tool_result_executed_source_reference("edit_block_and_run", payload) is None
+ assert _tool_result_executed_source_reference("run_browser_code", {"executed_source_reference": 42}) is None
+
+
@pytest.mark.asyncio
async def test_a_stashed_write_diff_rides_one_result_and_no_later_foreign_one() -> None:
diffs = [{"label": "download_step", "added": 3, "removed": 1, "patch": "@@\n-old\n+new"}]
diff --git a/tests/unit/test_copilot_tools_credential_id_misbinding.py b/tests/unit/test_copilot_tools_credential_id_misbinding.py
index 9581e27fc..21db99059 100644
--- a/tests/unit/test_copilot_tools_credential_id_misbinding.py
+++ b/tests/unit/test_copilot_tools_credential_id_misbinding.py
@@ -375,6 +375,7 @@ def _ctx() -> MagicMock:
ctx.turn_halt = None
ctx.build_test_outcomes = []
ctx.latest_recorded_build_test_outcome = None
+ ctx.credential_origin_recovery = None
return ctx
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index 62293850d..14df00fc2 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -36,13 +36,16 @@ from skyvern.webeye.actions.handler import (
DOWNLOAD_NOT_TRIGGERED_FOLLOWUP_MESSAGE,
ActionHandler,
ScopedXhrDownloadCapture,
+ _browser_dispatch_committed,
_cleanup_captured_download_popup,
_collect_inline_iframe_src_candidates,
_EagerAdoptedBlobCapture,
_looks_like_pdf,
+ _PageDeltaBaseline,
_persist_captured_download,
_provider_poll_and_measure,
_ProviderPollPhase,
+ _record_action_owned_popup_delta,
_recover_adopted_session_blob_pdf_iframe,
_recover_blocked_inline_pdf_download,
_remove_download_listener,
@@ -190,6 +193,9 @@ async def _run_false_click_observation(
app_mock.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
async def inner(*args: object, **kwargs: object) -> list[ActionSuccess | ActionFailure]:
+ # The shared stub models an action that reached the real type-handler dispatch (click_effect is
+ # the browser effect); commit the dispatch boundary the real _handle_action would set there.
+ _browser_dispatch_committed.set(True)
if click_effect:
click_effect(context, page)
if isinstance(action_outcome, BaseException):
@@ -1315,6 +1321,7 @@ async def test_handle_action_download_recovery_same_context_still_claims_new_pop
owning_ctx = SkyvernContext(task_id=task.task_id)
async def open_popup_and_close_page(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ _browser_dispatch_committed.set(True)
context_a.pages = [page, new_popup] # popup opened in context A during the action
page.is_closed.return_value = True # forces recovery, but back into context A
return [ActionSuccess()]
@@ -1346,7 +1353,10 @@ async def test_handle_action_download_recovery_same_context_still_claims_new_pop
@pytest.mark.asyncio
-async def test_reused_claimed_page_retired_at_next_action_entry_survives_later_credit(tmp_path: Path) -> None:
[email protected]("ownership", ["strong", "late", "both"])
+async def test_reused_claimed_page_retired_at_next_action_entry_survives_later_credit(
+ tmp_path: Path, ownership: str
+) -> None:
"""R1: an earlier no-credit action left popup Q claimed; a later action enters the real handle_action
seam with Q as its initiating page (Q has graduated to navigation state) and opens popup R. When
durable credit later runs it must close only R and leave Q open. On the pre-fix head both close,
@@ -1355,7 +1365,11 @@ async def test_reused_claimed_page_retired_at_next_action_entry_survives_later_c
task, _step, context, page_q, _scraped_page, _action = rig
owning_ctx = SkyvernContext(task_id=task.task_id)
# Action 1's leftover: Q is a claimed popup that never received a durable download.
- owning_ctx.record_download_popup_claim(task.task_id, page_q)
+ if ownership in ("strong", "both"):
+ owning_ctx.record_download_popup_claim(task.task_id, page_q)
+ if ownership in ("late", "both"):
+ owning_ctx.record_download_popup_late_candidate(task.task_id, page_q)
+ page_q.url = ":"
context.pages = [page_q]
r_popup = _EventEmitter(context)
@@ -3184,6 +3198,231 @@ async def test_handle_action_download_admits_request_event_queued_by_action(
page.remove_listener.assert_any_call(event, callbacks[event])
+async def test_popup_claim_session_baseline_anchored_to_authoritative_pre_click_read() -> None:
+ """Round-15 B: a previous download that settles after the action begins but before the authoritative
+ pre-click baseline must be in the popup claim's session baseline -- anchored to the SAME instant the
+ credit seam uses -- so dead-blank recovery treats it identically (pre-existing), not as new credit for
+ this popup. The settle here lands during ``list_valid_pages`` (before the authoritative baseline)."""
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task, step, page, browser_state, scraped_page, action = _make_download_click_context(
+ now=now,
+ organization=organization,
+ page_url="https://example.com/download",
+ )
+ task = task.model_copy(update={"download_timeout": 0.01, "browser_session_id": "bs-1"})
+ page.context._skyvern_cdp_download_active = False
+ popup_page = MagicMock()
+ callbacks: dict[str, list[Callable]] = {}
+ page.on.side_effect = lambda event, callback: callbacks.setdefault(event, []).append(callback)
+ page.evaluate = AsyncMock(return_value=[])
+
+ prev_file = "s3://bucket/browser_sessions/bs-1/downloads/previous-action.pdf"
+ prev_settled = False
+
+ async def _list_valid_pages() -> list[object]:
+ nonlocal prev_settled
+ # A previous action's download settles here -- after the action began, before the authoritative
+ # pre-click baseline read below.
+ prev_settled = True
+ return [page]
+
+ browser_state.list_valid_pages = AsyncMock(side_effect=_list_valid_pages)
+
+ async def _session_downloaded(**_: object) -> list[str]:
+ return [prev_file] if prev_settled else []
+
+ async def _session_downloading(**_: object) -> list[str]:
+ return []
+
+ async def mock_inner_handle_action(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ # At popup mint (post pre-click read, pre wait) the session listers have been called for the SINGLE
+ # authoritative pre-click read only -- no separate auxiliary prefetch adds a second listing.
+ captured["downloaded_awaits_preclick"] = mock_app.STORAGE.list_downloaded_files_in_browser_session.await_count
+ for cb in callbacks.get("popup", []):
+ cb(popup_page) # mint the popup so _record_download_popup_claim fires
+ return [ActionSuccess()]
+
+ ctx = SkyvernContext(
+ task_id=task.task_id, organization_id=task.organization_id, workflow_run_id=task.workflow_run_id
+ )
+ # Capture the session baseline AT RECORD TIME (end-of-action cleanup may later retire a MagicMock popup).
+ captured: dict[str, object] = {}
+ _orig_record = ctx.record_download_popup_claim
+
+ def _spy_record(*a: object, **k: object) -> None:
+ if len(a) > 1 and a[1] is popup_page:
+ captured["session_baseline_files"] = k.get("session_baseline_files")
+ return _orig_record(*a, **k)
+
+ ctx.record_download_popup_claim = _spy_record # type: ignore[method-assign]
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ mock_app = MagicMock()
+ mock_app.BROWSER_MANAGER.get_for_task.return_value = browser_state
+ mock_app.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(side_effect=_session_downloaded)
+ mock_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(side_effect=_session_downloading)
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=mock_inner_handle_action),
+ patch("skyvern.webeye.actions.handler.BROWSER_DOWNLOAD_NO_SIGNAL_GRACE_TIME", 0),
+ patch("skyvern.webeye.actions.handler.get_download_dir", return_value=temp_dir),
+ patch("skyvern.webeye.actions.handler.list_files_in_directory", return_value=[]),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=ctx),
+ patch(
+ "skyvern.webeye.actions.handler.check_downloading_files_and_wait_for_download_to_complete",
+ new=AsyncMock(),
+ ),
+ patch("skyvern.webeye.actions.handler.app", mock_app),
+ ):
+ await ActionHandler.handle_action(
+ scraped_page=scraped_page,
+ task=task,
+ step=step,
+ page=page,
+ action=action,
+ )
+
+ # The previous file settled before the authoritative pre-click baseline -> the popup claim anchors to
+ # that same instant and carries it (so recovery cannot miscredit it to this popup).
+ session_baseline = captured.get("session_baseline_files")
+ assert session_baseline is not None and prev_file in session_baseline
+ # ...and the per-claim session baseline is the SAME single authoritative pre-click listing -- there is
+ # no second (auxiliary prefetch) session listing before the click.
+ assert captured["downloaded_awaits_preclick"] == 1
+
+
+def test_record_action_owned_popup_delta_marks_only_multi_popup_sweeps() -> None:
+ """Round-19: a delta sweep that claims TWO OR MORE popups at one instant marks them sibling-ambiguous
+ (no file->page mapping among same-action siblings). A lone delta popup owns its download unambiguously
+ and is never marked, so its fast credit path is preserved."""
+ initiating_multi = MagicMock()
+ sib_a = MagicMock()
+ sib_b = MagicMock()
+ context_multi = MagicMock()
+ context_multi.pages = [initiating_multi, sib_a, sib_b]
+ initiating_multi.context = context_multi
+ ctx_multi = SkyvernContext(task_id="t")
+ multi = _record_action_owned_popup_delta(
+ ctx_multi,
+ task_id="t",
+ initiating_page=initiating_multi,
+ baseline=_PageDeltaBaseline(browser_context=context_multi, pages=[initiating_multi]),
+ )
+ assert multi.claimed == 2
+ assert ctx_multi.download_popup_claim_has_delta_siblings("t", sib_a) is True
+ assert ctx_multi.download_popup_claim_has_delta_siblings("t", sib_b) is True
+
+ initiating_lone = MagicMock()
+ lone = MagicMock()
+ context_lone = MagicMock()
+ context_lone.pages = [initiating_lone, lone]
+ initiating_lone.context = context_lone
+ ctx_lone = SkyvernContext(task_id="t")
+ single = _record_action_owned_popup_delta(
+ ctx_lone,
+ task_id="t",
+ initiating_page=initiating_lone,
+ baseline=_PageDeltaBaseline(browser_context=context_lone, pages=[initiating_lone]),
+ )
+ assert single.claimed == 1
+ assert ctx_lone.download_popup_claim_has_delta_siblings("t", lone) is False
+
+
+async def test_handle_action_delta_sweep_baselines_pre_action_session_not_teardown_settle() -> None:
+ """Round-14: the action-finally delta sweep must baseline against the PRE-ACTION session view, NOT a
+ fresh finally re-snapshot. Causal attribution -- only files present before the action began are provably
+ not this action's own download. An earlier action's file present at action start IS baselined; a session
+ file that appears only DURING the action (this popup's own download, settling in the teardown window)
+ must NOT be baselined, or recovery treats it as pre-existing and denies credit to the popup's own file."""
+ from skyvern.webeye.actions.handler import _PageDeltaOutcome
+
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task, step, page, browser_state, scraped_page, action = _make_download_click_context(
+ now=now,
+ organization=organization,
+ page_url="https://example.com/download",
+ )
+ task = task.model_copy(update={"download_timeout": 0.01, "browser_session_id": "bs-1"})
+ page.context._skyvern_cdp_download_active = False
+ callbacks: dict[str, Callable] = {}
+ page.on.side_effect = lambda event, callback: callbacks.__setitem__(event, callback)
+ page.evaluate = AsyncMock(return_value=[])
+
+ earlier_file = "s3://bucket/browser_sessions/bs-1/downloads/earlier-present-at-start.pdf"
+ own_teardown_settle = "s3://bucket/browser_sessions/bs-1/downloads/own.pdf"
+ action_started = False
+
+ async def mock_inner_handle_action(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ nonlocal action_started
+ # This popup's own download settles DURING the action (the teardown window).
+ action_started = True
+ return [ActionSuccess()]
+
+ async def _session_downloaded(**_: object) -> list[str]:
+ # earlier_file was already present before the action; own settles only after the action starts.
+ return [earlier_file, own_teardown_settle] if action_started else [earlier_file]
+
+ async def _session_downloading(**_: object) -> list[str]:
+ return []
+
+ captured: dict[str, object] = {}
+
+ def _spy_delta(
+ owning_context: object,
+ *,
+ task_id: str,
+ initiating_page: object,
+ baseline: object,
+ download_dir: object = None,
+ attempt_started_at: object = None,
+ session_baseline_files: list[str] | None = None,
+ session_observed: bool = False,
+ ) -> _PageDeltaOutcome:
+ captured["session_baseline_files"] = session_baseline_files
+ return _PageDeltaOutcome(claimed=0, context_replaced=False, pages=[])
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ mock_app = MagicMock()
+ mock_app.BROWSER_MANAGER.get_for_task.return_value = browser_state
+ mock_app.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(side_effect=_session_downloaded)
+ mock_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(side_effect=_session_downloading)
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=mock_inner_handle_action),
+ patch("skyvern.webeye.actions.handler.BROWSER_DOWNLOAD_NO_SIGNAL_GRACE_TIME", 0),
+ patch("skyvern.webeye.actions.handler.get_download_dir", return_value=temp_dir),
+ patch("skyvern.webeye.actions.handler.list_files_in_directory", return_value=[]),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=None),
+ patch("skyvern.webeye.actions.handler._record_action_owned_popup_delta", side_effect=_spy_delta),
+ patch(
+ "skyvern.webeye.actions.handler.check_downloading_files_and_wait_for_download_to_complete",
+ new=AsyncMock(),
+ ),
+ patch("skyvern.webeye.actions.handler.app", mock_app),
+ ):
+ await ActionHandler.handle_action(
+ scraped_page=scraped_page,
+ task=task,
+ step=step,
+ page=page,
+ action=action,
+ )
+
+ session_baseline = captured["session_baseline_files"]
+ assert session_baseline is not None
+ # Present before the action -> baselined out (earlier action's file / round-12 protection preserved).
+ assert earlier_file in session_baseline
+ # Appeared only during the action -> NOT baselined (this popup's own teardown-window settle stays
+ # creditable; round-14 fix).
+ assert own_teardown_settle not in session_baseline
+
+
@pytest.mark.asyncio
async def test_handle_action_download_in_flight_request_does_not_extend_custom_timeout(
span_exporter: InMemorySpanExporter,
@@ -4780,21 +5019,21 @@ async def test_handle_action_adopted_session_falls_through_to_session_folder_whe
download.page = page
download.save_as = AsyncMock(side_effect=Exception("Target page, context or browser has been closed"))
+ file_landed = False
+
async def mock_inner_handle_action(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ nonlocal file_landed
download_callbacks["download"](download)
+ # The shared browser lands the file in its session folder DURING the action.
+ file_landed = True
return [ActionSuccess()]
- # first STORAGE listing (before action) returns empty; subsequent listings return a file
- # that the shared browser landed in its session-scoped download folder.
+ # Time-based (not call-count-based): every pre-action listing -- the claim-baseline session pre-fetch
+ # and the folder-sync baseline poll -- returns empty; only once the file has landed do listings find it.
session_landed_path = "s3://bucket/browser_sessions/bs-1/downloads/session-late.pdf"
- storage_calls = 0
async def storage_side_effect(**kwargs: object) -> list[str]:
- nonlocal storage_calls
- storage_calls += 1
- if storage_calls == 1:
- return []
- return [session_landed_path]
+ return [session_landed_path] if file_landed else []
with tempfile.TemporaryDirectory() as temp_root:
primary_dir = os.path.join(temp_root, "bs-1")
@@ -7194,6 +7433,7 @@ async def test_explicit_download_marker_popup_recorded_as_claim(tmp_path: Path)
marker_popup.close = AsyncMock()
async def click_opens_marker_popup(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ _browser_dispatch_committed.set(True)
# The click opens the download popup; no Playwright download event ever fires on it.
for callback in popup_callbacks:
callback(marker_popup)
diff --git a/tests/unit/test_download_popup_lifecycle_e2e.py b/tests/unit/test_download_popup_lifecycle_e2e.py
index 9f6882531..609992129 100644
--- a/tests/unit/test_download_popup_lifecycle_e2e.py
+++ b/tests/unit/test_download_popup_lifecycle_e2e.py
@@ -1,32 +1,14 @@
-"""SKY-15371 load-bearing regression: real-Chromium artifact-shape download-popup lifecycle.
-
-Reproduces the deployed-recurrence anchor shape (artifact-forensics/report.md) end to end through the
-real shipped seams: an ordinary ``download=false`` CLICK synchronously ``window.open``s a new popup in
-the initiating page's BrowserContext; no Playwright ``download`` event ever fires (the file is credited
-later by the file-scan lifecycle); and the wedged popup is absent from the scraper-oriented
-``list_valid_pages()``. The download is then durably credited and the credit seam must close exactly
-that action-owned popup while leaving the opener open.
-
-The test drives ``ActionHandler.handle_action``'s real false-click producer (which arms
-``page.on("popup", ...)`` and records the task-scoped claim) over real headless Chromium, then the real
-``ForgeAgent._close_credited_download_popups`` credit consumer. Real Chromium supplies the
-artifact-shaped popup (a genuine same-context Page, event-free); only the browser-manager lookup, the
-download directory, and the durable-credit ``browser_state`` (its ``list_valid_pages`` /
-``browser_context``) are stubbed -- the remote/file-credit nondeterminism the contract permits.
-
-An inline ``application/pdf`` popup would fire a Playwright ``download`` event under a plain headless
-Chromium (the CDP interceptor that suppresses it in production is not wired here), defeating the
-no-download-event shape; a rendered HTML viewer that commits to a real URL reproduces the lingering,
-event-free popup deterministically and also proves URL/commit state is not a cleanup filter.
-
-The credit consumer must close the wedged popup even though the scraper-oriented ``list_valid_pages()``
-omits it: eligibility gates on ``popup.context is browser_state.browser_context``, not scraper-list
-membership.
+"""Real Chromium coverage for synchronous and after-return download Page ownership.
+
+The browser supplies real Page events and committed documents; persistence is controlled at the
+existing durable-credit boundary. No external site or production run is involved.
"""
from __future__ import annotations
+import asyncio
import threading
+import time
from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
@@ -39,9 +21,11 @@ import pytest_asyncio
from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.models import StepStatus
-from skyvern.webeye.actions.actions import ClickAction
-from skyvern.webeye.actions.handler import ActionHandler
-from skyvern.webeye.actions.responses import ActionSuccess
+from skyvern.schemas.runs import RunEngine
+from skyvern.webeye.actions.actions import ClickAction, InputTextAction, SwitchTabAction
+from skyvern.webeye.actions.handler import ActionHandler, _browser_dispatch_committed
+from skyvern.webeye.actions.responses import ActionFailure, ActionSuccess
+from skyvern.webeye.real_browser_state import RealBrowserState
from tests.unit.helpers import make_organization, make_step, make_task
@@ -132,6 +116,7 @@ async def test_action_owned_popup_closed_after_late_download_credit(popup_site:
async def inner(*args: object, **kwargs: object) -> list[ActionSuccess]:
pg = kwargs["page"]
+ _browser_dispatch_committed.set(True)
# Synchronous window.open toward a committing document: the real page.on("popup") producer
# armed by handle_action fires, and no Playwright download event is ever raised.
async with pg.expect_popup() as popup_info:
@@ -182,3 +167,480 @@ async def test_action_owned_popup_closed_after_late_download_credit(popup_site:
assert popup.is_closed(), "action-owned download popup was left open after durable credit (SKY-15371 wedge)"
assert not opener.is_closed(), "the opener page must remain open"
+
+
+async def test_dispatched_then_failed_popup_still_closed_after_late_credit(popup_site: Any, tmp_path: Path) -> None:
+ """Real Chromium: a committed dispatch that opens a same-context popup and then FAILS keeps its
+ action-owned claim through the failure, so the task's durable-credit seam still closes the marker.
+ Before the dispatch-boundary fix the failure released the claim and the credit seam closed nothing."""
+ context, opener, downloads = popup_site
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="task-popup-fail", workflow_run_id="wr-popup-fail")
+ step = make_step(now, task, step_id="step-popup-fail", status=StepStatus.created, order=0, output=None)
+ action = ClickAction(element_id="download-link", download=False)
+ owning_ctx = SkyvernContext(task_id=task.task_id)
+
+ scraped_page = MagicMock()
+ seam_browser_state = MagicMock()
+ seam_browser_state.browser_artifacts = MagicMock(needs_cdp_frame_publisher=False, remote_browser_session_id=None)
+ seam_browser_state.release_driver_on_close = False
+
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = seam_browser_state
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+
+ captured_popup: list[Any] = []
+
+ async def inner(*args: object, **kwargs: object) -> list[ActionFailure]:
+ pg = kwargs["page"]
+ _browser_dispatch_committed.set(True)
+ async with pg.expect_popup() as popup_info:
+ await pg.evaluate("window.open('/doc','_blank')")
+ popup = await popup_info.value
+ await popup.wait_for_load_state("domcontentloaded")
+ captured_popup.append(popup)
+ # A real post-dispatch failure (e.g. a challenge-solver error or action timeout after the click).
+ return [ActionFailure(Exception("dispatched then failed after opening the popup"))]
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=inner),
+ patch("skyvern.webeye.actions.handler.app", app_mock),
+ patch("skyvern.webeye.actions.handler.get_download_dir", MagicMock(return_value=str(tmp_path))),
+ patch("skyvern.webeye.actions.handler.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=owning_ctx),
+ ):
+ await ActionHandler.handle_action(
+ scraped_page, task, step, opener, action, file_download_false_click_eligible=True
+ )
+
+ assert captured_popup, "the dispatched action did not open a popup"
+ popup = captured_popup[0]
+ assert not popup.is_closed(), "the failed action must not close its own action-owned popup"
+ # The dispatched-then-failed epoch retained its claim across the failure.
+ recorded = owning_ctx.download_popup_claims.get(task.task_id, [])
+ assert any(candidate is popup for candidate in recorded), "dispatched failure released the action-owned claim"
+
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ credit_browser_state.list_valid_pages = AsyncMock(return_value=[opener])
+
+ agent = ForgeAgent()
+ with patch("skyvern.forge.agent.skyvern_context.current", return_value=owning_ctx):
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert popup.is_closed(), "durable credit must still close the marker of a dispatched-then-failed action"
+ assert not opener.is_closed(), "the opener page must remain open"
+
+
+async def test_after_return_child_of_failed_dispatch_reserved_before_next_action(
+ popup_site: Any, tmp_path: Path
+) -> None:
+ """Real browser timing: a committed dispatch FAILS for an unrelated reason and the download child it
+ triggered joins the BrowserContext only AFTER handle_action returns, before the next action. The
+ failure path must keep the ``context.on('page')`` owner armed to the next-action boundary exactly as
+ the success path does, so the after-return child is reserved and closed by durable credit. Before the
+ dispatch-boundary fix the failure detached the owner at its own exit and the child was never observed."""
+ context, opener, downloads = popup_site
+ sibling = await context.new_page()
+ await sibling.goto(opener.url, wait_until="domcontentloaded")
+
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="task-late-fail", workflow_run_id="wr-late-fail")
+ step = make_step(now, task, step_id="step-late-fail", status=StepStatus.created, order=0, output=None)
+ action = ClickAction(element_id="download-link", download=False)
+ owning_ctx = SkyvernContext(task_id=task.task_id)
+
+ scraped_page = MagicMock()
+ seam_browser_state = MagicMock()
+ seam_browser_state.browser_artifacts = MagicMock(needs_cdp_frame_publisher=False, remote_browser_session_id=None)
+ seam_browser_state.release_driver_on_close = False
+
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = seam_browser_state
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+
+ async def inner(*args: object, **kwargs: object) -> list[ActionFailure]:
+ _browser_dispatch_committed.set(True)
+ # The child opens ~300ms AFTER this dispatch returns; the action itself fails for an unrelated reason.
+ await opener.evaluate("setTimeout(() => window.open('/doc', '_blank'), 300)")
+ return [ActionFailure(Exception("challenge solver failed after the click was dispatched"))]
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=inner),
+ patch("skyvern.webeye.actions.handler.app", app_mock),
+ patch("skyvern.webeye.actions.handler.get_download_dir", MagicMock(return_value=str(tmp_path))),
+ patch("skyvern.webeye.actions.handler.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=owning_ctx),
+ ):
+ await ActionHandler.handle_action(
+ scraped_page, task, step, opener, action, file_download_false_click_eligible=True
+ )
+
+ returned_at = time.monotonic()
+ assert owning_ctx.download_popup_late_candidates.get(task.task_id) is None, "nothing is reserved yet at return"
+ # The failed epoch stashed its deferred reservation release for the step's no-credit seam.
+ assert task.task_id in owning_ctx.pending_download_reservation_release
+ # The context owner stays armed past the failed return and records the after-return child.
+ async with asyncio.timeout(5):
+ while not owning_ctx.download_popup_late_candidates.get(task.task_id):
+ await asyncio.sleep(0.01)
+ assert time.monotonic() - returned_at >= 0.15, "the child genuinely joined after handle_action returned"
+ delayed_child = owning_ctx.download_popup_late_candidates[task.task_id][0]
+ await delayed_child.wait_for_load_state("domcontentloaded")
+ assert not delayed_child.is_closed(), "discovery alone must not close a page before durable credit"
+
+ # A foreign-context page must never be observed by this context's owner.
+ foreign_ctx = await context.browser.new_context()
+ foreign_page = await foreign_ctx.new_page()
+ candidates = owning_ctx.download_popup_late_candidates.get(task.task_id, [])
+ assert all(c is not opener and c is not sibling and c is not foreign_page for c in candidates)
+
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ credit_browser_state.list_valid_pages = AsyncMock(return_value=[opener, sibling])
+ agent = ForgeAgent()
+ with patch("skyvern.forge.agent.skyvern_context.current", return_value=owning_ctx):
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert delayed_child.is_closed(), "durable credit must close the reserved after-return child of a failed dispatch"
+ assert not opener.is_closed()
+ assert not sibling.is_closed()
+ assert not foreign_page.is_closed()
+ assert owning_ctx.download_popup_context_listeners.get(task.task_id) is None
+ assert owning_ctx.download_popup_late_candidates == {}
+ assert owning_ctx.download_popup_claims == {}
+
+ await foreign_ctx.close()
+
+
+async def test_dispatched_failure_popup_survives_later_batch_action_then_credit_closes(
+ popup_site: Any, tmp_path: Path
+) -> None:
+ """Two dispatched popups survive a failed click, successful fallback, and execute_step's no-credit seam."""
+ context, opener, downloads = popup_site
+ unrelated = await context.new_page()
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task = make_task(now, organization, task_id="task-midbatch", workflow_run_id="wr-midbatch")
+ task.navigation_goal = "Download receipt"
+ step = make_step(now, task, step_id="step-midbatch", status=StepStatus.created, order=0, output=None)
+ action = ClickAction(element_id="download-link", download=False)
+ owning_ctx = SkyvernContext(task_id=task.task_id)
+
+ scraped_page = MagicMock()
+ seam_browser_state = MagicMock()
+ seam_browser_state.browser_artifacts = MagicMock(needs_cdp_frame_publisher=False, remote_browser_session_id=None)
+ seam_browser_state.release_driver_on_close = False
+
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = seam_browser_state
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+
+ captured_popup: list[Any] = []
+
+ async def open_popup(pg: Any) -> None:
+ _browser_dispatch_committed.set(True)
+ async with pg.expect_popup() as popup_info:
+ await pg.evaluate("window.open('/doc','_blank')")
+ popup = await popup_info.value
+ await popup.wait_for_load_state("domcontentloaded")
+ captured_popup.append(popup)
+
+ async def first_inner(*args: object, **kwargs: object) -> list[ActionFailure]:
+ await open_popup(kwargs["page"])
+ return [ActionFailure(Exception("dispatched then failed"))]
+
+ async def second_inner(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ await open_popup(kwargs["page"])
+ return [ActionSuccess()]
+
+ with (
+ patch("skyvern.webeye.actions.handler.app", app_mock),
+ patch("skyvern.webeye.actions.handler.get_download_dir", MagicMock(return_value=str(tmp_path))),
+ patch("skyvern.webeye.actions.handler.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=owning_ctx),
+ ):
+ with patch.object(ActionHandler, "_handle_action", side_effect=first_inner):
+ await ActionHandler.handle_action(
+ scraped_page, task, step, opener, action, file_download_false_click_eligible=True
+ )
+ popup = captured_popup[0]
+ assert any(c is popup for c in owning_ctx.download_popup_claims.get(task.task_id, [])), "claim must be recorded"
+ with patch.object(ActionHandler, "_handle_action", side_effect=second_inner):
+ await ActionHandler.handle_action(
+ scraped_page,
+ task,
+ step,
+ opener,
+ ClickAction(element_id="fallback", download=False),
+ file_download_false_click_eligible=True,
+ )
+
+ assert not popup.is_closed(), "the later batch action must not close action1's popup"
+ assert any(c is popup for c in owning_ctx.download_popup_claims.get(task.task_id, [])), (
+ "the later batch action's entry released action1's owned claim before the credit seam"
+ )
+
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ credit_browser_state.list_valid_pages = AsyncMock(return_value=[opener])
+ agent = ForgeAgent()
+ adopted = await context.new_page()
+ owning_ctx.retire_intentional_page(task.task_id, adopted)
+ step.status = StepStatus.failed
+ credit_browser_state.get_working_page = AsyncMock(return_value=None)
+ app_mock.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=None)
+ app_mock.DATABASE.tasks.get_task = AsyncMock(return_value=task)
+ app_mock.DATABASE.tasks.update_task = AsyncMock(return_value=task)
+ app_mock.AGENT_FUNCTION.validate_step_execution = AsyncMock()
+ app_mock.AGENT_FUNCTION.post_step_execution = AsyncMock()
+ app_mock.ARTIFACT_MANAGER.flush_step_archive = AsyncMock()
+ with (
+ patch("skyvern.forge.agent.app", app_mock),
+ patch("skyvern.forge.agent.analytics.capture"),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=owning_ctx),
+ patch("skyvern.forge.agent.skyvern_context.ensure_context", return_value=owning_ctx),
+ patch("skyvern.forge.agent.get_download_retry_started_at", AsyncMock(return_value=None)),
+ patch.object(agent, "initialize_execution_state", AsyncMock(return_value=(step, credit_browser_state, None))),
+ patch.object(agent, "agent_step", AsyncMock(return_value=(step, None))),
+ patch.object(agent, "update_task_errors_from_detailed_output", AsyncMock(return_value=task)),
+ patch.object(agent, "_wait_for_in_flight_downloads", AsyncMock()),
+ patch.object(agent, "_finalize_downloaded_files_for_task", AsyncMock(return_value=[])),
+ patch.object(agent, "handle_failed_step", AsyncMock(return_value=None)),
+ patch.object(agent, "clean_up_task", AsyncMock()),
+ ):
+ await agent.execute_step(
+ organization,
+ task,
+ step,
+ close_browser_on_completion=True,
+ complete_verification=True,
+ task_block=MagicMock(complete_on_download=True),
+ engine=RunEngine.skyvern_v1,
+ download_baseline_files=[],
+ )
+ assert all(not p.is_closed() for p in captured_popup)
+ with patch("skyvern.forge.agent.skyvern_context.current", return_value=owning_ctx):
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert len(captured_popup) == 2 and all(p.is_closed() for p in captured_popup)
+ assert not opener.is_closed(), "the opener page must remain open"
+ assert not adopted.is_closed() and not unrelated.is_closed()
+
+
+async def test_after_return_child_reserved_before_later_action_popup(popup_site: Any, tmp_path: Path) -> None:
+ """Real browser timing across the action-return, next-action, and durable-credit boundaries."""
+ context, opener, downloads = popup_site
+ sibling = await context.new_page()
+ await sibling.goto(opener.url, wait_until="domcontentloaded")
+
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="task-late", workflow_run_id="wr-late")
+ step = make_step(now, task, step_id="step-late", status=StepStatus.created, order=0, output=None)
+ action = ClickAction(element_id="download-link", download=False)
+ owning_ctx = SkyvernContext(task_id=task.task_id)
+
+ scraped_page = MagicMock()
+ seam_browser_state = MagicMock()
+ seam_browser_state.browser_artifacts = MagicMock(needs_cdp_frame_publisher=False, remote_browser_session_id=None)
+ seam_browser_state.release_driver_on_close = False
+
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = seam_browser_state
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+
+ async def inner(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ _browser_dispatch_committed.set(True)
+ await opener.evaluate("setTimeout(() => window.open('/doc', '_blank'), 300)")
+ return [ActionSuccess()]
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=inner),
+ patch("skyvern.webeye.actions.handler.app", app_mock),
+ patch("skyvern.webeye.actions.handler.get_download_dir", MagicMock(return_value=str(tmp_path))),
+ patch("skyvern.webeye.actions.handler.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=owning_ctx),
+ ):
+ await ActionHandler.handle_action(
+ scraped_page, task, step, opener, action, file_download_false_click_eligible=True
+ )
+
+ returned_at = time.monotonic()
+ assert owning_ctx.download_popup_claims == {}
+ assert owning_ctx.download_popup_late_candidates == {}
+ async with asyncio.timeout(5):
+ while not owning_ctx.download_popup_late_candidates.get(task.task_id):
+ await asyncio.sleep(0.01)
+ assert time.monotonic() - returned_at >= 0.15
+ delayed_child = owning_ctx.download_popup_late_candidates[task.task_id][0]
+ await delayed_child.wait_for_load_state("domcontentloaded")
+ blank_marker = await context.new_page()
+
+ async def open_later_popup(**kwargs: Any) -> list[ActionSuccess]:
+ _browser_dispatch_committed.set(True)
+ async with opener.expect_popup() as popup:
+ await opener.evaluate("window.open('/doc?receipt', '_blank')")
+ await (await popup.value).wait_for_load_state("domcontentloaded")
+ return [ActionSuccess()]
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=open_later_popup),
+ patch("skyvern.webeye.actions.handler.app", app_mock),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=owning_ctx),
+ ):
+ await ActionHandler.handle_action(
+ scraped_page,
+ task,
+ step,
+ opener,
+ InputTextAction(element_id="verification", text="test"),
+ file_download_false_click_eligible=True,
+ )
+ committed_popup = context.pages[-1]
+ # A foreign-context page must never be observed by this context's owner.
+ foreign_ctx = await context.browser.new_context()
+ foreign_page = await foreign_ctx.new_page()
+
+ assert blank_marker.url == "about:blank", "setup: the child reports about:blank before painting"
+ assert committed_popup.url.endswith("/doc?receipt"), "setup: the site popup must be committed"
+ assert downloads == [], "no Playwright download event fires in this shape"
+ candidates = owning_ctx.download_popup_late_candidates.get(task.task_id, [])
+ assert any(c is blank_marker for c in candidates)
+ assert any(c is delayed_child for c in candidates)
+ assert all(c is not committed_popup for c in candidates)
+ assert all(c is not opener and c is not sibling and c is not foreign_page for c in candidates)
+ assert not blank_marker.is_closed() and not committed_popup.is_closed(), "no close before durable credit"
+ assert await committed_popup.locator("body").inner_text() == "Receipt document"
+
+ # Durable credit arrives later.
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ credit_browser_state.list_valid_pages = AsyncMock(return_value=[opener, sibling, committed_popup])
+
+ agent = ForgeAgent()
+ with patch("skyvern.forge.agent.skyvern_context.current", return_value=owning_ctx):
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert blank_marker.is_closed(), "durable credit must close the owned about:blank page"
+ assert delayed_child.is_closed(), "durable credit must close the reserved after-return child"
+ assert not committed_popup.is_closed(), "a later action popup must survive unrelated credit"
+ assert not opener.is_closed(), "the opener must remain open"
+ assert not sibling.is_closed(), "the pre-existing sibling must remain open"
+ assert not foreign_page.is_closed(), "a foreign-context page must never be touched"
+ assert owning_ctx.download_popup_context_listeners.get(task.task_id) is None
+ assert owning_ctx.download_popup_late_candidates == {}
+ assert owning_ctx.download_popup_claims == {}
+ after_credit = await context.new_page()
+ assert owning_ctx.download_popup_late_candidates == {}, "credit must detach the listener"
+ assert not after_credit.is_closed()
+
+ await foreign_ctx.close()
+
+
+async def test_switch_tab_adopts_late_candidate_before_delayed_credit(popup_site: Any, tmp_path: Path) -> None:
+ context, opener, downloads = popup_site
+ unrelated = await context.new_page()
+ await unrelated.goto(f"{opener.url}doc", wait_until="domcontentloaded")
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="task-switch", workflow_run_id="wr-switch")
+ step = make_step(now, task, step_id="step-switch", status=StepStatus.created, order=0, output=None)
+ owning_ctx = SkyvernContext(task_id=task.task_id)
+ browser_state = RealBrowserState(pw=MagicMock(), browser_context=context, page=opener)
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = browser_state
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock()
+ app_mock.AGENT_FUNCTION.wait_for_challenge_solver = AsyncMock()
+
+ with (
+ patch("skyvern.webeye.actions.handler.app", app_mock),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=owning_ctx),
+ patch("skyvern.webeye.actions.handler.get_download_dir", return_value=str(tmp_path)),
+ patch("skyvern.webeye.actions.handler.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0),
+ ):
+
+ async def _dispatched_success(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ _browser_dispatch_committed.set(True)
+ return [ActionSuccess()]
+
+ with patch.object(ActionHandler, "_handle_action", side_effect=_dispatched_success):
+ await ActionHandler.handle_action(
+ MagicMock(),
+ task,
+ step,
+ opener,
+ ClickAction(element_id="download-link", download=False),
+ file_download_false_click_eligible=True,
+ )
+ # Real page events after the click returns reserve both pages, even after they commit.
+ target = await context.new_page()
+ sibling = await context.new_page()
+ await target.goto(unrelated.url, wait_until="domcontentloaded")
+ await sibling.goto(unrelated.url, wait_until="domcontentloaded")
+ assert owning_ctx.download_popup_late_candidates[task.task_id] == [target, sibling]
+ assert downloads == []
+ pages = await browser_state.list_valid_pages()
+ result = await ActionHandler.handle_action(
+ MagicMock(), task, step, opener, SwitchTabAction(tab_index=pages.index(target))
+ )
+ assert isinstance(result[-1], ActionSuccess)
+ assert result[-1].skip_remaining_actions
+ assert await browser_state.get_working_page() is target
+ assert not target.is_closed() and not sibling.is_closed()
+
+ await ForgeAgent()._close_credited_download_popups(task, browser_state)
+
+ assert not target.is_closed(), "SWITCH_TAB must protect the adopted tab from delayed credit"
+ assert sibling.is_closed(), "a genuine sibling reservation must still close"
+ assert not opener.is_closed()
+ assert not unrelated.is_closed(), "an unreserved page with the same URL must survive"
+ assert await browser_state.get_working_page() is target
+ assert await target.locator("body").inner_text() == "Receipt document"
+ assert owning_ctx.download_popup_late_candidates == {}
+ assert owning_ctx.download_popup_claims == {}
+
+
+async def test_claimed_real_dead_blank_no_credit_releases_and_recovers(popup_site: Any, tmp_path: Path) -> None:
+ """Real Chromium: a claimed real ``about:blank`` popup that never credits is given its bounded grace
+ (observed against a real empty download dir), then the EXACT page is released from both registries
+ and internal recovery is returned -- exercising real ``page.context``/``page_is_dead_blank`` identity
+ without orphaning the opener/survivor."""
+ context, opener, _downloads = popup_site
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="tsk-recover", workflow_run_id="wr_recover")
+ step = make_step(now, task, step_id="step-recover", status=StepStatus.created, order=0, output=None)
+ dead = await context.new_page() # a real about:blank dead-blank page
+ owning_ctx = SkyvernContext(task_id=task.task_id)
+ owning_ctx.record_download_popup_claim(task.task_id, dead)
+
+ browser_state = MagicMock()
+ browser_state.get_working_page = AsyncMock(return_value=dead)
+ browser_state.list_valid_pages = AsyncMock(return_value=[dead, opener])
+
+ agent = ForgeAgent()
+ with (
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=owning_ctx),
+ patch("skyvern.forge.agent.resolve_run_download_id", return_value="wr_recover"),
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=tmp_path),
+ ):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ browser_state,
+ # A genuinely tiny positive configured grace: production resolves ``download_timeout or
+ # BROWSER_DOWNLOAD_TIMEOUT``, so 0 would fall back to the 600s default and hang the test.
+ task_block=MagicMock(complete_on_download=True, download_timeout=0.01),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ assert owning_ctx.has_download_popup_claim(task.task_id, dead) is False, "exact real page must be released"
+ assert owning_ctx.download_popup_recovery_grace_started_at == {}, "the released page's anchor must be dropped"
+ assert dead.context is context, "release/recovery must not perturb the real BrowserContext identity"
+ assert not opener.is_closed(), "the http survivor must remain open"
diff --git a/tests/unit/test_download_popup_lifecycle_v4.py b/tests/unit/test_download_popup_lifecycle_v4.py
index 051478d13..2a5105ec2 100644
--- a/tests/unit/test_download_popup_lifecycle_v4.py
+++ b/tests/unit/test_download_popup_lifecycle_v4.py
@@ -16,26 +16,53 @@ from contextlib import ExitStack
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
import pytest
+import skyvern.forge.sdk.core.skyvern_context as _skvctx
+from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.models import StepStatus
-from skyvern.webeye.actions.actions import ClickAction, SelectOption, SelectOptionAction
-from skyvern.webeye.actions.handler import ActionHandler
-from skyvern.webeye.actions.responses import ActionSuccess
+from skyvern.webeye.actions.actions import (
+ ClickAction,
+ InputTextAction,
+ SelectOption,
+ SelectOptionAction,
+ SwitchTabAction,
+)
+from skyvern.webeye.actions.handler import ActionHandler, _browser_dispatch_committed, handle_switch_tab_action
+from skyvern.webeye.actions.responses import ActionAbort, ActionFailure, ActionSuccess, StaleActionAbort
from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptor
from tests.unit.helpers import make_organization, make_step, make_task
_HANDLER = "skyvern.webeye.actions.handler"
+_AGENT = "skyvern.forge.agent"
class _FakeContext:
- """Stand-in BrowserContext: only the ``pages`` list is read by the delta/close logic."""
+ """Stand-in BrowserContext: the ``pages`` list is read by the delta/close logic, and the
+ ``on``/``remove_listener`` page-event surface backs the event-driven ``context.on("page")`` ownership
+ (a same-context child that joins after the action seam returns without a popup event)."""
def __init__(self) -> None:
self.pages: list[_FakePage] = []
+ self._page_cbs: list[Callable[[Any], None]] = []
+
+ def on(self, event: str, cb: Callable[[Any], None]) -> None:
+ if event == "page":
+ self._page_cbs.append(cb)
+
+ def remove_listener(self, event: str, cb: Callable[[Any], None]) -> None:
+ if event == "page" and cb in self._page_cbs:
+ self._page_cbs.remove(cb)
+
+ def page_listener_count(self) -> int:
+ return len(self._page_cbs)
+
+ def emit_page(self, page: Any) -> None:
+ for cb in list(self._page_cbs):
+ cb(page)
class _FakePage:
@@ -76,6 +103,9 @@ class _FakePage:
def is_closed(self) -> bool:
return self._closed
+ async def bring_to_front(self) -> None:
+ pass
+
async def close(self, **_kwargs: Any) -> None:
self._events.append(f"{self._label}:close_start")
# Yield once so a terminal-close ordering is observable on the event loop.
@@ -110,8 +140,21 @@ def _make_env(**task_overrides: Any) -> tuple[Any, Any, Any, SkyvernContext, lis
return task, step, MagicMock(), ctx, events
+def _dispatched(inner: Any) -> Any:
+ """Wrap a patched ``_handle_action`` stub so it commits the browser-dispatch boundary before running,
+ modeling a stub that reached the real type-handler seam (the common case these tests exercise). The
+ real ``_handle_action`` sets this flag at its single dispatch site; a stub that instead models a
+ no-dispatch exit (stale abort / already-in-desired-state suppression) sets the flag False itself."""
+
+ async def _wrapped(*args: Any, **kwargs: Any) -> Any:
+ _browser_dispatch_committed.set(True)
+ return await inner(*args, **kwargs)
+
+ return _wrapped
+
+
def _enter_patches(stack: ExitStack, app_mock: Any, ctx: SkyvernContext, download_dir: Path, inner: Any) -> None:
- stack.enter_context(patch.object(ActionHandler, "_handle_action", side_effect=inner))
+ stack.enter_context(patch.object(ActionHandler, "_handle_action", side_effect=_dispatched(inner)))
stack.enter_context(patch(f"{_HANDLER}.app", app_mock))
stack.enter_context(patch(f"{_HANDLER}.get_download_dir", MagicMock(return_value=str(download_dir))))
stack.enter_context(patch(f"{_HANDLER}.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0))
@@ -950,3 +993,1265 @@ async def test_preaction_activity_within_admission_window_never_credits_this_cli
if pending is not None:
pending.cancel()
interceptor._cdp_handler_tasks.discard(pending)
+
+
+# --- Behavior A: event-driven Page ownership via context.on("page") (SKY-15371) ---------------------
+# The deployed shape credits an inline download through the CDP monitor + file-scan lifecycle: no
+# Playwright popup/download event fires, and the never-committed marker child joins the initiating
+# BrowserContext SHORTLY AFTER handle_action returns -- after the in-seam popup listener and the
+# action-window delta backstop have both been torn down. An event-driven ``context.on("page")`` owner,
+# armed alongside the popup listener and stopped before the next action, records the late child
+# for the existing durable-credit closer.
+
+
+def test_arm_context_listener_records_after_return_child_and_detaches_on_take() -> None:
+ ctx = SkyvernContext(task_id="t-A1")
+ context = _FakeContext()
+
+ def cb(child: Any) -> None:
+ ctx.record_download_popup_claim("t-A1", child)
+
+ ctx.arm_download_popup_context_listener("t-A1", context, cb)
+ assert context.page_listener_count() == 1
+ # Idempotent per (task, context): a second download click in the same task must not stack listeners.
+ ctx.arm_download_popup_context_listener("t-A1", context, cb)
+ assert context.page_listener_count() == 1
+
+ child = object()
+ context.emit_page(child) # joins the context after the seam returned
+ assert ctx.download_popup_claims.get("t-A1") == [child]
+
+ taken = ctx.take_download_popup_claims("t-A1")
+ assert taken == [child]
+ # Detached at the durable claim boundary; a further late child is no longer observed.
+ assert context.page_listener_count() == 0
+ context.emit_page(object())
+ assert ctx.download_popup_claims.get("t-A1") is None
+
+
+def test_clear_claims_detaches_context_listener() -> None:
+ ctx = SkyvernContext(task_id="t-A2")
+ context = _FakeContext()
+ ctx.arm_download_popup_context_listener("t-A2", context, lambda child: None)
+ assert context.page_listener_count() == 1
+ ctx.clear_download_popup_claims("t-A2")
+ assert context.page_listener_count() == 0
+
+
+def test_detach_swallows_remove_listener_error() -> None:
+ ctx = SkyvernContext(task_id="t-A3")
+
+ class _Boom:
+ def on(self, *_a: Any) -> None:
+ pass
+
+ def remove_listener(self, *_a: Any) -> None:
+ raise RuntimeError("context torn down")
+
+ ctx.arm_download_popup_context_listener("t-A3", _Boom(), lambda child: None)
+ # Terminal claim teardown must never raise even if the underlying context is already gone.
+ ctx.take_download_popup_claims("t-A3")
+ ctx.clear_download_popup_claims("t-A3")
+
+
[email protected]("late_url", [":", "about:blank", "", "http://origin/receipt"])
+async def test_context_page_listener_closes_late_child_after_credit(tmp_path: Path, late_url: str) -> None:
+ task, step, scraped_page, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/documents", events, "opener")
+ sibling = _FakePage(context, "http://origin/sibling", events, "sibling")
+ context.pages.extend([opener, sibling])
+ action = ClickAction(element_id="dl-link", download=False)
+ app_mock = _app_mock(action)
+
+ async def inner(*_a: object, **_k: object) -> list[ActionSuccess]:
+ # No popup event, no download event, no action-window page delta: the whole in-seam capture
+ # surface stays empty (the deployed CDP/file-scan shape).
+ return [ActionSuccess()]
+
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, inner)
+ await ActionHandler.handle_action(
+ scraped_page, task, step, opener, action, file_download_false_click_eligible=True
+ )
+
+ # The in-seam popup listener is removed in the action finally; the context page owner is NOT --
+ # removing it synchronously at return would miss the after-return child.
+ assert context.page_listener_count() == 1, "context.on('page') owner must survive the action finally"
+
+ late_child = _FakePage(context, late_url, events, "late")
+ context.pages.append(late_child)
+ context.emit_page(late_child)
+ candidates = ctx.download_popup_late_candidates.get(task.task_id, [])
+ assert any(c is late_child for c in candidates), "the after-return same-context child was not recorded"
+ assert not late_child.is_closed(), "discovery alone must not close a page before durable credit"
+
+ foreign = _FakePage(_FakeContext(), late_url, events, "foreign")
+ context.emit_page(opener)
+ context.emit_page(sibling)
+ context.emit_page(foreign)
+ assert ctx.download_popup_late_candidates.get(task.task_id) == [late_child]
+
+ browser_state = MagicMock(browser_context=context)
+ browser_state.list_valid_pages = AsyncMock(return_value=[opener, sibling])
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, browser_state)
+
+ assert late_child.is_closed()
+ assert not any(page.is_closed() for page in (opener, sibling, foreign))
+ assert not opener._popup_cbs
+ assert context.page_listener_count() == 0
+ assert ctx.download_popup_context_listeners == {}
+ assert ctx.download_popup_claims == {}
+ assert ctx.download_popup_late_candidates == {}
+
+
+# --- Behavior A guard: a deliberate NEW_TAB is not misclaimed and closed by download credit ----------
+# The task-scoped context.on("page") owner records every same-context child until the durable claim
+# boundary. A deliberate NEW_TAB (the task's last pre-credit action) creates a same-context page that the
+# owner records; the ordinary discard-on-reuse cannot protect it because no later action starts on it. The
+# creation seam must retire that exact page's claim so the credit consumer never closes an intentional tab.
+
+
+async def test_deliberate_new_tab_survives_download_credit(tmp_path: Path) -> None:
+ from skyvern.webeye.actions.actions import NewTabAction
+ from skyvern.webeye.actions.handler import handle_new_tab_action
+
+ task, step, scraped_page, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+
+ # Arm the context owner exactly as the false-click download seam does (records a late candidate).
+ def on_context_child(child: Any) -> None:
+ if child is not opener:
+ ctx.record_download_popup_late_candidate(task.task_id, child)
+
+ ctx.arm_download_popup_context_listener(task.task_id, context, on_context_child)
+
+ new_tab = _FakePage(context, "http://origin/new", events, "newtab")
+
+ browser_state = MagicMock()
+
+ async def _new_page() -> Any:
+ # Production new_page() joins the page to the context, firing context.on("page").
+ context.pages.append(new_tab)
+ context.emit_page(new_tab)
+ return new_tab
+
+ browser_state.new_page = _new_page
+ browser_state.navigate_to_url = AsyncMock()
+ browser_state.set_active_page = AsyncMock()
+
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = browser_state
+
+ action = NewTabAction(url="http://origin/new")
+ with (
+ patch(f"{_HANDLER}.app", app_mock),
+ patch(f"{_HANDLER}.validate_fetch_url", MagicMock(return_value="http://origin/new")),
+ patch(f"{_HANDLER}.skyvern_context.current", return_value=ctx),
+ ):
+ result = await handle_new_tab_action(action, opener, scraped_page, task, step)
+ assert isinstance(result[-1], ActionSuccess)
+
+ # The creation seam retired the exact new tab's claim before durable credit.
+ assert all(c is not new_tab for c in ctx.download_popup_late_candidates.get(task.task_id, [])), (
+ "the deliberate NEW_TAB claim was not discarded at the creation seam"
+ )
+
+ # A durable download credit arrives while the deliberate tab is still open.
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ agent = ForgeAgent()
+ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert not new_tab.is_closed(), "a deliberately-created NEW_TAB must not be closed by download credit"
+ assert not opener.is_closed(), "the opener must remain open"
+
+
+# --- Terminal-cleanup listener timing (SKY-15371): keep the owner armed through settle/finalize ------
+# clean_up_task must NOT take/detach the task context.on("page") owner at entry: a late marker that joins
+# the context during the final screenshot / settle / finalization awaits would be missed even when
+# finalization then grants durable credit. The owner stays armed until the durable-credit result is known,
+# then strong claims + late candidates are taken exactly once and closed (credit) or expired (no credit).
+
+
+class _SettleCM:
+ """Async context manager standing in for settle_browser_downloads_for_context; runs a hook on enter to
+ model a same-context child joining the context while cleanup is awaiting settle."""
+
+ def __init__(self, on_enter: Any) -> None:
+ self._on_enter = on_enter
+
+ async def __aenter__(self) -> None:
+ self._on_enter()
+
+ async def __aexit__(self, *_a: object) -> bool:
+ return False
+
+
+def _cleanup_patches(
+ stack: ExitStack, ctx: SkyvernContext, task: Any, browser_state: Any, on_settle: Any, finalize_result: Any
+) -> None:
+ app_mock = MagicMock()
+ app_mock.DATABASE.tasks.get_task = AsyncMock(return_value=task)
+ app_mock.STORAGE.save_downloaded_files = AsyncMock(return_value=None)
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = browser_state
+ stack.enter_context(patch(f"{_AGENT}.app", app_mock))
+ stack.enter_context(patch(f"{_AGENT}.skyvern_context.current", return_value=ctx))
+ stack.enter_context(patch(f"{_AGENT}.analytics.capture", MagicMock()))
+ stack.enter_context(patch(f"{_AGENT}.has_download_interceptor_for_context", MagicMock(return_value=False)))
+ stack.enter_context(patch(f"{_AGENT}.resolve_run_download_id", MagicMock(return_value="run-cleanup")))
+ stack.enter_context(patch(f"{_AGENT}.drain_speculative_persist_tasks", AsyncMock()))
+ stack.enter_context(
+ patch(f"{_AGENT}.settle_browser_downloads_for_context", MagicMock(return_value=_SettleCM(on_settle)))
+ )
+ stack.enter_context(
+ patch.object(ForgeAgent, "_finalize_downloaded_files_for_task", AsyncMock(return_value=finalize_result))
+ )
+
+
[email protected]("late_url", [":", "about:blank", "", "http://origin/receipt"])
+async def test_late_page_during_settle_is_closed_by_terminal_credit(tmp_path: Path, late_url: str) -> None:
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+
+ # Arm the owner exactly as the false-click download seam does; initial late-candidate set is empty.
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+ assert ctx.download_popup_late_candidates.get(task.task_id, []) == []
+
+ late_blank = _FakePage(context, late_url, events, "late")
+
+ def _on_settle() -> None:
+ context.pages.append(late_blank)
+ context.emit_page(late_blank)
+ assert not late_blank.is_closed(), "settle has not yet proved durable credit"
+
+ browser_state = MagicMock()
+ browser_state.browser_context = context
+
+ with ExitStack() as stack:
+ _cleanup_patches(stack, ctx, task, browser_state, _on_settle, finalize_result=["stmt.pdf"])
+ await ForgeAgent().clean_up_task(
+ task, step, need_final_screenshot=False, download_suffix="stmt", list_files_before=[]
+ )
+
+ assert late_blank.is_closed(), "a late marker joining during settle must be closed once terminal credit lands"
+ assert not opener.is_closed(), "the opener must remain open"
+ assert context.page_listener_count() == 0, "the context owner must be detached after terminal cleanup"
+
+
[email protected]("late_url", [":", "about:blank", "", "http://origin/receipt"])
+async def test_terminal_no_credit_expires_owner_without_close(tmp_path: Path, late_url: str) -> None:
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+ late_blank = _FakePage(context, late_url, events, "late")
+ claimed = _FakePage(context, late_url, events, "claimed")
+ ctx.record_download_popup_claim(task.task_id, claimed)
+
+ browser_state = MagicMock()
+ browser_state.browser_context = context
+
+ with ExitStack() as stack:
+ # finalize proves NO durable credit (empty list).
+ _cleanup_patches(stack, ctx, task, browser_state, lambda: context.emit_page(late_blank), finalize_result=[])
+ await ForgeAgent().clean_up_task(
+ task, step, need_final_screenshot=False, download_suffix="stmt", list_files_before=[]
+ )
+
+ assert not late_blank.is_closed(), "no durable credit => no destructive close"
+ assert not claimed.is_closed()
+ assert context.page_listener_count() == 0, "the owner must still be detached/expired on the no-credit path"
+ assert ctx.download_popup_late_candidates.get(task.task_id) is None, "late-candidate state must be expired"
+ assert ctx.download_popup_claims == {}
+ assert ctx.download_popup_context_listeners == {}
+
+
+async def test_terminal_db_refresh_failure_still_expires_owner(tmp_path: Path) -> None:
+ from skyvern.exceptions import TaskNotFound
+
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+
+ app_mock = MagicMock()
+ app_mock.DATABASE.tasks.get_task = AsyncMock(side_effect=RuntimeError("db down"))
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{_AGENT}.app", app_mock))
+ stack.enter_context(patch(f"{_AGENT}.skyvern_context.current", return_value=ctx))
+ with pytest.raises(TaskNotFound):
+ await ForgeAgent().clean_up_task(task, step, need_final_screenshot=False)
+
+ assert context.page_listener_count() == 0, "a DB refresh failure must not leave the owner armed"
+
+
+async def test_terminal_settle_exception_expires_owner_without_close(tmp_path: Path) -> None:
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+ late_blank = _FakePage(context, ":", events, "late")
+ ctx.record_download_popup_late_candidate(task.task_id, late_blank)
+
+ browser_state = MagicMock()
+ browser_state.browser_context = context
+
+ def _boom_settle() -> None:
+ raise RuntimeError("settle blew up")
+
+ with ExitStack() as stack:
+ _cleanup_patches(stack, ctx, task, browser_state, _boom_settle, finalize_result=["stmt.pdf"])
+ # The save block catches its own exceptions; cleanup completes without raising.
+ await ForgeAgent().clean_up_task(
+ task, step, need_final_screenshot=False, download_suffix="stmt", list_files_before=[]
+ )
+
+ assert not late_blank.is_closed(), "a settle failure (no proven credit) must not destructively close a marker"
+ assert context.page_listener_count() == 0, "a settle failure must still detach/expire the owner"
+
+
+# --- Intentional-page ownership exclusion (SKY-15371 PR A) -------------------------------------------
+# The context.on("page") owner records EVERY newly-created same-context blank Page, including deliberately
+# created tabs (NEW_TAB, magic link) that stay blank until a later navigation. A delayed download credit
+# could close such an intentional tab while it is still blank. Each creation seam must retire the exact new
+# Page from both registries the instant new_page() returns -- before any await that could let credit fire.
+
+
+def test_retire_intentional_page_exact_identity_only() -> None:
+ ctx = SkyvernContext(task_id="t-int")
+ a = object()
+ b = object()
+ # A genuine same-task blank download late candidate (a) and an intentional page (b).
+ ctx.record_download_popup_late_candidate("t-int", a)
+ ctx.record_download_popup_late_candidate("t-int", b)
+ ctx.record_download_popup_claim("t-int", b) # b also happened to be a strong claim
+ ctx.record_download_popup_claim("other", a) # a sibling task bucket must be preserved
+
+ ctx.retire_intentional_page("t-int", b)
+
+ assert ctx.download_popup_late_candidates.get("t-int") == [a], "only the intentional page is retired"
+ assert "t-int" not in ctx.download_popup_claims, "b was the only strong claim for the task -> bucket dropped"
+ assert ctx.download_popup_claims.get("other") == [a], "sibling task bucket preserved"
+
+
+def test_retire_intentional_page_idempotent_when_unrecorded() -> None:
+ ctx = SkyvernContext(task_id="t-int2")
+ never_recorded = object()
+ # Must not raise and must not create/mutate buckets when the listener never recorded the page.
+ ctx.retire_intentional_page("t-int2", never_recorded)
+ assert ctx.download_popup_late_candidates.get("t-int2") is None
+ assert ctx.download_popup_claims.get("t-int2") is None
+
+
+async def test_new_tab_retired_before_navigation_survives_delayed_credit(tmp_path: Path) -> None:
+ from skyvern.webeye.actions.actions import NewTabAction
+ from skyvern.webeye.actions.handler import handle_new_tab_action
+
+ task, step, scraped_page, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+
+ new_tab = _FakePage(context, ":", events, "newtab") # deliberately-created tab, still blank
+ browser_state = MagicMock()
+
+ async def _new_page() -> Any:
+ context.pages.append(new_tab)
+ context.emit_page(new_tab) # production: new_page() joins the context, firing context.on("page")
+ return new_tab
+
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+
+ async def _navigate(*_a: Any, **_k: Any) -> None:
+ # A durable download credit fires WHILE navigation is still awaiting.
+ await ForgeAgent()._close_credited_download_popups(task, credit_browser_state)
+
+ browser_state.new_page = _new_page
+ browser_state.navigate_to_url = _navigate
+ browser_state.set_active_page = AsyncMock()
+
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = browser_state
+
+ with (
+ patch(f"{_HANDLER}.app", app_mock),
+ patch(f"{_HANDLER}.validate_fetch_url", MagicMock(return_value="http://origin/new")),
+ patch(f"{_HANDLER}.skyvern_context.current", return_value=ctx),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),
+ ):
+ result = await handle_new_tab_action(NewTabAction(url="http://origin/new"), opener, scraped_page, task, step)
+
+ assert isinstance(result[-1], ActionSuccess)
+ assert not new_tab.is_closed(), "a NEW_TAB retired before navigation must survive a credit firing during nav"
+
+
[email protected]("ownership", ["late", "claim", "both"])
[email protected]("credit_during_activation", [True, False], ids=["activation", "after-return"])
[email protected]("through_dispatcher", [False, True], ids=["handler-first-tab", "dispatcher-last-tab"])
+async def test_switch_tab_target_survives_delayed_credit(
+ ownership: str, credit_during_activation: bool, through_dispatcher: bool
+) -> None:
+ task, step, scraped_page, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ unrelated = _FakePage(context, "http://origin/doc", events, "unrelated")
+ target = _FakePage(context, "http://origin/doc", events, "target")
+ late_sibling = _FakePage(context, "http://origin/doc", events, "late_sibling")
+ claimed_sibling = _FakePage(context, "http://origin/doc", events, "claimed_sibling")
+ context.pages.extend([opener, unrelated, late_sibling, claimed_sibling])
+ context.pages.insert(len(context.pages) if through_dispatcher else 0, target)
+ ctx.arm_download_popup_context_listener(
+ task.task_id, context, lambda child: ctx.record_download_popup_late_candidate(task.task_id, child)
+ )
+ if ownership in ("late", "both"):
+ context.emit_page(target)
+ if ownership in ("claim", "both"):
+ ctx.record_download_popup_claim(task.task_id, target)
+ context.emit_page(late_sibling)
+ ctx.record_download_popup_claim(task.task_id, claimed_sibling)
+ ctx.record_download_popup_claim("other-task", unrelated)
+ ctx.record_download_popup_late_candidate("other-task", unrelated)
+
+ action = SwitchTabAction(tab_index=len(context.pages) - 1 if through_dispatcher else 0)
+ app_mock = _app_mock(action)
+ app_mock.AGENT_FUNCTION.wait_for_challenge_solver = AsyncMock()
+ browser_state = app_mock.BROWSER_MANAGER.get_for_task.return_value
+ browser_state.browser_context = context
+ browser_state.list_valid_pages = AsyncMock(return_value=list(context.pages))
+ active_pages: list[_FakePage] = []
+ agent = ForgeAgent()
+
+ async def activate(selected: _FakePage) -> None:
+ assert selected is target
+ # The dispatcher stops old capture; adopting a target alone must leave capture untouched.
+ assert context.page_listener_count() == (0 if through_dispatcher else 1)
+ assert not any(p.is_closed() for p in context.pages)
+ active_pages.append(selected)
+ if credit_during_activation:
+ await agent._close_credited_download_popups(task, browser_state)
+
+ browser_state.set_active_page = activate
+ with (
+ patch(f"{_HANDLER}.app", app_mock),
+ patch(f"{_HANDLER}.skyvern_context.current", return_value=ctx),
+ ):
+ if through_dispatcher:
+ results = await ActionHandler.handle_action(scraped_page, task, step, opener, action)
+ else:
+ results = await handle_switch_tab_action(action, opener, scraped_page, task, step)
+ assert isinstance(results[-1], ActionSuccess)
+ assert results[-1].skip_remaining_actions
+ if not credit_during_activation:
+ assert not any(p.is_closed() for p in context.pages)
+ await agent._close_credited_download_popups(task, browser_state)
+
+ assert active_pages == [target]
+ assert not target.is_closed(), "the selected working tab must survive delayed download credit"
+ assert late_sibling.close_terminal, "adopting a target must preserve genuine sibling reservations"
+ assert claimed_sibling.close_terminal
+ assert not opener.is_closed()
+ assert not unrelated.is_closed(), "same-URL and other-task pages must survive"
+ assert ctx.download_popup_claims == {"other-task": [unrelated]}
+ assert ctx.download_popup_late_candidates == {"other-task": [unrelated]}
+
+
+async def test_magic_link_page_retired_survives_delayed_credit() -> None:
+ task, step, scraped_page, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+
+ magic_page = _FakePage(context, ":", events, "magic") # blank until the returned GotoUrlAction navigates it
+ browser_state = MagicMock()
+
+ async def _new_page() -> Any:
+ context.pages.append(magic_page)
+ context.emit_page(magic_page)
+ return magic_page
+
+ browser_state.new_page = _new_page
+
+ from skyvern.forge.sdk.schemas.totp_codes import OTPType
+
+ otp = MagicMock()
+ otp.get_otp_type.return_value = OTPType.MAGIC_LINK
+ otp.value = "https://magic.example/verify"
+
+ agent = ForgeAgent()
+ with (
+ patch("skyvern.forge.agent.poll_otp_value", AsyncMock(return_value=otp)),
+ patch("skyvern.forge.agent.skyvern_context.ensure_context", return_value=ctx),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),
+ ):
+ actions = await agent.handle_potential_magic_link(
+ task, step, scraped_page, browser_state, {"should_verify_by_magic_link": True}
+ )
+ # A durable download credit fires after the tab was created but before the returned navigation runs.
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert actions and actions[0].is_magic_link, "magic-link flow must still return the navigation action"
+ assert not magic_page.is_closed(), "a retired magic-link tab must not be closed by a delayed download credit"
+
+
+# --- Recovered working page is intentional/persistent (SKY-15371 PR A) -------------------------------
+# _recover_download_page recreates the working page (direct new_page path) while the download context.on("page")
+# owner can still be armed, so the replacement joins the context and is recorded as a blank late candidate. A
+# delayed download credit firing during the recovery navigation must not close this deliberate page. (The
+# reconnect path builds the page on a fresh context with no owner armed, so it is never recorded -- no test
+# theater is invented for it.)
+
+
+async def test_recovered_working_page_survives_delayed_credit_direct_new_page(tmp_path: Path) -> None:
+ from skyvern.webeye.actions.handler import _recover_download_page
+
+ task, step, scraped_page, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ ctx.arm_download_popup_context_listener(
+ task.task_id,
+ context,
+ lambda child: ctx.record_download_popup_late_candidate(task.task_id, child) if child is not opener else None,
+ )
+
+ # A genuine same-task blank download late candidate that MUST still close on credit.
+ sibling_dl = _FakePage(context, ":", events, "sibling_dl")
+ context.pages.append(sibling_dl)
+ ctx.record_download_popup_late_candidate(task.task_id, sibling_dl)
+
+ replacement = _FakePage(context, ":", events, "replacement") # blank until recovery navigation commits it
+ browser_state = MagicMock()
+
+ async def _new_page() -> Any:
+ context.pages.append(replacement)
+ context.emit_page(replacement) # the replacement joins the initiating context (recorded by the owner)
+ return replacement
+
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+
+ async def _navigate(*_a: Any, **_k: Any) -> None:
+ # A durable download credit fires WHILE the recovery navigation is still awaiting.
+ await ForgeAgent()._close_credited_download_popups(task, credit_browser_state)
+
+ browser_state.new_page = _new_page
+ browser_state.navigate_to_url = _navigate
+ browser_state.set_active_page = AsyncMock()
+
+ with (
+ patch(f"{_HANDLER}.skyvern_context.current", return_value=ctx),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),
+ ):
+ result = await _recover_download_page(
+ browser_state, task, page_url_before_download="http://origin/", timeout_seconds=5.0, recovery_site="test"
+ )
+
+ assert result is replacement, "recovery must return the replacement working page"
+ assert not replacement.is_closed(), "the deliberate replacement working page must survive a delayed credit"
+ assert sibling_dl.is_closed(), "a genuine same-task blank download late candidate must still close on credit"
+
+
[email protected]("late_url", [":", "about:blank", "", "http://origin/receipt"])
+async def test_late_and_strong_candidates_close_once_after_credit_regardless_of_url(late_url: str) -> None:
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ late = _FakePage(context, late_url, events, "late")
+ strong = _FakePage(context, late_url, events, "strong")
+ foreign = _FakePage(_FakeContext(), late_url, events, "foreign")
+ context.pages.extend([opener, late, strong])
+ for page in (late, strong, foreign):
+ ctx.record_download_popup_late_candidate(task.task_id, page)
+ ctx.record_download_popup_claim(task.task_id, strong)
+ ctx.record_download_popup_claim(task.task_id, foreign)
+
+ credit_browser_state = MagicMock()
+ credit_browser_state.browser_context = context
+ agent = ForgeAgent()
+ with (
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),
+ patch.object(strong, "is_closed", return_value=False),
+ ):
+ await agent._close_credited_download_popups(task, credit_browser_state)
+
+ assert late.is_closed(), "durable credit closes an owned late candidate regardless of its URL"
+ assert strong.is_closed()
+ assert events.count("late:close_start") == 1
+ assert events.count("strong:close_start") == 1
+ assert not foreign.is_closed()
+ assert not opener.is_closed()
+ assert ctx.download_popup_claims == {}
+ assert ctx.download_popup_late_candidates == {}
+
+
+async def test_late_candidates_share_claim_close_deadline() -> None:
+ task, _step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ claimed = _FakePage(context, ":", events, "claimed", close_hangs=True)
+ late = _FakePage(context, "http://origin/receipt", events, "late")
+ ctx.record_download_popup_claim(task.task_id, claimed)
+ ctx.record_download_popup_late_candidate(task.task_id, late)
+ browser_state = MagicMock(browser_context=context)
+
+ with (
+ patch(f"{_AGENT}.skyvern_context.current", return_value=ctx),
+ patch(f"{_AGENT}.BROWSER_PAGE_CLOSE_TIMEOUT", 0.05),
+ ):
+ await asyncio.wait_for(ForgeAgent()._close_credited_download_popups(task, browser_state), timeout=1)
+
+ assert "claimed:close_hang" in events
+ assert "late:close_start" not in events, "the hung claim spent the shared budget"
+ assert ctx.download_popup_claims == {}
+ assert ctx.download_popup_late_candidates == {}
+
+
+def test_cleanup_outgoing_context_detaches_all_listeners_and_clears_state() -> None:
+ ctx = SkyvernContext(task_id="t-out")
+ context = _FakeContext()
+ ctx.arm_download_popup_context_listener("t-out", context, lambda _p: None)
+ ctx.record_download_popup_claim("t-out", object())
+ ctx.record_download_popup_late_candidate("t-out", object())
+ assert context.page_listener_count() == 1
+
+ # The exact hook reset/replace/_restore invoke on the outgoing context.
+ _skvctx._cleanup_outgoing_context(ctx)
+
+ assert context.page_listener_count() == 0, "outgoing-context teardown must detach the context.on('page') owner"
+ assert ctx.download_popup_context_listeners == {}
+ assert ctx.download_popup_claims == {}
+ assert ctx.download_popup_late_candidates == {}
+
+
+def test_scoped_child_cleanup_does_not_detach_main_task_listener() -> None:
+ main_ctx = SkyvernContext(task_id="main")
+ context = _FakeContext()
+ main_ctx.arm_download_popup_context_listener("main", context, lambda _p: None)
+ token = _skvctx._context.set(main_ctx) # raw set so no cleanup is triggered on the main context
+ try:
+ child = SkyvernContext(task_id="child")
+ with _skvctx.scoped(child):
+ pass # on exit, _restore cleans the CHILD context (empty buckets), not main
+ assert context.page_listener_count() == 1, "scoped child teardown must not detach the main task's listener"
+ assert "main" in main_ctx.download_popup_context_listeners
+ finally:
+ _skvctx._context.reset(token)
+
+
+def test_detach_all_swallows_remove_listener_error_and_clears_rest() -> None:
+ ctx = SkyvernContext(task_id="t1")
+
+ class _Boom:
+ def on(self, *_a: Any) -> None:
+ pass
+
+ def remove_listener(self, *_a: Any) -> None:
+ raise RuntimeError("context already gone")
+
+ good = _FakeContext()
+ ctx.arm_download_popup_context_listener("t1", _Boom(), lambda _p: None)
+ ctx.arm_download_popup_context_listener("t2", good, lambda _p: None)
+ ctx.record_download_popup_claim("t1", object())
+ ctx.record_download_popup_late_candidate("t2", object())
+
+ ctx.detach_all_download_popup_context_listeners() # the raising listener must not abort the rest
+
+ assert good.page_listener_count() == 0, "a remove_listener failure on one listener must not skip the others"
+ assert ctx.download_popup_context_listeners == {}
+ assert ctx.download_popup_claims == {}
+ assert ctx.download_popup_late_candidates == {}
+
+
[email protected]("adopt", ["none", "strong", "late"])
[email protected]("outcome", ["success", "failure", "exception"])
+async def test_next_action_stops_capture_but_preserves_prior_reservations(
+ tmp_path: Path, adopt: str, outcome: str
+) -> None:
+ task, step, scraped, ctx, events = _make_env(download_timeout=0.01)
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ first = ClickAction(element_id="download", download=False)
+ strong = _FakePage(context, "http://origin/viewer", events, "strong")
+ candidate = _FakePage(context, "about:blank", events, "candidate")
+ later_popup = _FakePage(context, "http://origin/auth", events, "auth")
+
+ async def first_inner(**_kwargs: Any) -> list[ActionSuccess]:
+ context.pages.append(strong)
+ context.emit_page(strong)
+ for callback in list(opener._popup_cbs):
+ callback(strong)
+ return [ActionSuccess()]
+
+ with ExitStack() as stack:
+ _enter_patches(stack, _app_mock(first), ctx, tmp_path, first_inner)
+ await ActionHandler.handle_action(scraped, task, step, opener, first, file_download_false_click_eligible=True)
+ context.pages.append(candidate)
+ context.emit_page(candidate)
+ assert ctx.download_popup_claims[task.task_id] == [strong]
+ assert ctx.download_popup_late_candidates[task.task_id] == [strong, candidate]
+
+ async def later_inner(**_kwargs: Any) -> list[ActionSuccess | ActionFailure]:
+ context.pages.append(later_popup)
+ context.emit_page(later_popup)
+ if outcome == "exception":
+ raise RuntimeError("unrelated action failed")
+ if outcome == "failure":
+ return [ActionFailure(Exception("unrelated action failed"))]
+ return [ActionSuccess()]
+
+ stack.enter_context(patch.object(ActionHandler, "_handle_action", side_effect=later_inner))
+ later = InputTextAction(element_id="verification", text="test")
+ if outcome == "exception":
+ stack.enter_context(pytest.raises(RuntimeError, match="unrelated action failed"))
+ await ActionHandler.handle_action(
+ scraped,
+ task,
+ step,
+ {"none": opener, "strong": strong, "late": candidate}[adopt],
+ later,
+ file_download_false_click_eligible=True,
+ )
+
+ assert not strong.is_closed()
+ assert not candidate.is_closed()
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, MagicMock(browser_context=context))
+ assert strong.is_closed() is (adopt != "strong")
+ assert candidate.is_closed() is (adopt != "late")
+ assert not later_popup.is_closed()
+ assert not opener.is_closed()
+ assert context.page_listener_count() == 0
+ assert ctx.download_popup_claims == ctx.download_popup_late_candidates == {}
+
+
[email protected]("teardown", ["clear", "context"])
+def test_detached_callback_cannot_recreate_reservations(teardown: str) -> None:
+ ctx = SkyvernContext(task_id="task")
+ context = _FakeContext()
+ ctx.arm_download_popup_context_listener(
+ "task", context, lambda page: ctx.record_download_popup_late_candidate("task", page)
+ )
+ queued_callback = context._page_cbs[0]
+ context.remove_listener = MagicMock(side_effect=RuntimeError("context recycled"))
+ if teardown == "clear":
+ ctx.clear_download_popup_claims("task")
+ else:
+ ctx.detach_all_download_popup_context_listeners()
+ queued_callback(object())
+ assert ctx.download_popup_late_candidates == {}
+ assert ctx.download_popup_context_listeners == {}
+
+
[email protected]("failure", ["exception", "cancel", "result", "persist"])
[email protected]("dispatched", [True, False])
[email protected]("prior_reservations", [False, True])
+async def test_failed_action_reservation_release_is_keyed_on_browser_dispatch(
+ tmp_path: Path, failure: str, dispatched: bool, prior_reservations: bool
+) -> None:
+ """A failed action's download reservations are decided by the dispatch boundary, not result status.
+
+ A dispatched-then-failed epoch keeps its action-owned reservation so the task's durable-credit seam
+ can still close the marker popup (the SKY-15371 dispatch-boundary fix); a no-dispatch failed exit
+ (stale abort, already-in-desired-state suppression, pre-handler error) releases its epoch as before.
+ Cancellation is the exception: it re-raises through the step loop with no next action and no
+ clean_up_task, so the epoch detaches its listener and releases its reservation at the seam even when
+ it was dispatched. In every case prior-epoch reservations survive.
+ """
+ task, step, scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ candidate = _FakePage(context, "about:blank", events, "candidate")
+ prior_claim = _FakePage(context, "about:blank", events, "prior-claim")
+ prior_late = _FakePage(context, "about:blank", events, "prior-late")
+ if prior_reservations:
+ ctx.record_download_popup_claim(task.task_id, prior_claim)
+ ctx.record_download_popup_late_candidate(task.task_id, prior_late)
+ action = ClickAction(element_id="download", download=False)
+ app_mock = _app_mock(action)
+
+ async def inner(**_kwargs: Any) -> list[Any]:
+ # Mirror the real type-handler seam: a committed browser dispatch sets the boundary flag; a
+ # no-dispatch exit (stale abort / desired-state suppression) leaves it False.
+ _browser_dispatch_committed.set(dispatched)
+ context.emit_page(candidate)
+ for callback in list(opener._popup_cbs):
+ callback(candidate)
+ if failure == "cancel":
+ raise asyncio.CancelledError()
+ if failure == "exception":
+ raise RuntimeError("action failed")
+ if failure == "result":
+ return [ActionFailure(Exception("action failed"))]
+ return [ActionSuccess()]
+
+ if failure == "persist":
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock(side_effect=RuntimeError("persistence failed"))
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, inner)
+ if failure != "result":
+ stack.enter_context(pytest.raises(asyncio.CancelledError if failure == "cancel" else RuntimeError))
+ await ActionHandler.handle_action(scraped, task, step, opener, action, file_download_false_click_eligible=True)
+
+ assert not candidate.is_closed()
+ # A dispatched-then-failed epoch keeps its context owner armed to the next action's boundary (as a
+ # successful dispatch does), so an after-return child is still observed; a no-dispatch exit stops it
+ # now. Cancellation keeps nothing armed: it has no next-action boundary to invalidate capture at.
+ keeps_armed = dispatched and failure != "cancel"
+ assert context.page_listener_count() == (1 if keeps_armed else 0)
+ # The dispatched-then-failed epoch retains its action-owned candidate until durable credit; the
+ # no-dispatch epoch has already released it, and cancellation releases its epoch at the seam.
+ assert ctx.has_download_popup_claim(task.task_id, candidate) is keeps_armed
+
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, MagicMock(browser_context=context))
+ # Durable credit closes exactly the reservations still held: the retained candidate, plus any
+ # prior-epoch reservations, which always survive an intervening action's failure.
+ assert candidate.is_closed() is keeps_armed
+ assert prior_claim.is_closed() is prior_reservations
+ assert prior_late.is_closed() is prior_reservations
+ assert not opener.is_closed()
+ assert ctx.download_popup_claims == ctx.download_popup_late_candidates == {}
+
+
+async def test_dispatched_cancellation_detaches_listener_and_releases_epoch(tmp_path: Path) -> None:
+ """A dispatched action cancelled mid-flight (elapsed-time timeout / user cancel) re-raises through the
+ step loop's ``except CancelledError``, which -- unlike every failure handler -- re-raises without
+ running clean_up_task. There is therefore no next action and no teardown to invalidate capture at a
+ later boundary, so the epoch must detach its ``context.on("page")`` owner and release its own
+ reservation right at the cancellation seam. Holding the listener armed (the ordinary failed-dispatch
+ behavior) would strand it on the live BrowserContext, where a page that joins during teardown would be
+ recorded by the orphaned callback -- recreating a reservation the run can never credit or close."""
+ task, step, scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ prior_claim = _FakePage(context, "about:blank", events, "prior-claim")
+ ctx.record_download_popup_claim(task.task_id, prior_claim)
+ candidate = _FakePage(context, "about:blank", events, "candidate")
+ action = ClickAction(element_id="download", download=False)
+ app_mock = _app_mock(action)
+
+ async def inner(**_kwargs: Any) -> list[Any]:
+ # Committed browser dispatch; a same-context child joins during the armed seam and is recorded by
+ # the context owner, then the action is cancelled before it can return.
+ _browser_dispatch_committed.set(True)
+ context.emit_page(candidate)
+ raise asyncio.CancelledError()
+
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, inner)
+ with pytest.raises(asyncio.CancelledError):
+ await ActionHandler.handle_action(
+ scraped, task, step, opener, action, file_download_false_click_eligible=True
+ )
+
+ assert context.page_listener_count() == 0, "cancellation left the context owner armed with no boundary to stop it"
+ assert not ctx.has_download_popup_claim(task.task_id, candidate), "cancellation must release its own epoch"
+ assert ctx.has_download_popup_claim(task.task_id, prior_claim), (
+ "a prior-epoch reservation must survive cancellation"
+ )
+ assert not candidate.is_closed(), "releasing the reservation frees the child; the cancel seam does not close it"
+
+ # The detached callback cannot resurrect a reservation for a page that joins during teardown.
+ late_during_teardown = _FakePage(context, "about:blank", events, "late-teardown")
+ context.emit_page(late_during_teardown)
+ assert not ctx.has_download_popup_claim(task.task_id, late_during_teardown), (
+ "an orphaned callback recorded a page after cancellation detached capture"
+ )
+
+
[email protected]("exit_kind", ["stale_skipped", "desired_completed"])
+async def test_no_dispatch_exit_releases_epoch_and_stops_listener(tmp_path: Path, exit_kind: str) -> None:
+ """A true no-dispatch exit (stale abort -> skipped, already-desired suppression -> completed) never
+ owned a download: at wrapper exit its epoch reservations are released and the context listener is
+ stopped, so a later durable credit cannot close a page it spuriously captured; prior reservations
+ opened before this action survive untouched."""
+ task, step, scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ during_seam = _FakePage(context, "about:blank", events, "during-seam")
+ prior_claim = _FakePage(context, "about:blank", events, "prior-claim")
+ ctx.record_download_popup_claim(task.task_id, prior_claim)
+ action = ClickAction(element_id="toggle", download=False)
+ app_mock = _app_mock(action)
+
+ async def inner(**_kwargs: Any) -> list[Any]:
+ # No browser dispatch commits: a stale abort returns before the type-handler seam, and a
+ # desired-state suppression sets the flag back to False. A same-context page still appears
+ # during the armed seam and is captured as a current-epoch candidate.
+ _browser_dispatch_committed.set(False)
+ context.emit_page(during_seam)
+ for callback in list(opener._popup_cbs):
+ callback(during_seam)
+ if exit_kind == "stale_skipped":
+ result = StaleActionAbort()
+ result.skip_remaining_actions = True
+ return [result]
+ return [ActionAbort(desired_state_reached=True)]
+
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, inner)
+ await ActionHandler.handle_action(scraped, task, step, opener, action, file_download_false_click_eligible=True)
+
+ assert context.page_listener_count() == 0, "no-dispatch exit must stop the armed context listener"
+ assert not ctx.has_download_popup_claim(task.task_id, during_seam), "no-dispatch epoch must be released"
+ assert ctx.has_download_popup_claim(task.task_id, prior_claim), "prior-epoch reservation must survive"
+ # A later durable credit closes only the surviving prior reservation, never the spurious capture.
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, MagicMock(browser_context=context))
+ assert not during_seam.is_closed(), "a later credit must not close a page from a no-dispatch epoch"
+ assert prior_claim.is_closed(), "the surviving prior reservation is closed by durable credit"
+
+
+async def test_dispatched_failure_without_credit_releases_at_step_seam(tmp_path: Path) -> None:
+ """A dispatched-then-failed marker stays reserved between the failure and the step's credit seam --
+ so #17139 blank recovery cannot close it mid-flight -- and is released the instant the seam finds no
+ credit, restoring recovery eligibility before the retry scrape."""
+ task, step, scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ marker = _FakePage(context, "about:blank", events, "marker")
+ action = ClickAction(element_id="download", download=False)
+ app_mock = _app_mock(action)
+
+ async def inner(**_kwargs: Any) -> list[Any]:
+ _browser_dispatch_committed.set(True)
+ context.emit_page(marker)
+ for callback in list(opener._popup_cbs):
+ callback(marker)
+ return [ActionFailure(Exception("dispatched then failed"))]
+
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, inner)
+ await ActionHandler.handle_action(scraped, task, step, opener, action, file_download_false_click_eligible=True)
+
+ # Between failure and the credit seam the marker is still reserved: the #17139 guard refuses to close it.
+ assert ctx.has_download_popup_claim(task.task_id, marker), "dispatched-failed marker must stay reserved pre-seam"
+ # The step's complete-on-download seam runs and finds no durable credit: release the deferred epoch now.
+ ctx.apply_pending_download_reservation_release(task.task_id)
+ assert not ctx.has_download_popup_claim(task.task_id, marker), "uncredited marker must release at the seam"
+ assert not marker.is_closed(), "release frees the marker for blank recovery; it does not close it"
+
+
+async def test_dispatched_failure_late_child_after_return_is_captured_and_closed_by_credit(tmp_path: Path) -> None:
+ """A dispatched action can fail for a reason unrelated to its click (a challenge-solver error or a
+ post-click timeout) while the download popup it opened joins the BrowserContext only AFTER
+ ``handle_action`` returns -- before the next action begins. The failure path must keep the
+ ``context.on("page")`` owner armed to that next-action boundary exactly as the success path does, so
+ the late child is recorded and closed by durable credit. Detaching capture at the failed epoch's own
+ exit reopens the after-return/before-next-action race this PR exists to close."""
+ task, step, scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ action = ClickAction(element_id="download", download=False)
+ app_mock = _app_mock(action)
+
+ async def inner(**_kwargs: Any) -> list[Any]:
+ # Committed browser dispatch, then an unrelated failure. Nothing joins the context during the
+ # seam: the popup arrives only after handle_action has already returned.
+ _browser_dispatch_committed.set(True)
+ return [ActionFailure(Exception("challenge solver failed after the click was dispatched"))]
+
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, inner)
+ await ActionHandler.handle_action(scraped, task, step, opener, action, file_download_false_click_eligible=True)
+
+ # Symmetric with the success path: a failed dispatch keeps its context owner armed past return so an
+ # after-return child is still observed before the next action's invalidation boundary.
+ assert context.page_listener_count() == 1, (
+ "a failed dispatch detached the context owner at its own exit; a popup joining before the next action is missed"
+ )
+ late_child = _FakePage(context, "about:blank", events, "late")
+ context.pages.append(late_child)
+ context.emit_page(late_child)
+ assert ctx.has_download_popup_claim(task.task_id, late_child), (
+ "the after-return child of a failed dispatch was not captured"
+ )
+ assert not late_child.is_closed(), "discovery alone must not close a page before durable credit"
+
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, MagicMock(browser_context=context))
+ assert late_child.is_closed(), "durable credit must close the exact after-return child"
+ assert not opener.is_closed()
+ assert context.page_listener_count() == 0
+ assert ctx.download_popup_claims == ctx.download_popup_late_candidates == {}
+
+
[email protected]("second_outcome", ["success", "failure", "no_dispatch"])
[email protected]("after_no_credit_seam", [False, True])
+async def test_dispatched_failure_reservations_survive_a_later_same_batch_action(
+ tmp_path: Path, second_outcome: str, after_no_credit_seam: bool
+) -> None:
+ """A dispatched-then-failed action's owned reservations must survive a later action in the SAME
+ batch (the batch continues on ``stop_execution_on_failure=False`` or the duplicate-element fallback)
+ so durable credit can still close the marker. The deferred release is applied only at the step's
+ complete-on-download no-credit seam -- never at the next action's entry -- while that next action's
+ entry still stops the previous capture listener."""
+ task, step, scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ strong = _FakePage(context, "about:blank", events, "strong")
+ late = _FakePage(context, "about:blank", events, "late")
+ action1 = ClickAction(element_id="download", download=False)
+ app_mock = _app_mock(action1)
+
+ async def first_inner(**_kwargs: Any) -> list[Any]:
+ _browser_dispatch_committed.set(True)
+ for callback in list(opener._popup_cbs):
+ callback(strong)
+ context.emit_page(late)
+ return [ActionFailure(Exception("dispatched then failed"))]
+
+ with ExitStack() as stack:
+ _enter_patches(stack, app_mock, ctx, tmp_path, first_inner)
+ await ActionHandler.handle_action(scraped, task, step, opener, action1, file_download_false_click_eligible=True)
+ assert ctx.has_download_popup_claim(task.task_id, strong), "strong claim must survive the failure"
+ assert ctx.has_download_popup_claim(task.task_id, late), "late candidate must survive the failure"
+ assert context.page_listener_count() == 1, (
+ "the failed epoch's listener stays armed until the next action's entry (symmetric with success)"
+ )
+
+ # A second action in the same batch runs BEFORE any credit seam. It must not release action1's
+ # owned reservations at its entry.
+ later_page = _FakePage(context, "http://origin/next", events, "later")
+
+ async def second_inner(**_kwargs: Any) -> list[Any]:
+ _browser_dispatch_committed.set(second_outcome != "no_dispatch")
+ context.emit_page(later_page)
+ if second_outcome == "failure":
+ return [ActionFailure(Exception("second action failed"))]
+ if second_outcome == "no_dispatch":
+ return [ActionAbort(desired_state_reached=True)]
+ return [ActionSuccess()]
+
+ stack.enter_context(patch.object(ActionHandler, "_handle_action", side_effect=second_inner))
+ second_action = ClickAction(element_id="fallback", download=False)
+ await ActionHandler.handle_action(
+ scraped, task, step, opener, second_action, file_download_false_click_eligible=True
+ )
+
+ # action1's owned reservations still survive after the second action ran.
+ assert ctx.has_download_popup_claim(task.task_id, strong), "the next action must not release action1's strong claim"
+ assert ctx.has_download_popup_claim(task.task_id, late), "the next action must not release action1's late candidate"
+ assert (task.task_id in ctx.pending_download_reservation_release) is (second_outcome != "success")
+ if after_no_credit_seam:
+ ctx.apply_pending_download_reservation_release(task.task_id)
+ retained = not after_no_credit_seam or second_outcome == "success"
+ assert ctx.has_download_popup_claim(task.task_id, strong) is retained
+ assert ctx.has_download_popup_claim(task.task_id, late) is retained
+
+ # Durable credit now closes exactly action1's owned popups.
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, MagicMock(browser_context=context))
+ assert strong.is_closed() is retained
+ assert late.is_closed() is retained
+ assert later_page.is_closed() is (retained and second_outcome != "no_dispatch")
+ assert not opener.is_closed()
+ assert ctx.download_popup_claims == ctx.download_popup_late_candidates == {}
+
+
+def test_earliest_pending_snapshot_retained_and_preserves_prior_reservations() -> None:
+ """Multiple dispatched failures in one step keep the EARLIEST pending pre-dispatch snapshot: at the
+ no-credit seam every reservation minted since that first failure is released, while reservations
+ that predate it survive. A later no-dispatch retain cannot disturb the pending epoch."""
+ ctx = SkyvernContext(task_id="task")
+ prior = object()
+ minted_first = object()
+ minted_second = object()
+ ctx.record_download_popup_claim("task", prior)
+
+ # First dispatched failure stashes its pre-action snapshot (prior only), then mints a claim.
+ ctx.stash_pending_download_reservation_release("task", ctx.snapshot_download_popup_reservations("task"))
+ ctx.record_download_popup_claim("task", minted_first)
+ # A second dispatched failure later in the batch must NOT overwrite the earliest snapshot.
+ ctx.stash_pending_download_reservation_release("task", ctx.snapshot_download_popup_reservations("task"))
+ ctx.record_download_popup_late_candidate("task", minted_second)
+
+ # The no-credit seam applies the earliest snapshot: everything minted since the first failure goes,
+ # the pre-existing reservation stays.
+ ctx.apply_pending_download_reservation_release("task")
+ assert ctx.has_download_popup_claim("task", prior), "a reservation predating the first failure must survive"
+ assert not ctx.has_download_popup_claim("task", minted_first), "a claim minted after the first failure is released"
+ assert not ctx.has_download_popup_claim("task", minted_second), "a candidate minted later is released too"
+ assert "task" not in ctx.pending_download_reservation_release, "the pending release is consumed"
+
+
+ ("action_kind", "setup_result"),
+ [
+ (kind, result)
+ for kind in ("click", "select")
+ for result in ("abort", "success", "no_op_skip", "no_op_complete", "exception", "failure")
+ ]
+ + [("input", "unreported")],
+)
+async def test_setup_effects_determine_wrapper_reservations(
+ tmp_path: Path, setup_result: str, action_kind: str
+) -> None:
+ """Drive real setup dispatch: only explicit no-effect results release the epoch; exceptions retain it."""
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ opener = _FakePage(context, "http://origin/", events, "opener")
+ context.pages.append(opener)
+ setup_popup = _FakePage(context, "about:blank", events, "setup-popup")
+ action: ClickAction | SelectOptionAction | InputTextAction = (
+ SelectOptionAction(element_id="download", option=SelectOption(label="receipt"))
+ if action_kind == "select"
+ else ClickAction(element_id="download", download=False)
+ )
+ if action_kind == "input":
+ action = InputTextAction(element_id="download", text="receipt")
+ ctx.record_download_popup_claim(task.task_id, setup_popup)
+ ctx.stash_pending_download_reservation_release(task.task_id, ((), ()))
+ committed = not setup_result.startswith("no_op")
+
+ scraped_page = MagicMock()
+ scraped_page.id_to_element_dict = {"download": object()}
+
+ app_mock = _app_mock(action)
+ app_mock.AGENT_FUNCTION.wait_for_challenge_solver = AsyncMock()
+
+ async def effectful_setup(*_args: Any, **_kwargs: Any) -> list[Any]:
+ context.emit_page(setup_popup)
+ if setup_result == "exception":
+ raise RuntimeError("setup failed after a possible browser effect")
+ if setup_result == "failure":
+ return [ActionFailure(RuntimeError("setup caught an uncertain click failure"))]
+ if setup_result == "unreported":
+ return [ActionAbort()]
+ if not committed:
+ return [ActionAbort(desired_state_reached=setup_result == "no_op_complete")]
+ if setup_result == "abort":
+ return [ActionAbort(setup_performed=True)]
+ return [ActionSuccess(setup_performed=True)]
+
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{_HANDLER}.app", app_mock))
+ stack.enter_context(patch(f"{_HANDLER}.get_download_dir", MagicMock(return_value=str(tmp_path))))
+ stack.enter_context(patch(f"{_HANDLER}.skyvern_context.current", return_value=ctx))
+ stack.enter_context(patch(f"{_HANDLER}.settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0.0))
+ stack.enter_context(patch.dict(ActionHandler._setup_action_types, {action.action_type: effectful_setup}))
+ await ActionHandler.handle_action(
+ scraped_page, task, step, opener, action, file_download_false_click_eligible=True
+ )
+
+ if action_kind == "input":
+ ctx.apply_pending_download_reservation_release(task.task_id)
+ assert _browser_dispatch_committed.get() is committed
+ assert ctx.has_download_popup_claim(task.task_id, setup_popup) is committed
+ # A committed dispatch keeps its context owner armed to the next action's boundary for every outcome
+ # that reaches the arming seam -- including a later exception/failure (symmetric with success). Only a
+ # pre-arm no-effect exit ("unreported") never armed it.
+ capture_survives = committed and setup_result != "unreported"
+ assert context.page_listener_count() == int(capture_survives)
+ assert not setup_popup.is_closed()
+ later_page = _FakePage(context, "about:blank", events, "later")
+ context.emit_page(later_page)
+ with patch(f"{_AGENT}.skyvern_context.current", return_value=ctx):
+ await ForgeAgent()._close_credited_download_popups(task, MagicMock(browser_context=context))
+ assert setup_popup.is_closed() is committed
+ assert later_page.is_closed() is capture_survives
+ assert not opener.is_closed()
+
+
[email protected]("phase", ["refresh", "screenshot", "context", "settle", "finalize"])
[email protected]("cancel", [False, True])
+async def test_terminal_fault_releases_all_download_reservations(phase: str, cancel: bool) -> None:
+ task, step, _scraped, ctx, events = _make_env()
+ context = _FakeContext()
+ candidate = _FakePage(context, "about:blank", events, "candidate")
+ ctx.record_download_popup_claim(task.task_id, candidate)
+ ctx.record_download_popup_late_candidate(task.task_id, candidate)
+ ctx.arm_download_popup_context_listener(task.task_id, context, lambda page: None)
+ browser_state = MagicMock(browser_context=context)
+ browser_state.get_working_page = AsyncMock(return_value=candidate)
+ fault = asyncio.CancelledError() if cancel else RuntimeError("terminal fault")
+
+ def fail() -> None:
+ raise fault
+
+ with ExitStack() as stack:
+ _cleanup_patches(stack, ctx, task, browser_state, fail if phase == "settle" else lambda: None, [])
+ if phase == "refresh":
+ stack.enter_context(patch(f"{_AGENT}.app.DATABASE.tasks.get_task", AsyncMock(side_effect=fault)))
+ elif phase == "screenshot":
+ browser_state.take_fullpage_screenshot = AsyncMock(side_effect=fault)
+ elif phase == "context":
+ type(browser_state).browser_context = PropertyMock(side_effect=fault)
+ elif phase == "finalize":
+ stack.enter_context(
+ patch.object(ForgeAgent, "_finalize_downloaded_files_for_task", AsyncMock(side_effect=fault))
+ )
+ if cancel or phase in {"refresh", "context"}:
+ stack.enter_context(pytest.raises(asyncio.CancelledError if cancel else Exception))
+ await ForgeAgent().clean_up_task(
+ task, step, need_final_screenshot=phase == "screenshot", download_suffix="file", list_files_before=[]
+ )
+ assert not candidate.is_closed()
+ assert context.page_listener_count() == 0
+ assert ctx.download_popup_claims == ctx.download_popup_late_candidates == {}
diff --git a/tests/unit/test_empty_page_recovery.py b/tests/unit/test_empty_page_recovery.py
index fcf3396dd..cf7151d70 100644
--- a/tests/unit/test_empty_page_recovery.py
+++ b/tests/unit/test_empty_page_recovery.py
@@ -7,13 +7,16 @@ claim read, and the cached-script generation marker filter.
from __future__ import annotations
+import asyncio
+import time
from datetime import UTC, datetime
-from unittest.mock import AsyncMock, MagicMock
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.exceptions import FailedToReloadPage, ScrapingFailedBlankPage
-from skyvern.forge.agent import ForgeAgent
+from skyvern.forge.agent import EMPTY_PAGE_RECOVERY_MAX_ATTEMPTS, ForgeAgent
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.models import StepStatus
@@ -43,6 +46,16 @@ def _page(url: str, child_frame_urls: list[str] | None = None) -> MagicMock:
return page
+_AGENT = "skyvern.forge.agent"
+
+
+def _task_block(*, complete_on_download: bool = True, download_timeout: float | None = None) -> MagicMock:
+ block = MagicMock()
+ block.complete_on_download = complete_on_download
+ block.download_timeout = download_timeout
+ return block
+
+
# ---- Case 1: scraper blank predicate + raise -------------------------------------------------
@@ -312,3 +325,1308 @@ def test_generate_script_skips_internal_recovery_close_action() -> None:
# KeyError and aborts whole-script generation. The filter must drop it so generation succeeds.
fn = _build_block_fn(block, actions=[recovery_action])
assert fn is not None
+
+
+def _recovery_state(dead: MagicMock, survivor: MagicMock) -> MagicMock:
+ state = MagicMock()
+ state.get_working_page = AsyncMock(return_value=dead)
+ state.list_valid_pages = AsyncMock(return_value=[dead, survivor])
+ return state
+
+
+# ---- bounded claimed-dead-blank recovery (deadline anchor) -----------------------------------
+
+
+def test_recovery_grace_is_per_exact_page_with_independent_budgets() -> None:
+ """Each exact Page anchors its OWN recovery-grace start (at its first recovery observation), so a
+ sibling anchored later gets an independent remaining budget; releasing one leaves the other intact."""
+ ctx = SkyvernContext(task_id="t")
+ page_a = MagicMock()
+ page_b = MagicMock()
+ ctx.record_download_popup_claim("t", page_a)
+ ctx.record_download_popup_late_candidate("t", page_b)
+ ctx.anchor_download_popup_recovery_grace("t", page_a, 0.0) # A's recovery grace starts at t=0
+ ctx.anchor_download_popup_recovery_grace("t", page_b, 1000.0) # B's independently at t=1000
+ # At t=1000, A is fully aged for a 60s grace; B still has the full 60s -> independent budgets.
+ assert ctx.remaining_download_popup_grace("t", page_a, 60.0, 1000.0) == 0.0
+ assert ctx.remaining_download_popup_grace("t", page_b, 60.0, 1000.0) == 60.0
+ ctx.retire_intentional_page("t", page_a) # releasing A must not touch B's anchor
+ assert ctx.remaining_download_popup_grace("t", page_a, 60.0, 1000.0) is None
+ assert ctx.remaining_download_popup_grace("t", page_b, 60.0, 1000.0) == 60.0
+
+
+def test_download_popup_claim_baseline_is_per_exact_page_and_lifecycle_bound() -> None:
+ """Each exact Page anchors its OWN baseline snapshot (first-creation wins); a sibling gets an
+ independent snapshot; a page is only dropped once it leaves BOTH registries."""
+ ctx = SkyvernContext(task_id="t")
+ page_a = MagicMock()
+ page_b = MagicMock()
+ ctx.record_download_popup_claim("t", page_a, baseline_files=["/d/a1.pdf"])
+ ctx.record_download_popup_claim("t", page_a, baseline_files=["/d/a2.pdf"]) # re-record must not reset
+ ctx.record_download_popup_late_candidate("t", page_b, baseline_files=["/d/a1.pdf", "/d/b.pdf"])
+ assert ctx.download_popup_claim_baseline_for("t", page_a) == ("/d/a1.pdf",) # first snapshot wins
+ assert ctx.download_popup_claim_baseline_for("t", page_b) == ("/d/a1.pdf", "/d/b.pdf") # sibling independent
+ # Releasing A drops only A's baseline; B (still a late candidate) keeps its own.
+ ctx.release_download_popup_claim("t", page_a)
+ assert ctx.download_popup_claim_baseline_for("t", page_a) is None
+ assert ctx.download_popup_claim_baseline_for("t", page_b) == ("/d/a1.pdf", "/d/b.pdf")
+ # B leaving its last registry drops its baseline too.
+ ctx.discard_download_popup_late_candidate("t", page_b)
+ assert ctx.download_popup_claim_baseline_for("t", page_b) is None
+ assert ctx.download_popup_claim_baseline == {}
+
+
+def test_release_download_popup_claim_frees_exact_page_and_preserves_intentional_semantics() -> None:
+ """The narrow release helper drops one exact page from both registries; ``retire_intentional_page``
+ delegates to it so NEW_TAB/magic-link protection is unchanged (sibling and other pages survive)."""
+ ctx = SkyvernContext(task_id="t")
+ expired = MagicMock()
+ sibling = MagicMock()
+ intentional = MagicMock()
+ ctx.record_download_popup_claim("t", expired, baseline_files=["/d/x.pdf"])
+ ctx.record_download_popup_claim("t", sibling, baseline_files=["/d/y.pdf"])
+ ctx.record_download_popup_late_candidate("t", intentional)
+ ctx.release_download_popup_claim("t", expired)
+ assert ctx.has_download_popup_claim("t", expired) is False
+ assert ctx.has_download_popup_claim("t", sibling) is True
+ # retire_intentional_page still retires a deliberate tab from both registries (unchanged behavior).
+ ctx.retire_intentional_page("t", intentional)
+ assert ctx.has_download_popup_claim("t", intentional) is False
+ assert ctx.has_download_popup_claim("t", sibling) is True
+
+
+def test_action_delta_sweep_anchors_page_baseline_not_baseline_less() -> None:
+ """Finding 1: the action-finally delta sweep must anchor each swept popup's own download baseline --
+ a claim-time local run-dir read unioned with the caller's pre-fetched session snapshot -- not create a
+ baseline-less claim that falls back to the stale block baseline. With an earlier file in that baseline,
+ the swept popup captures it so recovery cannot miscredit that pre-existing file to the popup."""
+ from skyvern.webeye.actions.handler import _PageDeltaBaseline, _record_action_owned_popup_delta
+
+ local_file = "/d/earlier.pdf"
+ session_file = "s3://bucket/earlier-session.pdf"
+ ctx = SkyvernContext(task_id="t")
+ browser_context = MagicMock()
+ initiating = MagicMock()
+ initiating.context = browser_context
+ pre_existing = MagicMock()
+ new_popup = MagicMock()
+ browser_context.pages = [initiating, pre_existing, new_popup] # new_popup added after the baseline
+ baseline = _PageDeltaBaseline(browser_context=browser_context, pages=[initiating, pre_existing])
+
+ with patch("skyvern.webeye.actions.handler.list_files_in_directory", return_value=[local_file]):
+ outcome = _record_action_owned_popup_delta(
+ ctx,
+ task_id="t",
+ initiating_page=initiating,
+ baseline=baseline,
+ download_dir=Path("/d"),
+ attempt_started_at=None,
+ session_baseline_files=[session_file],
+ )
+
+ assert outcome.claimed == 1 and outcome.pages == [new_popup]
+ assert ctx.download_popup_claim_baseline_for("t", new_popup) == (local_file, session_file)
+
+
+def test_retain_prunes_baseline_for_dropped_page_not_just_created_at() -> None:
+ """Finding 2: the retain/pending-release seam (_prune_claim_deadlines) must prune the baseline
+ snapshot for a page dropped from both registries, not only its creation anchor -- otherwise a stale
+ baseline lingers (first-wins + id() reuse) and could attach to a new Page in the miscredit direction."""
+ ctx = SkyvernContext(task_id="t")
+ kept = MagicMock()
+ dropped = MagicMock()
+ ctx.record_download_popup_claim("t", kept, baseline_files=["/d/kept.pdf"])
+ ctx.record_download_popup_claim("t", dropped, baseline_files=["/d/dropped.pdf"])
+ ctx.anchor_download_popup_recovery_grace("t", kept, 0.0)
+ ctx.anchor_download_popup_recovery_grace("t", dropped, 0.0)
+ # Retain only `kept`: `dropped` leaves both registries at this seam and must be fully pruned.
+ ctx.retain_download_popup_reservations("t", ((kept,), ()))
+ assert ctx.download_popup_claim_baseline_for("t", kept) == ("/d/kept.pdf",)
+ assert ctx.download_popup_claim_baseline_for("t", dropped) is None
+ assert ctx.download_popup_recovery_grace_started_at.get("t", {}).get(id(dropped)) is None
+
+
+def test_recovery_grace_anchor_is_first_wins_and_clamps() -> None:
+ ctx = SkyvernContext(task_id="t")
+ page = MagicMock()
+ ctx.record_download_popup_claim("t", page)
+ ctx.anchor_download_popup_recovery_grace("t", page, 0.0)
+ ctx.anchor_download_popup_recovery_grace("t", page, 5.0) # re-entry/cancellation must not reset
+ assert ctx.remaining_download_popup_grace("t", page, 30.0, 0.0) == 30.0
+ assert ctx.remaining_download_popup_grace("t", page, 30.0, 100.0) == 0.0 # aged clamps at 0
+ assert ctx.remaining_download_popup_grace("t", MagicMock(), 30.0, 0.0) is None # no anchor
+
+
+def test_recovery_grace_is_not_anchored_at_claim_mint() -> None:
+ """Round-22 (Blocker 1): the handler's post-click wait owns the pre-recovery phase, so recording a
+ claim (event-recorded OR finally-swept) must NOT start the recovery grace. It is anchored first-wins at
+ the first recovery observation -> a full grace regardless of when the claim was minted; a later
+ observation consumes the remaining budget and never restarts."""
+ ctx = SkyvernContext(task_id="t")
+ page = MagicMock()
+ ctx.record_download_popup_claim("t", page)
+ ctx.record_download_popup_late_candidate("t", page)
+ # Recording alone does not start the recovery grace.
+ assert ctx.remaining_download_popup_grace("t", page, 60.0, 500.0) is None
+ # First recovery observation starts it -> full grace no matter how long ago the claim was minted.
+ ctx.anchor_download_popup_recovery_grace("t", page, 500.0)
+ assert ctx.remaining_download_popup_grace("t", page, 60.0, 500.0) == 60.0
+ # A later recovery observation consumes remaining and never restarts (re-entry/cancellation safe).
+ ctx.anchor_download_popup_recovery_grace("t", page, 540.0)
+ assert ctx.remaining_download_popup_grace("t", page, 60.0, 540.0) == 20.0
+
+
+async def test_first_recovery_grants_full_grace_after_handler_wait() -> None:
+ """Round-22 (Blocker 1): even after the handler's own post-click wait has fully elapsed between claim
+ mint and recovery, the FIRST blank-page recovery observation must receive ~one full recovery grace, not
+ ~0. Proven by capturing the bounded observer's ``remaining``."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ captured: dict[str, float] = {}
+
+ async def _capture(*_a: object, remaining: float, **_k: object) -> bool:
+ captured["remaining"] = remaining
+ return False
+
+ # The claim is minted well before recovery (the handler wait then burns its own budget). Recovery
+ # observes at monotonic t=100 (>> the 45s grace). Anchoring at claim mint would leave < 45s here;
+ # anchoring first-wins at THIS observation leaves the full 45s.
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=[], session_observed=True)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.time.monotonic", return_value=100.0),
+ patch(_OBSERVE, new=AsyncMock(side_effect=_capture)),
+ ):
+ await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _no_credit_state(dead, [dead, survivor]),
+ task_block=_task_block(complete_on_download=True, download_timeout=45.0),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert captured["remaining"] == 45.0 # full grace at first recovery, not ~0
+ finally:
+ skyvern_context.reset()
+
+
+def test_released_page_not_resurrected_by_pending_release_retention() -> None:
+ """Amendment 5 / non-resurrection: once the exact page is released, applying a stale pending-release
+ snapshot that still names it cannot bring the page or its anchor back."""
+ ctx = SkyvernContext(task_id="t")
+ dead = MagicMock()
+ sibling = MagicMock()
+ ctx.record_download_popup_claim("t", dead)
+ ctx.record_download_popup_claim("t", sibling)
+ ctx.anchor_download_popup_recovery_grace("t", dead, 0.0)
+ ctx.stash_pending_download_reservation_release("t", ((dead, sibling), ())) # snapshot includes dead
+ ctx.retire_intentional_page("t", dead) # recovery releases the exact page
+ ctx.apply_pending_download_reservation_release("t") # retention only shrinks; must not re-add dead
+ assert ctx.has_download_popup_claim("t", dead) is False
+ assert ctx.remaining_download_popup_grace("t", dead, 10.0, time.monotonic()) is None
+ assert ctx.has_download_popup_claim("t", sibling) is True
+
+
+def test_recovery_grace_anchor_dropped_only_when_page_leaves_both_registries() -> None:
+ ctx = SkyvernContext(task_id="t")
+ page = MagicMock()
+ ctx.record_download_popup_claim("t", page)
+ ctx.record_download_popup_late_candidate("t", page)
+ ctx.anchor_download_popup_recovery_grace("t", page, 0.0)
+ ctx.discard_download_popup_claim("t", page) # still a late candidate -> anchor survives
+ assert ctx.remaining_download_popup_grace("t", page, 10.0, time.monotonic()) is not None
+ ctx.discard_download_popup_late_candidate("t", page) # gone from both -> anchor dropped
+ assert ctx.remaining_download_popup_grace("t", page, 10.0, time.monotonic()) is None
+ # clear / detach also drop anchors
+ other = MagicMock()
+ ctx.record_download_popup_claim("t", other)
+ ctx.anchor_download_popup_recovery_grace("t", other, 0.0)
+ ctx.clear_download_popup_claims("t")
+ assert ctx.download_popup_recovery_grace_started_at == {}
+
+
+async def test_observe_returns_true_on_direct_final_file(tmp_path: Path) -> None:
+ """Amendment 2/6a: a silent claim whose download materializes as a FINAL file with no
+ ``.crdownload`` is observed as credited (read-only)."""
+ task = make_task(datetime.now(UTC), make_organization(datetime.now(UTC)), task_id="t", workflow_run_id="wr_x")
+ agent = ForgeAgent()
+ before = [str(tmp_path / "old.pdf")]
+ after = before + [str(tmp_path / "new.pdf")]
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=after),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ ):
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=5.0, list_files_before=before, attempt_started_at=None
+ )
+ assert credited is True
+
+
+async def test_observe_returns_false_when_nothing_lands(tmp_path: Path) -> None:
+ task = make_task(datetime.now(UTC), make_organization(datetime.now(UTC)), task_id="t", workflow_run_id="wr_x")
+ agent = ForgeAgent()
+ before = [str(tmp_path / "old.pdf")]
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=before),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ ):
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=0.05, list_files_before=before, attempt_started_at=None
+ )
+ assert credited is False
+
+
+async def test_observe_bounds_session_read_by_remaining_grace(tmp_path: Path) -> None:
+ """Finding A (P1): the session-storage reads in the grace observer must be bounded by the remaining
+ grace, so a STALLED remote read cannot hold the step past the download deadline. A slow read yields no
+ credit and the observer returns within the (tiny) budget rather than blocking on the storage call."""
+ task = make_task(
+ datetime.now(UTC),
+ make_organization(datetime.now(UTC)),
+ task_id="t",
+ workflow_run_id="wr_x",
+ browser_session_id="pbs_x",
+ )
+ agent = ForgeAgent()
+
+ async def _stalled_session_read(**_: object) -> list[str]:
+ await asyncio.sleep(5) # storage stall far exceeding the grace; bounded read must cut it off
+ return ["s3://bucket/late.pdf"]
+
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ patch(f"{_AGENT}.app") as mock_app,
+ ):
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(side_effect=_stalled_session_read)
+ mock_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(side_effect=_stalled_session_read)
+ started = time.monotonic()
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=0.05, list_files_before=[], attempt_started_at=None
+ )
+ elapsed = time.monotonic() - started
+
+ assert credited is False # a stalled read is never credited
+ assert elapsed < 2.0, f"observer held the step {elapsed:.2f}s past the grace on a stalled session read"
+
+
+async def test_observe_bounds_nested_inflight_session_listing(tmp_path: Path) -> None:
+ """Finding A (P1, round 16): the IN-FLIGHT branch calls _wait_for_in_flight_downloads, whose OWN
+ browser-session listing runs before its internal timeout cap. A stall there must not hold the step past
+ the grace either. This drives the in-flight branch (local .crdownload present) with a stalled nested
+ session listing and proves the observer still returns within the budget -- the completed-file read is
+ fast here, unlike ``test_observe_bounds_session_read_by_remaining_grace`` which never reaches this branch."""
+ task = make_task(
+ datetime.now(UTC),
+ make_organization(datetime.now(UTC)),
+ task_id="t",
+ workflow_run_id="wr_x",
+ browser_session_id="pbs_x",
+ )
+ agent = ForgeAgent()
+
+ async def _stalled_session_read(**_: object) -> list[str]:
+ await asyncio.sleep(5) # nested in-flight listing stall far exceeding the grace
+ return ["s3://bucket/late.pdf.crdownload"]
+
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ # A local in-flight file drives the in-flight branch without any session read in _in_flight_present.
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[str(tmp_path / "foo.crdownload")]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.wait_for_download_finished", new=AsyncMock(return_value=None)),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ patch(f"{_AGENT}.app") as mock_app,
+ ):
+ # The completed-file read is fast (empty) so the budget survives to the in-flight branch; only the
+ # nested in-flight session listing stalls.
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[])
+ mock_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(side_effect=_stalled_session_read)
+ started = time.monotonic()
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=0.05, list_files_before=[], attempt_started_at=None
+ )
+ elapsed = time.monotonic() - started
+
+ assert credited is False
+ assert mock_app.STORAGE.list_downloading_files_in_browser_session.await_count >= 1 # the branch was reached
+ assert elapsed < 2.0, f"observer held {elapsed:.2f}s past the grace on a stalled nested in-flight listing"
+
+
+async def test_observe_skips_session_read_when_grace_exhausted() -> None:
+ """Finding B: pin the documented 'exhausted budget skips the read entirely' contract -- with no
+ remaining grace the observer must NOT issue any remote session listing (a doomed remote call), rather
+ than a floored-budget read. Proves the early-out is intentional, not incidental."""
+ task = make_task(
+ datetime.now(UTC),
+ make_organization(datetime.now(UTC)),
+ task_id="t",
+ workflow_run_id="wr_x",
+ browser_session_id="pbs_x",
+ )
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=Path("/tmp")),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ patch(f"{_AGENT}.app") as mock_app,
+ ):
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[])
+ mock_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=0.0, list_files_before=[], attempt_started_at=None
+ )
+ assert credited is False
+ mock_app.STORAGE.list_downloaded_files_in_browser_session.assert_not_awaited()
+ mock_app.STORAGE.list_downloading_files_in_browser_session.assert_not_awaited()
+
+
+async def test_session_listing_error_during_grace_waits_then_releases_and_recovers(tmp_path: Path) -> None:
+ """Round-17 B: a NON-timeout session-listing failure during the dead-blank grace must be treated as an
+ empty observation, not propagated. The observer must still wait out the remaining grace and return no
+ credit, so _empty_page_recovery_plan releases the exact claim and recovers -- rather than the error
+ escaping to the broad catch and re-raising the original blank-page failure."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=[], session_observed=True)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(
+ side_effect=RuntimeError("transient session storage failure")
+ )
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(
+ side_effect=RuntimeError("transient session storage failure")
+ )
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ # Listing error -> empty observation -> no credit -> release the exact claim + recover (not re-raise).
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ assert ctx.has_download_popup_claim(task.task_id, dead) is False
+ finally:
+ skyvern_context.reset()
+
+
+async def test_nested_inflight_waiter_error_during_grace_waits_then_releases_and_recovers(tmp_path: Path) -> None:
+ """Round-18 B: the in-flight branch calls _wait_for_in_flight_downloads, whose OWN session listing can
+ raise a NON-timeout error. That must be contained as no settle for the iteration -- the observer keeps
+ waiting to grace expiry and returns no credit, so _empty_page_recovery_plan releases the exact claim and
+ recovers -- rather than the error escaping to the broad catch and re-raising the original blank failure."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=[], session_observed=True)
+ skyvern_context.set(ctx)
+ waiter = AsyncMock(side_effect=RuntimeError("transient session storage failure in the nested waiter"))
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ # A local in-flight file drives the in-flight branch, so the nested waiter is reached; the
+ # completed-file reads stay empty so nothing is ever credited.
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[str(tmp_path / "foo.crdownload")]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.ForgeAgent._wait_for_in_flight_downloads", new=waiter),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[])
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ # Nested waiter error -> contained -> no credit -> release the exact claim + recover (not re-raise).
+ assert waiter.await_count >= 1 # the in-flight branch (and the failing nested waiter) was reached
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ assert ctx.has_download_popup_claim(task.task_id, dead) is False
+ finally:
+ skyvern_context.reset()
+
+
+async def test_sibling_delta_popup_not_credited_by_sibling_file_and_settles_own_download(tmp_path: Path) -> None:
+ """Round-19: two blank popups claimed together in one delta sweep are same-action siblings with no
+ file->page mapping. In a NON-complete block, sibling #2's dead-blank recovery must NOT early-credit and
+ close on sibling #1's completed file (which landed after the shared snapshot); it must keep observing so
+ its OWN in-flight download can settle first, rather than being cancelled by an early close."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead2 = _page("about:blank") # the sibling under observation (its own download is still in flight)
+ sibling1 = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ # Both claimed together -> marked as sibling-ambiguous. dead2's baseline is empty: sibling #1's file
+ # settled only AFTER the shared sweep snapshot, so it is "new" against dead2's baseline.
+ ctx.record_download_popup_claim(task.task_id, sibling1, baseline_files=[])
+ ctx.record_download_popup_claim(task.task_id, dead2, baseline_files=[])
+ ctx.mark_download_popup_claim_delta_siblings(task.task_id, [sibling1, dead2])
+ skyvern_context.set(ctx)
+ waiter = AsyncMock(return_value=None)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ # sibling #1's COMPLETED file is present (new vs dead2's empty baseline); dead2's OWN download
+ # is still an in-flight partial, which drives the in-flight settle branch.
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[str(tmp_path / "sibling1.pdf")]),
+ patch(
+ f"{_AGENT}.list_downloading_files_in_directory",
+ return_value=[str(tmp_path / "dead2-own.crdownload")],
+ ),
+ patch(f"{_AGENT}.ForgeAgent._wait_for_in_flight_downloads", new=waiter),
+ ):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead2, survivor),
+ task_block=_task_block(complete_on_download=False, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ # The sibling's file did NOT short-circuit dead2's grace: the in-flight settle branch was reached,
+ # giving dead2's own download its full budget before recovery closes the dead blank.
+ assert waiter.await_count >= 1
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ finally:
+ skyvern_context.reset()
+
+
+async def test_lone_delta_popup_keeps_fast_new_file_credit(tmp_path: Path) -> None:
+ """Round-19 non-regression: the sibling suppression must be scoped to multi-popup sweeps. A LONE
+ claimed popup (not marked as a sibling) owns a new completed file unambiguously (round-14), so its
+ recovery still credits early on that file and never needs the in-flight settle branch."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=[]) # lone claim, never marked
+ skyvern_context.set(ctx)
+ waiter = AsyncMock(return_value=None)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[str(tmp_path / "own.pdf")]),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.ForgeAgent._wait_for_in_flight_downloads", new=waiter),
+ ):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=False, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ # Credited early on its own new file: the in-flight settle branch was never needed.
+ assert waiter.await_count == 0
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ finally:
+ skyvern_context.reset()
+
+
+_OBSERVE = f"{_AGENT}.ForgeAgent._observe_claimed_download_within_grace"
+
+
+def _no_credit_state(working: MagicMock, valid_pages: list[MagicMock]) -> MagicMock:
+ state = MagicMock()
+ state.get_working_page = AsyncMock(return_value=working)
+ state.list_valid_pages = AsyncMock(return_value=valid_pages)
+ return state
+
+
+async def test_recovery_no_survivor_keeps_claim_and_consumes_no_attempt() -> None:
+ """Round-21: grace expires with no credit and NO http survivor -> return None with the exact claim,
+ its baseline, and its creation anchor all intact (so terminal cleanup can still settle a late
+ download under the original claim), and no recovery attempt consumed. The release must not precede
+ the survivor check."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=["/d/x.pdf"], session_observed=True)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with patch(_OBSERVE, new=AsyncMock(return_value=False)):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _no_credit_state(dead, [dead]), # only the dead blank; no survivor
+ task_block=_task_block(complete_on_download=True, download_timeout=0.01),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result is None
+ assert ctx.has_download_popup_claim(task.task_id, dead) is True
+ assert ctx.download_popup_claim_baseline_for(task.task_id, dead) is not None
+ assert ctx.remaining_download_popup_grace(task.task_id, dead, 60.0, time.monotonic()) is not None
+ assert ctx.empty_page_recovery_attempts.get(task.task_id, 0) == 0
+ finally:
+ skyvern_context.reset()
+
+
+async def test_recovery_cap_reached_keeps_claim_and_consumes_no_attempt() -> None:
+ """Round-21: grace expires with no credit and the attempt cap is already reached -> return None with
+ the exact claim intact and no additional attempt consumed. The release must not precede the cap
+ check."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=["/d/x.pdf"], session_observed=True)
+ ctx.empty_page_recovery_attempts[task.task_id] = EMPTY_PAGE_RECOVERY_MAX_ATTEMPTS
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with patch(_OBSERVE, new=AsyncMock(return_value=False)):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _no_credit_state(dead, [dead, survivor]), # survivor present, but cap is exhausted
+ task_block=_task_block(complete_on_download=True, download_timeout=0.01),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result is None
+ assert ctx.has_download_popup_claim(task.task_id, dead) is True
+ assert ctx.download_popup_claim_baseline_for(task.task_id, dead) is not None
+ assert ctx.empty_page_recovery_attempts[task.task_id] == EMPTY_PAGE_RECOVERY_MAX_ATTEMPTS
+ finally:
+ skyvern_context.reset()
+
+
[email protected]("mutation", ["page_replaced", "claim_adopted"])
+async def test_recovery_toctou_during_grace_fails_closed_with_claim_intact(mutation: str) -> None:
+ """Round-21 TOCTOU: the grace wait is a window in which the working page can be replaced or the exact
+ claim adopted. Revalidation before mutation must fail closed -> return None, no recovery attempt
+ consumed, and (for the replaced case) the ORIGINAL exact claim intact -- recovery must never close a
+ page other than the one it observed, nor recover a page whose ownership was handed off."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=["/d/x.pdf"], session_observed=True)
+ skyvern_context.set(ctx)
+ state = MagicMock()
+ observe: AsyncMock
+ if mutation == "page_replaced":
+ replacement = _page("https://example.test/replacement")
+ replacement.is_closed.return_value = False
+ state.get_working_page = AsyncMock(side_effect=[dead, replacement]) # replaced during the wait
+ state.list_valid_pages = AsyncMock(return_value=[replacement, survivor])
+ observe = AsyncMock(return_value=False)
+ else: # claim adopted (released) mid-wait
+
+ async def _observe_then_adopt(*_: object, **__: object) -> bool:
+ ctx.retire_intentional_page(task.task_id, dead)
+ return False
+
+ state.get_working_page = AsyncMock(return_value=dead)
+ state.list_valid_pages = AsyncMock(return_value=[dead, survivor])
+ observe = AsyncMock(side_effect=_observe_then_adopt)
+ try:
+ agent = ForgeAgent()
+ with patch(_OBSERVE, new=observe):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ state,
+ task_block=_task_block(complete_on_download=True, download_timeout=0.01),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result is None
+ assert ctx.empty_page_recovery_attempts.get(task.task_id, 0) == 0
+ if mutation == "page_replaced":
+ assert ctx.has_download_popup_claim(task.task_id, dead) is True
+ finally:
+ skyvern_context.reset()
+
+
+async def test_recovery_eligible_releases_only_exact_claim_and_consumes_one_attempt() -> None:
+ """Round-21 non-regression: survivor present and cap available -> exactly one internal recovery
+ action, one attempt consumed, ONLY the exact page's claim released, and a sibling claim preserved."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ sibling = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead, baseline_files=["/d/x.pdf"], session_observed=True)
+ ctx.record_download_popup_claim(task.task_id, sibling, baseline_files=["/d/y.pdf"], session_observed=True)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with patch(_OBSERVE, new=AsyncMock(return_value=False)):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _no_credit_state(dead, [dead, survivor]),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.01),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ assert ctx.has_download_popup_claim(task.task_id, dead) is False # exact claim released
+ assert ctx.has_download_popup_claim(task.task_id, sibling) is True # sibling preserved
+ assert ctx.empty_page_recovery_attempts[task.task_id] == 1
+ finally:
+ skyvern_context.reset()
+
+
+async def test_observe_returns_true_on_session_only_final_file(tmp_path: Path) -> None:
+ """A completed download that lands ONLY in persistent browser-session storage (not the local run
+ dir) must be observed as credited, mirroring the authoritative credit seam's local+session union."""
+ task = make_task(
+ datetime.now(UTC),
+ make_organization(datetime.now(UTC)),
+ task_id="t",
+ workflow_run_id="wr_x",
+ browser_session_id="pbs_x",
+ )
+ agent = ForgeAgent()
+ before = [str(tmp_path / "old.pdf")] # local baseline; session had no files before the step
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=before), # local run dir unchanged
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ patch(f"{_AGENT}.app") as mock_app,
+ ):
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=["s3://bucket/new.pdf"])
+ mock_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=5.0, list_files_before=before, attempt_started_at=None
+ )
+ assert credited is True
+
+
+async def test_inflight_crdownload_settling_during_grace_does_not_credit(tmp_path: Path) -> None:
+ """Finding 2: an earlier download in-flight at claim time (``foo.pdf.crdownload`` in the baseline)
+ settles to ``foo.pdf`` during the grace. Normalized identity comparison must collapse the two shapes
+ so the settle is NOT read as a new arrival that would miscredit this claimed page."""
+ task = make_task(datetime.now(UTC), make_organization(datetime.now(UTC)), task_id="t", workflow_run_id="wr_x")
+ agent = ForgeAgent()
+ baseline = [str(tmp_path / "foo.pdf.crdownload")] # earlier download in-flight when the claim was created
+ settled = [str(tmp_path / "foo.pdf")] # same download, settled to its final name during the grace
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=settled),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=SkyvernContext(task_id="t")),
+ ):
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=0.05, list_files_before=baseline, attempt_started_at=None
+ )
+ assert credited is False
+
+
+async def test_session_only_file_present_at_claim_time_does_not_credit_but_later_arrival_does(
+ tmp_path: Path,
+) -> None:
+ """Finding 1: per-claim baselines include the pre-click session snapshot (captured from the single
+ authoritative pre-click listing). A session-only file present when the claim is created is in the
+ baseline (must NOT credit); a session-only file that arrives AFTER the claim is new (must credit)."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ session_file = "s3://bucket/earlier-session.pdf"
+
+ async def _run(claim_session_files: list[str], observed_session_files: list[str]):
+ # Claim-time session baseline = the pre-click session snapshot the authoritative read captures.
+ claim_baseline = list(claim_session_files)
+ ctx = SkyvernContext(task_id="t")
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ # main-path claims are session-observed, so recovery unions session files for them
+ ctx.record_download_popup_claim("t", dead, baseline_files=claim_baseline, session_observed=True)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(
+ return_value=observed_session_files
+ )
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ return await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[], # stale block baseline never contained the session file
+ )
+ finally:
+ skyvern_context.reset()
+
+ # Present at claim time -> in the union claim baseline -> NOT credited -> release + recover.
+ present = await _run(claim_session_files=[session_file], observed_session_files=[session_file])
+ assert present is not None and len(present) == 1 and present[0].is_internal_recovery is True
+
+ # Arrived only after the claim -> not in the baseline -> credited -> complete-on-download short-circuit.
+ after = await _run(claim_session_files=[], observed_session_files=[session_file])
+ assert after == []
+
+
+async def test_false_click_claim_not_credited_by_session_only_file(tmp_path: Path) -> None:
+ """Round-11: a claim WITHOUT a session baseline (the v4 false-click path, local-only, no remote
+ listing) must NOT be credited by a session-only file that appeared after the block baseline. The
+ observer has no session reference for such a claim, so it must not union session files -- otherwise an
+ earlier action's session-only file reads as new and prematurely completes / wrongly releases."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ session_file = "s3://bucket/earlier-action-session.pdf"
+ ctx = SkyvernContext(task_id="t")
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ # A false-click claim: local-only baseline, NOT session-observed (session_observed defaults to False).
+ ctx.record_download_popup_claim("t", dead, baseline_files=[])
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[session_file])
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ # Not session-observed -> the session file is ignored -> not credited -> release + recover.
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ # And the observer never consulted session storage for this local-only claim.
+ agent_app.STORAGE.list_downloaded_files_in_browser_session.assert_not_awaited()
+ agent_app.STORAGE.list_downloading_files_in_browser_session.assert_not_awaited()
+ finally:
+ skyvern_context.reset()
+
+
+async def test_finally_resnapshot_augments_stale_event_recorded_session_baseline(tmp_path: Path) -> None:
+ """Round-12: an event-recorded popup anchors the STALE pre-action session snapshot (empty here). An
+ earlier action's session download settles before the popup is minted; the action-finally resnapshot
+ re-records the same popup and AUGMENTS (unions) its session baseline -- setdefault would keep the stale
+ first snapshot. Recovery must then NOT treat that earlier file as new. A popup whose own download lands
+ only after its mint (absent from the augment) must still credit."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ earlier_session_file = "s3://bucket/earlier-action.pdf"
+
+ async def _run(finally_session: list[str], observed_session: list[str]):
+ ctx = SkyvernContext(task_id="t")
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ # Event-recorded (sync popup callback): stale pre-action session snapshot is empty.
+ ctx.record_download_popup_claim("t", dead, baseline_files=[], session_observed=True, session_baseline_files=[])
+ # Action-finally resnapshot re-records the SAME page with the fresh session view.
+ ctx.record_download_popup_claim(
+ "t", dead, baseline_files=[], session_observed=True, session_baseline_files=finally_session
+ )
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=observed_session)
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ return await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ finally:
+ skyvern_context.reset()
+
+ # Earlier action's file settled by the finally -> augmented into the baseline -> NOT credited -> recover.
+ present = await _run(finally_session=[earlier_session_file], observed_session=[earlier_session_file])
+ assert present is not None and len(present) == 1 and present[0].is_internal_recovery is True
+
+ # The popup's own download lands only after its mint AND after the finally (absent from the augment)
+ # -> not in the baseline -> credited -> complete-on-download short-circuit.
+ after = await _run(finally_session=[], observed_session=["s3://bucket/own-download.pdf"])
+ assert after == []
+
+
+async def test_own_inflight_partial_excluded_from_baseline_still_credits(tmp_path: Path) -> None:
+ """Round-13 (observer view): the popup's OWN download in-flight at the finally must NOT be in its
+ baseline, so when it settles during a later grace the observer credits it. If the partial's identity had
+ been augmented in (the round-12 over-augment), normalize would collapse the settled URI to it and drop
+ the credit -- releasing/failing the popup for a slightly-late own download."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ own_partial = "s3://bucket/own.pdf.crdownload"
+ own_settled = "s3://bucket/own.pdf"
+
+ async def _run(session_baseline: list[str]):
+ ctx = SkyvernContext(task_id="t")
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(
+ "t", dead, baseline_files=[], session_observed=True, session_baseline_files=session_baseline
+ )
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ # The own download has settled by the time recovery observes it.
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[own_settled])
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(return_value=[])
+ return await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ finally:
+ skyvern_context.reset()
+
+ # Settled-only augment (the fix): the own in-flight partial never entered the baseline -> its settle
+ # is a new file -> credited.
+ assert await _run(session_baseline=[]) == []
+ # The harm the fix avoids: had the own partial been augmented in (round-12 over-augment), the settled
+ # URI normalizes to the baselined identity -> not new -> the popup is wrongly released instead of credited.
+ released = await _run(session_baseline=[own_partial])
+ assert released is not None and len(released) == 1 and released[0].is_internal_recovery is True
+
+
+async def test_session_inflight_partial_settling_during_grace_does_not_credit_but_later_partial_does(
+ tmp_path: Path,
+) -> None:
+ """Round-6 residual: the claim baseline must also union the session's IN-FLIGHT partials (the s3
+ downloaded-listing excludes them). An earlier session download still partial at claim time settles to
+ its final name during the grace; ``normalize_download_identity`` collapses partial->final so it is NOT
+ miscredited. A partial that starts only AFTER the claim is still allowed to settle and credit."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", browser_session_id="pbs_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ partial = "s3://bucket/foo.pdf.crdownload"
+ settled = "s3://bucket/foo.pdf"
+
+ async def _run(
+ claim_downloaded: list[str],
+ claim_downloading: list[str],
+ observed_downloaded: list[str],
+ observed_downloading: list[str],
+ ):
+ # Claim-time session baseline = the pre-click session snapshot (downloaded + in-flight) the
+ # authoritative read captures, exactly as the download-action claim recorder builds the baseline.
+ claim_baseline = list(claim_downloaded) + list(claim_downloading)
+ ctx = SkyvernContext(task_id="t")
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ # main-path claims are session-observed, so recovery unions session files for them
+ ctx.record_download_popup_claim("t", dead, baseline_files=claim_baseline, session_observed=True)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.app") as agent_app,
+ ):
+ agent_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=observed_downloaded)
+ agent_app.STORAGE.list_downloading_files_in_browser_session = AsyncMock(
+ return_value=observed_downloading
+ )
+ return await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ finally:
+ skyvern_context.reset()
+
+ # Partial present at claim time, settled to its final name during the grace -> NOT credited.
+ present = await _run(
+ claim_downloaded=[], claim_downloading=[partial], observed_downloaded=[settled], observed_downloading=[]
+ )
+ assert present is not None and len(present) == 1 and present[0].is_internal_recovery is True
+
+ # A partial that starts only AFTER the claim -> not in the baseline -> allowed to settle and credit.
+ after = await _run(
+ claim_downloaded=[], claim_downloading=[], observed_downloaded=[settled], observed_downloading=[]
+ )
+ assert after == []
+
+
+async def test_recovery_uses_exact_page_baseline_not_stale_block_baseline(tmp_path: Path) -> None:
+ """Multi-download regression: an earlier action's file already sits in the run dir when a LATER
+ claimed dead-blank popup is created, so that popup's page baseline captures it. The observer must
+ compare against THIS page's baseline, not the stale block baseline reused across recursive steps --
+ otherwise the earlier file is miscredited to the later page, releasing/closing it before its own
+ download can settle. Proves per-page isolation: with an empty page baseline the same file DOES
+ credit its own page."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ earlier_file = tmp_path / "earlier.pdf"
+ earlier_file.write_text("x")
+
+ # Later popup: its claim is created AFTER earlier.pdf exists, so its baseline captures earlier.pdf.
+ later_ctx = SkyvernContext(task_id=task.task_id)
+ dead_later = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ later_ctx.record_download_popup_claim(task.task_id, dead_later, baseline_files=[str(earlier_file)])
+ skyvern_context.set(later_ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ ):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead_later, survivor),
+ # tiny positive grace so the un-credited observation ages out fast instead of hanging
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[], # STALE block baseline: captured before earlier.pdf landed
+ )
+ # earlier.pdf is in the later page's own baseline -> NOT new credit -> release + recover.
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ assert later_ctx.has_download_popup_claim(task.task_id, dead_later) is False
+ finally:
+ skyvern_context.reset()
+
+ # Earlier page (isolation counter-case): its claim predates earlier.pdf (empty page baseline), so the
+ # very same file legitimately credits ITS page -> complete-on-download short-circuit returns [].
+ earlier_ctx = SkyvernContext(task_id=task.task_id)
+ dead_earlier = _page("about:blank")
+ survivor2 = _page("https://example.test/")
+ survivor2.is_closed.return_value = False
+ earlier_ctx.record_download_popup_claim(task.task_id, dead_earlier, baseline_files=[])
+ skyvern_context.set(earlier_ctx)
+ try:
+ agent = ForgeAgent()
+ with (
+ patch(f"{_AGENT}.resolve_run_download_id", return_value="wr_x"),
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ ):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead_earlier, survivor2),
+ task_block=_task_block(complete_on_download=True, download_timeout=0.05),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result == [], "a file new to THIS page's baseline must credit it"
+ finally:
+ skyvern_context.reset()
+
+
+async def test_observe_workflow_less_task_observes_via_task_id(tmp_path: Path) -> None:
+ """A true workflow-less standalone task (workflow_run_id=None) keys its download dir by task_id,
+ exactly as the authoritative credit seam resolves it (``workflow_run_id or task_id``). The observer
+ must still observe such a task, not bail early on the missing workflow_run_id."""
+ task = make_task(
+ datetime.now(UTC),
+ make_organization(datetime.now(UTC)),
+ task_id="t",
+ workflow_run_id=None,
+ )
+ agent = ForgeAgent()
+ before = [str(tmp_path / "old.pdf")]
+ after = before + [str(tmp_path / "new.pdf")]
+ ctx = SkyvernContext(task_id="t") # no run_id/workflow_run_id -> resolve_run_download_id falls to task_id
+ with (
+ patch(f"{_AGENT}.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch(f"{_AGENT}.list_downloading_files_in_directory", return_value=[]),
+ patch(f"{_AGENT}.list_files_in_directory", return_value=after),
+ patch(f"{_AGENT}.skyvern_context.current", return_value=ctx),
+ ):
+ credited = await agent._observe_claimed_download_within_grace(
+ task, _task_block(), remaining=5.0, list_files_before=before, attempt_started_at=None
+ )
+ assert credited is True
+
+
+async def test_standalone_task_grace_uses_task_download_timeout() -> None:
+ """Standalone task (task_block is None): the settlement grace must come from ``task.download_timeout``,
+ not the 600s global fallback, matching the authoritative credit seams' standalone-task resolution."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x", download_timeout=123.0)
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ observe = AsyncMock(return_value=False)
+ with patch.object(ForgeAgent, "_observe_claimed_download_within_grace", observe):
+ await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=None,
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ remaining = observe.call_args.kwargs["remaining"]
+ assert remaining <= 123.0, "grace must be bounded by task.download_timeout"
+ assert remaining > 100.0, "grace must not fall back to the 600s global for a configured standalone task"
+ finally:
+ skyvern_context.reset()
+
+
+async def test_claimed_blank_complete_on_download_credit_routes_empty_list() -> None:
+ """Credit during grace -> return [] so the single authoritative 3106 seam finalizes and completes;
+ the claim is NOT released here and no recovery attempt is consumed."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t", workflow_run_id="wr_x")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with patch.object(ForgeAgent, "_observe_claimed_download_within_grace", AsyncMock(return_value=True)):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=True),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result == []
+ assert ctx.has_download_popup_claim(task.task_id, dead) is True # not released
+ assert ctx.empty_page_recovery_attempts == {} # no attempt consumed
+ finally:
+ skyvern_context.reset()
+
+
[email protected]("complete_on_download", [True, False])
+async def test_claimed_blank_no_credit_releases_exact_page_and_recovers(complete_on_download: bool) -> None:
+ """Both paths bounded (amendment 5): after the grace elapses with no credit, the EXACT page is
+ released from both registries and a recovery ClosePageAction is returned; attempt consumed once."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ sibling = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead)
+ ctx.record_download_popup_late_candidate(task.task_id, dead)
+ ctx.record_download_popup_claim(task.task_id, sibling) # unrelated sibling must survive
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with patch.object(ForgeAgent, "_observe_claimed_download_within_grace", AsyncMock(return_value=False)):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(complete_on_download=complete_on_download),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result is not None and len(result) == 1 and result[0].is_internal_recovery is True
+ assert ctx.has_download_popup_claim(task.task_id, dead) is False # exact page released, both registries
+ assert ctx.has_download_popup_claim(task.task_id, sibling) is True # sibling preserved
+ assert ctx.empty_page_recovery_attempts.get(task.task_id) == 1
+ finally:
+ skyvern_context.reset()
+
+
+async def test_claimed_blank_cancellation_performs_no_ownership_mutation() -> None:
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ ctx.record_download_popup_claim(task.task_id, dead)
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ with patch.object(
+ ForgeAgent, "_observe_claimed_download_within_grace", AsyncMock(side_effect=asyncio.CancelledError())
+ ):
+ with pytest.raises(asyncio.CancelledError):
+ await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert ctx.has_download_popup_claim(task.task_id, dead) is True # claim intact
+ assert ctx.empty_page_recovery_attempts == {} # no attempt consumed
+ finally:
+ skyvern_context.reset()
+
+
+async def test_unclaimed_dead_blank_recovers_without_observation() -> None:
+ """No claim -> today's fast path, no grace observation invoked."""
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="t")
+ step = make_step(now, task, step_id="s", status=StepStatus.running, order=0, output=None)
+ ctx = SkyvernContext(task_id=task.task_id)
+ dead = _page("about:blank")
+ survivor = _page("https://example.test/")
+ survivor.is_closed.return_value = False
+ skyvern_context.set(ctx)
+ try:
+ agent = ForgeAgent()
+ observe = AsyncMock(return_value=False)
+ with patch.object(ForgeAgent, "_observe_claimed_download_within_grace", observe):
+ result = await agent._empty_page_recovery_plan(
+ task,
+ step,
+ _recovery_state(dead, survivor),
+ task_block=_task_block(),
+ attempt_started_at=None,
+ list_files_before=[],
+ )
+ assert result is not None and len(result) == 1
+ observe.assert_not_awaited()
+ finally:
+ skyvern_context.reset()
diff --git a/tests/unit/test_mcp_block_tools.py b/tests/unit/test_mcp_block_tools.py
index f73145160..2da9a9e6d 100644
--- a/tests/unit/test_mcp_block_tools.py
+++ b/tests/unit/test_mcp_block_tools.py
@@ -127,6 +127,17 @@ async def test_block_schema_task_redirects_to_navigation() -> None:
assert any("deprecated" in w.lower() for w in result["warnings"])
+async def test_block_schema_google_sheets_write_carries_its_knowledge_section() -> None:
+ result = await skyvern_block_schema(block_type="google_sheets_write")
+
+ assert result["ok"] is True
+ description = result["data"]["description"]
+ assert result["data"]["use_cases"]
+ for shape_token in ("[[", "column_mapping", "cells", "| tojson"):
+ assert shape_token in description
+
+
@pytest.mark.asyncio
async def test_block_schema_unknown_type_returns_error() -> None:
"""Requesting schema for a nonexistent type should return an error with available types."""
@@ -283,12 +294,19 @@ _DIRECT_FILE_DOWNLOAD_OUTPUT = {
"downloaded_files": [{"url": "https://files.example.test/report.pdf", "filename": "report.pdf"}],
"downloaded_file_urls": ["https://files.example.test/report.pdf"],
}
+_HTTP_REQUEST_OUTPUT = {
+ "status_code": 200,
+ "headers": {"Content-Type": "application/json"},
+ "body": {"metric": "30 %"},
+ "response_body": {"metric": "30 %"},
+}
_TEMPLATING_FAMILY_OUTPUTS = {
"label": _BROWSER_TASK_OUTPUT,
"extract_items": _BROWSER_TASK_OUTPUT,
"get_data": _BROWSER_TASK_OUTPUT,
"summarize_notes": _NON_TASK_OUTPUT,
"fetch_report": _DIRECT_FILE_DOWNLOAD_OUTPUT,
+ "fetch_metric": _HTTP_REQUEST_OUTPUT,
}
diff --git a/tests/unit/test_multi_field_totp.py b/tests/unit/test_multi_field_totp.py
index 0959b01d9..a6df8f8fc 100644
--- a/tests/unit/test_multi_field_totp.py
+++ b/tests/unit/test_multi_field_totp.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import hashlib
import json
from copy import deepcopy
@@ -12,6 +13,7 @@ from unittest.mock import AsyncMock, MagicMock, call
import pytest
import structlog
+from playwright.async_api import Error as PlaywrightError
from skyvern.config import settings
from skyvern.forge.agent import (
@@ -27,11 +29,13 @@ from skyvern.forge.sdk.core.skyvern_context import (
)
from skyvern.forge.sdk.models import StepStatus
from skyvern.schemas.run_enums import RunEngine
+from skyvern.webeye.actions import multi_field_totp as multi_field_totp_module
from skyvern.webeye.actions.actions import ActionStatus, ClickAction, InputOrSelectContext, InputTextAction
from skyvern.webeye.actions.handler import (
_fill_multi_field_totp_group,
_resolve_multi_field_totp_code,
)
+from skyvern.webeye.actions.multi_field_totp import _multi_field_totp_frame_gone
from skyvern.webeye.actions.responses import STALE_TARGET_TOOL_RESULT, ActionFailure, ActionSuccess
from tests.unit.helpers import make_organization, make_step, make_task
from tests.unit.scoped_asyncio import ScopedAsyncio
@@ -1117,7 +1121,7 @@ async def test_single_input_page_preserves_external_verification_code(
assert any(entry.args[0] is element and entry.kwargs["is_secret_value"] for entry in mask.await_args_list)
-def test_persistence_copy_redacts_armed_digit_and_reasoning_without_mutating_execution_action() -> None:
+def test_persistence_copy_keeps_typed_digit_and_drops_seed_without_mutating_execution_action() -> None:
metadata = {
"tagName": "div",
"attributes": {"value": "7", "class": "otp"},
@@ -1154,10 +1158,10 @@ def test_persistence_copy_redacts_armed_digit_and_reasoning_without_mutating_exe
persisted = action_for_multi_field_totp_persistence(action)
assert action.text == "7"
- assert persisted.text == "*"
- assert persisted.reasoning == "Entered a one-time code digit."
- assert persisted.intention == "*"
- assert persisted.response == "*"
+ assert persisted.text == "7"
+ assert persisted.reasoning == "use the current code here"
+ assert persisted.intention == "enter the code"
+ assert persisted.response == "7"
assert persisted.totp_timing_info == {
"is_totp_sequence": True,
"action_index": 0,
@@ -1167,9 +1171,9 @@ def test_persistence_copy_redacts_armed_digit_and_reasoning_without_mutating_exe
assert _SEED not in str(persisted.totp_timing_info)
assert persisted.input_or_select_context is not None
- assert persisted.input_or_select_context.intention == persisted.reasoning
- assert persisted.input_or_select_context.field == persisted.reasoning
- assert persisted.input_or_select_context.date_format == persisted.reasoning
+ assert persisted.input_or_select_context.intention == "Entered a one-time code digit."
+ assert persisted.input_or_select_context.field == "Entered a one-time code digit."
+ assert persisted.input_or_select_context.date_format == "Entered a one-time code digit."
assert persisted.input_or_select_context.is_required is True
assert action.input_or_select_context.intention == "Enter digit 7"
@@ -2785,7 +2789,7 @@ async def test_execute_step_rebound_group_requires_expected_value(
"123456"
)
persisted = [*persisted_inputs, *[entry.kwargs["action"] for entry in create_action.await_args_list]]
- assert [action.text for action in persisted] == ["*"] * 6
+ assert [action.text for action in persisted] == [action.text for action in otp_actions]
if leading:
assert all(action.skyvern_element_data["attributes"]["value"] == "*" for action in persisted)
assert [action.skyvern_element_hash for action in persisted] == planning_hashes
@@ -2931,3 +2935,127 @@ def test_credential_ambiguity_preserves_external_attempt(
assert state.filled_code_hash == hashlib.sha256(_CODE.encode()).hexdigest()
assert state.filled_at == 10.0
assert context.totp_codes == {f"{task_id}_totp_cache": _CODE}
+
+
+_CONTEXT_DESTROYED_ERROR = "Execution context was destroyed, most likely because of a navigation."
+
+
+class _NeverResolvingHandle:
+ """Frame ElementHandle whose direct handle reads never resolve, so a regression that reads the id
+ straight off the handle (``get_attribute`` re-resolving the driver's 30s ``:scope`` selector, or a
+ handle-bound ``evaluate``) instead of through the common ``SkyvernFrame.evaluate`` abstraction trips
+ the bounded wait."""
+
+ async def get_attribute(self, name: str) -> str | None:
+ await asyncio.Event().wait()
+ raise AssertionError("get_attribute should never resolve")
+
+ async def evaluate(self, expression: str, arg: object = None) -> object:
+ await asyncio.Event().wait()
+ raise AssertionError("handle.evaluate should never resolve")
+
+
+class _FrameStub:
+ def __init__(self, handle: _NeverResolvingHandle, parent_frame: object, *, detached: bool = False) -> None:
+ self._handle = handle
+ self.parent_frame = parent_frame
+ self._detached = detached
+
+ def is_detached(self) -> bool:
+ return self._detached
+
+ async def frame_element(self) -> _NeverResolvingHandle:
+ return self._handle
+
+
+class _EvaluateSpy:
+ """Stands in for the common ``SkyvernFrame.evaluate`` abstraction and records how it was called."""
+
+ def __init__(self, *, result: object) -> None:
+ self._result = result
+ self.calls: list[SimpleNamespace] = []
+
+ async def __call__(self, *, frame: object, expression: str, arg: object = None, **kwargs: object) -> object:
+ self.calls.append(SimpleNamespace(frame=frame, expression=expression, arg=arg, kwargs=kwargs))
+ if isinstance(self._result, BaseException):
+ raise self._result
+ return self._result
+
+
+def _child_frame(handle: _NeverResolvingHandle) -> _FrameStub:
+ return _FrameStub(handle, parent_frame=object())
+
+
+def _page_with_child(child: _FrameStub) -> SimpleNamespace:
+ return SimpleNamespace(main_frame=child.parent_frame, frames=[child.parent_frame, child])
+
+
+async def test_frame_gone_returns_false_when_original_id_still_live(monkeypatch: pytest.MonkeyPatch) -> None:
+ frame_id = "CD34"
+ handle = _NeverResolvingHandle()
+ child = _child_frame(handle)
+ page = _page_with_child(child)
+ spy = _EvaluateSpy(result=frame_id)
+ monkeypatch.setattr(multi_field_totp_module.SkyvernFrame, "evaluate", spy)
+
+ result = await asyncio.wait_for(_multi_field_totp_frame_gone(page, frame_id), timeout=2)
+
+ assert result is False
+ assert len(spy.calls) == 1
+ # The iframe's ElementHandle lives in the PARENT frame's execution context, so the id must be
+ # read there with the handle as the argument -- not from the child frame or off the handle.
+ assert spy.calls[0].frame is child.parent_frame
+ assert spy.calls[0].arg is handle
+
+
+async def test_frame_gone_reads_orphan_id_via_main_frame_context(monkeypatch: pytest.MonkeyPatch) -> None:
+ # An orphan iframe (child attach before its parent) briefly has parent_frame=None; its handle is
+ # owned by main_frame, so the read must evaluate there -- not from the child frame.
+ frame_id = "CD34"
+ handle = _NeverResolvingHandle()
+ child = _FrameStub(handle, parent_frame=None)
+ main_frame = object()
+ page = SimpleNamespace(main_frame=main_frame, frames=[main_frame, child])
+ spy = _EvaluateSpy(result=frame_id)
+ monkeypatch.setattr(multi_field_totp_module.SkyvernFrame, "evaluate", spy)
+
+ result = await asyncio.wait_for(_multi_field_totp_frame_gone(page, frame_id), timeout=2)
+
+ assert result is False
+ assert len(spy.calls) == 1
+ assert spy.calls[0].frame is main_frame
+ assert spy.calls[0].arg is handle
+
+
+async def test_frame_gone_returns_true_when_original_id_replaced(monkeypatch: pytest.MonkeyPatch) -> None:
+ page = _page_with_child(_child_frame(_NeverResolvingHandle()))
+ monkeypatch.setattr(multi_field_totp_module.SkyvernFrame, "evaluate", _EvaluateSpy(result="EF56"))
+
+ result = await asyncio.wait_for(_multi_field_totp_frame_gone(page, "CD34"), timeout=2)
+
+ assert result is True
+
+
+async def test_frame_gone_indeterminate_when_frame_id_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ page = _page_with_child(_child_frame(_NeverResolvingHandle()))
+ monkeypatch.setattr(multi_field_totp_module.SkyvernFrame, "evaluate", _EvaluateSpy(result=None))
+
+ result = await asyncio.wait_for(_multi_field_totp_frame_gone(page, "CD34"), timeout=2)
+
+ assert result is None
+
+
+async def test_frame_gone_indeterminate_when_execution_context_destroyed(monkeypatch: pytest.MonkeyPatch) -> None:
+ page = _page_with_child(_child_frame(_NeverResolvingHandle()))
+ monkeypatch.setattr(
+ multi_field_totp_module.SkyvernFrame, "evaluate", _EvaluateSpy(result=PlaywrightError(_CONTEXT_DESTROYED_ERROR))
+ )
+
+ result = await asyncio.wait_for(_multi_field_totp_frame_gone(page, "CD34"), timeout=2)
+
+ assert result is None
diff --git a/tests/unit/test_otp_service.py b/tests/unit/test_otp_service.py
index a36f7a258..b76cf645c 100644
--- a/tests/unit/test_otp_service.py
+++ b/tests/unit/test_otp_service.py
@@ -2348,6 +2348,7 @@ async def test_get_otp_value_from_db_forwards_created_after(monkeypatch: pytest.
async def test_get_otp_value_from_db_scopes_query_to_workflow_run_when_provided() -> None:
"""Run-scoped polling prefers exact rows but keeps unscoped email/SMS pushes eligible."""
unscoped = SimpleNamespace(
+ totp_code_id="otp_unscoped",
code="111111",
otp_type=OTPType.TOTP,
created_at=datetime(2026, 6, 8, 20, 4, 0),
@@ -2357,6 +2358,7 @@ async def test_get_otp_value_from_db_scopes_query_to_workflow_run_when_provided(
expired_at=None,
)
other_run = SimpleNamespace(
+ totp_code_id="otp_other_run",
code="333333",
otp_type=OTPType.TOTP,
created_at=datetime(2026, 6, 8, 20, 5, 0),
@@ -2366,6 +2368,7 @@ async def test_get_otp_value_from_db_scopes_query_to_workflow_run_when_provided(
expired_at=None,
)
scoped = SimpleNamespace(
+ totp_code_id="otp_scoped",
code="222222",
otp_type=OTPType.TOTP,
created_at=datetime(2026, 6, 8, 20, 6, 0),
@@ -2398,6 +2401,7 @@ async def test_get_otp_value_from_db_scopes_query_to_workflow_run_when_provided(
@pytest.mark.asyncio
async def test_get_otp_value_from_db_allows_unscoped_code_for_run_scoped_poll() -> None:
unscoped = SimpleNamespace(
+ totp_code_id="otp_unscoped",
code="111111",
otp_type=OTPType.TOTP,
created_at=datetime(2026, 6, 8, 20, 4, 0),
@@ -2407,6 +2411,7 @@ async def test_get_otp_value_from_db_allows_unscoped_code_for_run_scoped_poll()
expired_at=None,
)
other_run = SimpleNamespace(
+ totp_code_id="otp_other_run",
code="333333",
otp_type=OTPType.TOTP,
created_at=datetime(2026, 6, 8, 20, 5, 0),
@@ -2434,6 +2439,7 @@ async def test_get_otp_value_from_db_allows_unscoped_code_for_run_scoped_poll()
@pytest.mark.asyncio
async def test_get_otp_value_from_db_preserves_unscoped_lookup_without_workflow_run() -> None:
unscoped = SimpleNamespace(
+ totp_code_id="otp_unscoped",
code="111111",
otp_type=OTPType.TOTP,
created_at=datetime(2026, 6, 8, 20, 4, 0),
@@ -2717,6 +2723,61 @@ def _raw_otp_row(
)
+async def test_get_otp_value_from_db_counts_rows_the_filters_drop() -> None:
+ expired = _raw_otp_row(totp_code_id="otp_expired")
+ expired.expired_at = datetime(2020, 1, 1)
+ other_run = _parsed_otp_row(
+ totp_code_id="otp_other_run",
+ content="Your code is 123456.",
+ code="123456",
+ otp_type=OTPType.TOTP,
+ workflow_run_id="wr_other",
+ )
+ context = otp_service.RawOTPVerificationContext()
+ with patch("skyvern.services.otp_service.app") as mock_app:
+ mock_app.DATABASE.otp.get_otp_codes = AsyncMock(return_value=[other_run])
+ mock_app.DATABASE.otp.get_raw_otp_codes = AsyncMock(return_value=[expired])
+ result = await _get_otp_value_from_db(
+ "o_test",
+ workflow_run_id="wr_test",
+ expected_otp_type=OTPType.TOTP,
+ raw_context=context,
+ )
+
+ assert result is None
+ assert context.seen_row_ids == {"otp_expired", "otp_other_run"}
+ assert context.store_queried is True
+
+
+async def test_seen_rows_include_rows_the_reparse_budget_never_read(monkeypatch: pytest.MonkeyPatch) -> None:
+ rows = [
+ _raw_otp_row(totp_code_id=f"otp_{index}", created_at=datetime(2026, 7, 30, 12, index, 0))
+ for index in range(otp_service._RAW_OTP_REPARSE_LIMIT + 2)
+ ]
+ context = otp_service.RawOTPVerificationContext()
+
+ async def fake_parse_otp_login(*_args: object, **_kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(otp_service, "parse_otp_login", fake_parse_otp_login)
+ with patch("skyvern.services.otp_service.app") as mock_app:
+ mock_app.DATABASE.otp.get_otp_codes = AsyncMock(return_value=[])
+ mock_app.DATABASE.otp.get_raw_otp_codes = AsyncMock(return_value=rows)
+ result = await _get_otp_value_from_db(
+ "o_test",
+ expected_otp_type=OTPType.MAGIC_LINK,
+ raw_context=context,
+ )
+
+ assert result is None
+ assert len(context.seen_row_ids) == len(rows)
+ assert len(context.misses) == otp_service._RAW_OTP_REPARSE_LIMIT
+
+
@pytest.mark.asyncio
async def test_newer_raw_message_is_reparsed_before_older_parsed_value() -> None:
older_parsed = _parsed_otp_row(
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 65dd20960..02bef137c 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -39,6 +39,17 @@ from skyvern.forge.request_logging import (
# ---------------------------------------------------------------------------
[email protected]("method", ["GET", "POST"])
[email protected]("path", ["/api/v1/users/me/onboarding", "/api/v1/users/me/onboarding/"])
+ "body", ['{"project_owner":{"professional_email":"[email protected]"}}', "broken [email protected] {"]
+)
+def test_onboarding_bodies_are_opaque_even_when_malformed(method: str, path: str, body: str) -> None:
+ request = Request({"type": "http", "method": method, "path": path, "headers": [], "query_string": b""})
+ assert _sanitize_body(request, body.encode(), "application/json") == REDACTED
+ assert _sanitize_response_body(request, body, "application/json") == REDACTED
+
+
class TestClientIpFromHeaders:
def test_extracts_first_hop_from_x_forwarded_for(self) -> None:
headers = {"x-forwarded-for": "203.0.113.10, 10.0.0.1"}
diff --git a/tests/unit/test_stale_context_guards.py b/tests/unit/test_stale_context_guards.py
index c510b2711..7abe5d45e 100644
--- a/tests/unit/test_stale_context_guards.py
+++ b/tests/unit/test_stale_context_guards.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import asyncio
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -7,8 +9,154 @@ from playwright.async_api import Error as PlaywrightError
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from skyvern.exceptions import MissingElement, MissingElementDict, MultipleElementsFound
+from skyvern.webeye.scraper import scraper as scraper_module
from skyvern.webeye.utils.dom import SkyvernElement, is_element_detached_error, resolve_locator
+_CONTEXT_DESTROYED_ERROR = "Execution context was destroyed, most likely because of a navigation."
+
+
+class _NeverResolvingHandle:
+ """Frame ElementHandle whose direct handle reads never resolve. Both the selector-based
+ ``get_attribute`` (which the driver re-resolves through a 30s ``:scope`` wait after the parent
+ document navigated) and the handle-bound ``evaluate`` hang forever, so any regression that reads
+ the id straight off the handle instead of through the common ``SkyvernFrame.evaluate`` abstraction
+ trips the bounded wait."""
+
+ async def is_visible(self) -> bool:
+ return True
+
+ async def get_attribute(self, name: str) -> str | None:
+ await asyncio.Event().wait()
+ raise AssertionError("get_attribute should never resolve")
+
+ async def evaluate(self, expression: str, arg: object = None) -> object:
+ await asyncio.Event().wait()
+ raise AssertionError("handle.evaluate should never resolve")
+
+
+class _FrameStub:
+ def __init__(self, handle: _NeverResolvingHandle, parent_frame: object, page: object = None) -> None:
+ self._handle = handle
+ self.parent_frame = parent_frame
+ self.page = page
+
+ async def frame_element(self) -> _NeverResolvingHandle:
+ return self._handle
+
+
+class _EvaluateSpy:
+ """Stands in for the common ``SkyvernFrame.evaluate`` abstraction and records how it was called."""
+
+ def __init__(self, *, result: object) -> None:
+ self._result = result
+ self.calls: list[SimpleNamespace] = []
+
+ async def __call__(self, *, frame: object, expression: str, arg: object = None, **kwargs: object) -> object:
+ self.calls.append(SimpleNamespace(frame=frame, expression=expression, arg=arg, kwargs=kwargs))
+ if isinstance(self._result, BaseException):
+ raise self._result
+ return self._result
+
+
+async def test_add_frame_interactable_elements_reads_id_through_parent_frame_abstraction(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ frame_id = "AB12"
+ handle = _NeverResolvingHandle()
+ parent = object()
+ frame = _FrameStub(handle, parent_frame=parent)
+ engine_selection = object()
+ spy = _EvaluateSpy(result=frame_id)
+ monkeypatch.setattr(scraper_module.SkyvernFrame, "evaluate", spy)
+ built_child = {"id": frame_id, "attributes": {}}
+ skyvern_frame = MagicMock()
+ skyvern_frame.build_tree_from_body = AsyncMock(return_value=([built_child], [built_child], {}))
+ monkeypatch.setattr(scraper_module.SkyvernFrame, "create_instance", AsyncMock(return_value=skyvern_frame))
+ monkeypatch.setattr(scraper_module, "_wait_for_scrape_ready", AsyncMock())
+
+ elements: list[dict] = [{"id": frame_id}]
+ tree: list[dict] = [{"id": frame_id}]
+ result_elements, result_tree = await asyncio.wait_for(
+ scraper_module.add_frame_interactable_elements(frame, 0, elements, tree, {}, engine_selection=engine_selection),
+ timeout=2,
+ )
+
+ assert built_child in result_elements
+ assert result_tree[0]["children"] == [built_child]
+ assert skyvern_frame.build_tree_from_body.await_args.kwargs["frame_name"] == frame_id
+ assert len(spy.calls) == 1
+ # The iframe's ElementHandle lives in the PARENT frame's execution context, so the id must be
+ # read there with the handle as the argument -- not from the child frame or off the handle.
+ assert spy.calls[0].frame is parent
+ assert spy.calls[0].arg is handle
+ assert spy.calls[0].kwargs.get("engine_selection") is engine_selection
+
+
+async def test_add_frame_interactable_elements_reads_orphan_id_via_main_frame_context(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # An orphan iframe (child attach arrives before its parent) briefly has parent_frame=None; its
+ # handle is owned by main_frame, so the read must evaluate there -- not from the child frame.
+ frame_id = "AB12"
+ handle = _NeverResolvingHandle()
+ main_frame = object()
+ frame = _FrameStub(handle, parent_frame=None, page=SimpleNamespace(main_frame=main_frame))
+ spy = _EvaluateSpy(result=frame_id)
+ monkeypatch.setattr(scraper_module.SkyvernFrame, "evaluate", spy)
+ built_child = {"id": frame_id, "attributes": {}}
+ skyvern_frame = MagicMock()
+ skyvern_frame.build_tree_from_body = AsyncMock(return_value=([built_child], [built_child], {}))
+ monkeypatch.setattr(scraper_module.SkyvernFrame, "create_instance", AsyncMock(return_value=skyvern_frame))
+ monkeypatch.setattr(scraper_module, "_wait_for_scrape_ready", AsyncMock())
+
+ elements: list[dict] = [{"id": frame_id}]
+ tree: list[dict] = [{"id": frame_id}]
+ await asyncio.wait_for(
+ scraper_module.add_frame_interactable_elements(frame, 0, elements, tree, {}),
+ timeout=2,
+ )
+
+ assert len(spy.calls) == 1
+ assert spy.calls[0].frame is main_frame
+ assert spy.calls[0].arg is handle
+
+
+async def test_add_frame_interactable_elements_skips_when_frame_id_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ frame = _FrameStub(_NeverResolvingHandle(), parent_frame=object())
+ monkeypatch.setattr(scraper_module.SkyvernFrame, "evaluate", _EvaluateSpy(result=None))
+ elements: list[dict] = [{"id": "existing"}]
+ tree: list[dict] = [{"id": "existing"}]
+
+ result = await asyncio.wait_for(
+ scraper_module.add_frame_interactable_elements(frame, 0, elements, tree, {}),
+ timeout=2,
+ )
+
+ assert result == (elements, tree)
+
+
+async def test_add_frame_interactable_elements_skips_when_execution_context_destroyed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ frame = _FrameStub(_NeverResolvingHandle(), parent_frame=object())
+ monkeypatch.setattr(
+ scraper_module.SkyvernFrame, "evaluate", _EvaluateSpy(result=PlaywrightError(_CONTEXT_DESTROYED_ERROR))
+ )
+ elements: list[dict] = [{"id": "existing"}]
+ tree: list[dict] = [{"id": "existing"}]
+
+ result = await asyncio.wait_for(
+ scraper_module.add_frame_interactable_elements(frame, 0, elements, tree, {}),
+ timeout=2,
+ )
+
+ assert result == (elements, tree)
+
+
_DETACHED_ERROR = "ElementHandle.content_frame: Element is not attached to the DOM"
_FRAME_DETACHED_ERROR = "Locator.count: Frame was detached"
_FRAME_HAS_BEEN_DETACHED_ERROR = "Frame.frame_element: Frame has been detached."
diff --git a/tests/unit/test_tab_action_handlers.py b/tests/unit/test_tab_action_handlers.py
index 7711ad466..f4631e9e1 100644
--- a/tests/unit/test_tab_action_handlers.py
+++ b/tests/unit/test_tab_action_handlers.py
@@ -1,6 +1,7 @@
"""Tests for the NEW_TAB / SWITCH_TAB / CLOSE_PAGE action handlers."""
from datetime import UTC, datetime
+from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -16,7 +17,7 @@ from skyvern.webeye.actions.handler import (
handle_new_tab_action,
handle_switch_tab_action,
)
-from skyvern.webeye.actions.responses import ActionFailure, ActionSuccess
+from skyvern.webeye.actions.responses import ActionFailure, ActionResult, ActionSuccess
from tests.unit.helpers import make_organization, make_step, make_task
@@ -361,3 +362,38 @@ async def test_handle_action_retires_download_claim_for_user_close() -> None:
await ActionHandler.handle_action(MagicMock(), task, step, dead, action)
assert context.has_download_popup_claim(task.task_id, dead) is False
+
+
+async def test_recovery_dispatch_preserves_late_reservation_until_release() -> None:
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now), task_id="task-reserved")
+ step = make_step(now, task, step_id="step-reserved", status=StepStatus.running, order=0, output=None)
+ dead = _dead_blank_page("about:blank")
+ context = SkyvernContext(task_id=task.task_id)
+ context.record_download_popup_late_candidate(task.task_id, dead)
+ state = MagicMock()
+ state.list_valid_pages = AsyncMock(return_value=[dead, _survivor_page()])
+
+ async def dispatch(**kwargs: Any) -> list[ActionResult]:
+ return await handle_close_page_action(
+ kwargs["action"], kwargs["page"], kwargs["scraped_page"], kwargs["task"], kwargs["step"]
+ )
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=dispatch),
+ patch("skyvern.webeye.actions.handler.app", _handle_action_deps(state)),
+ patch.object(skyvern_context, "current", return_value=context),
+ ):
+ result = await ActionHandler.handle_action(
+ MagicMock(), task, step, dead, actions.ClosePageAction(is_internal_recovery=True)
+ )
+ assert isinstance(result[0], ActionFailure)
+ dead.close.assert_not_awaited()
+ assert context.has_download_popup_claim(task.task_id, dead)
+ context.clear_download_popup_claims(task.task_id)
+ result = await ActionHandler.handle_action(
+ MagicMock(), task, step, dead, actions.ClosePageAction(is_internal_recovery=True)
+ )
+ assert isinstance(result[0], ActionSuccess)
+ dead.close.assert_awaited_once()
diff --git a/tests/unit/test_taskv3_captcha_tools.py b/tests/unit/test_taskv3_captcha_tools.py
index 93dfd1ec6..ee845e4ca 100644
--- a/tests/unit/test_taskv3_captcha_tools.py
+++ b/tests/unit/test_taskv3_captcha_tools.py
@@ -278,10 +278,19 @@ class _MarkerOnlyLocator:
async def count(self) -> int:
return self._count
+ def nth(self, _index: int) -> _MarkerOnlyLocator:
+ return self
+
+ async def is_visible(self) -> bool:
+ return True
+
+ async def bounding_box(self) -> dict[str, float]:
+ return {"x": 10.0, "y": 10.0, "width": 300.0, "height": 80.0}
+
class _MarkerOnlyPage:
- """Only the generic CAPTCHA marker selector matches: the real ladder detects a challenge, finds no
- checkbox/anchor/recaptcha arm, and raises CaptchaChallengeUnsolvedError."""
+ """Only the generic CAPTCHA marker selector matches, and it is rendered: the real ladder detects a
+ challenge, finds no checkbox/anchor/recaptcha arm, and raises CaptchaChallengeUnsolvedError."""
def __init__(self) -> None:
self.url = "https://app.example/login"
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index d05a12597..8aa329d92 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -88,6 +88,8 @@ from skyvern.forge.taskv3.loop import (
run_agent_tool_loop,
)
from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls
+from skyvern.forge.taskv3.tools import build_browser_tools
+from skyvern.utils.url_validators import validate_fetch_url
from tests.unit.helpers import make_organization, make_task
@@ -1674,6 +1676,70 @@ async def test_page_unavailable_tool_error_still_stops_batch() -> None:
assert any(m.get("name") == "type" and "skipped" in m["content"] for m in turn1_tool_msgs)
+async def test_a_navigate_whose_document_never_became_ready_stops_the_batch() -> None:
+ # SKY-16278: navigate now returns ok for a document that committed without becoming ready, where it
+ # used to raise. The rest of the batch was queued against a page the model has not seen, so it must
+ # not run — and the readiness the tool reported has to reach the model before it acts again.
+ type_calls: list[tuple[str, dict[str, Any]]] = []
+
+ async def partial_navigate(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok(
+ "navigated to https://example.test/apply (HTTP 200); the document was not ready after 20s",
+ data={"page_state_changed": True, "readiness_incomplete": True},
+ ok_class="committed_not_loaded",
+ )
+
+ tools = [
+ ToolSpec(name="navigate", description="n", parameters={}, handler=partial_navigate),
+ _recording_tool("type", type_calls),
+ make_finish_tool(),
+ ]
+ script = [
+ [("navigate", {"url": "https://example.test/apply"}), ("type", {"selector": "#name"})],
+ [("finish", {"status": "completed", "reason": "recovered"})],
+ ]
+ outcome, _ = await _run(script, tools)
+
+ assert outcome.status == "completed"
+ assert type_calls == []
+ turn1_tool_msgs = [m for m in outcome.messages if m.get("role") == "tool"]
+ assert any(m.get("name") == "type" and "had not finished loading" in m["content"] for m in turn1_tool_msgs)
+
+
+async def test_a_navigate_onto_a_ready_document_lets_the_rest_of_its_batch_run() -> None:
+ # The other side of the same rule, and the reason the batch stop is keyed on `readiness_incomplete`
+ # rather than on "navigate did not report `loaded`": a ready document is one the model may act on,
+ # so a navigate batched with a click still runs the click. Keying the stop on the ok_class instead
+ # would cost a turn on every page that has parsed but is still fetching — which is most of them.
+ click_calls: list[tuple[str, dict[str, Any]]] = []
+
+ async def document_ready_navigate(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok(
+ "navigated to https://example.test/apply (HTTP 200); the document is ready after 2s, but the "
+ "page is still loading its scripts and resources",
+ data={"page_state_changed": True},
+ ok_class="document_ready",
+ )
+
+ tools = [
+ ToolSpec(name="navigate", description="n", parameters={}, handler=document_ready_navigate),
+ _recording_tool("click", click_calls),
+ make_finish_tool(),
+ ]
+ script = [
+ [("navigate", {"url": "https://example.test/apply"}), ("click", {"selector": "#apply"})],
+ [("finish", {"status": "completed", "reason": "applied"})],
+ ]
+ outcome, _ = await _run(script, tools)
+
+ assert outcome.status == "completed"
+ assert [args["selector"] for _name, args in click_calls] == ["#apply"]
+ skipped = [m for m in outcome.messages if m.get("role") == "tool" and "skipped" in str(m.get("content"))]
+ assert skipped == []
+
+
@pytest.mark.asyncio
async def test_page_probe_change_across_failed_call_stops_batch() -> None:
# A billable tool's error carries no data flag, but the page_probe sampled before and after the
@@ -6189,6 +6255,118 @@ async def test_tool_call_record_carries_a_stable_action_key_hash_and_never_the_v
assert _SECRET_TEXT not in dump and "#city" not in dump and _SALT not in dump
+async def test_navigate_records_name_the_host_and_no_other_tool_does() -> None:
+ # SKY-16278: a navigate timeout was unattributable — neither the per-call record nor the raise line
+ # named the target, so a fleet read could not say which URL cost 60s. Attribution is scheme and
+ # host, never more: the record is otherwise names, sizes and booleans, and a signed or sign-in URL
+ # is a bearer secret whoever produced it — the model included, because it types back the link a
+ # page just showed it. A payload ref is the one value logged whole: it names the target without
+ # being the address. Every other tool's record keeps exactly its current fields.
+ signed = "https://files.example.test/d/a1b2c3?token=eyJhbGciOiJIUzI1NiJ9.c2lnbmVk.Q29ycmVjdEhvcnNl"
+ refs = mask_opaque_urls({"link": signed})
+ token = refs.masked["link"]
+
+ async def navigate_handler(args: dict[str, Any]) -> ToolResult:
+ if args["url"] == "https://dead.example.test/x":
+ raise RuntimeError("boom")
+ # Raw on purpose: the rule belongs to the record field, not to whichever caller filled it.
+ return ToolResult.ok("navigated", data={"landed_url": signed, "same_page": args["url"] == signed})
+
+ tools = [
+ ToolSpec(name="navigate", description="n", parameters={}, handler=navigate_handler),
+ _recording_tool("click", []),
+ make_finish_tool(),
+ ]
+ script = [
+ [("navigate", {"url": token})],
+ [("click", {"selector": "#go"})],
+ [("navigate", {"url": signed})],
+ [("navigate", {"url": "https://dead.example.test/x"})],
+ [("finish", {"status": "completed", "reason": "ok"})],
+ ]
+ ctx = SkyvernContext(task_id="tsk_nav_log")
+ ctx.opaque_url_refs = refs.refs
+ skyvern_context.set(ctx)
+ try:
+ with capture_logs() as entries:
+ outcome, _ = await _run(script, tools)
+ finally:
+ skyvern_context.reset()
+ assert outcome.status == "completed"
+ records = [entry for entry in entries if entry["event"] == "taskv3 tool call finished"]
+ navigates = [entry for entry in records if entry["tool"] == "navigate"]
+ assert navigates[0]["requested_url"] == token
+ assert navigates[0]["landed_url"] == "https://files.example.test/<redacted>"
+ # The model typed the signed URL itself and the run landed on that same URL: both are host only.
+ # RED before: a landing byte-identical to the argument was logged whole.
+ assert navigates[1]["requested_url"] == "https://files.example.test/<redacted>"
+ assert navigates[1]["landed_url"] == "https://files.example.test/<redacted>"
+ assert navigates[2]["requested_url"] == "https://dead.example.test/<redacted>"
+ # Whether the browser was already on the page it was sent to, so a post-deploy read can measure how
+ # often the model re-navigates to the page it is on. Nothing in the loop branches on it.
+ assert navigates[0]["same_page"] is False
+ assert navigates[1]["same_page"] is True
+ # A raised handler builds its result in the loop, so the url has to come from the args there too.
+ raised = [entry for entry in entries if entry["event"] == "taskv3 tool handler raised"][0]
+ assert raised["requested_url"] == "https://dead.example.test/<redacted>"
+ click = [entry for entry in records if entry["tool"] == "click"][0]
+ assert "requested_url" not in click and "landed_url" not in click and "same_page" not in click
+ dump = _record_dump([*navigates, raised])
+ assert "c2lnbmVk" not in dump and "/d/a1b2c3" not in dump
+
+
+async def test_a_url_the_record_cannot_parse_redacts_it_and_never_aborts_the_run() -> None:
+ # The record helper is evaluated to build the kwargs BEFORE the `taskv3 tool handler raised` call
+ # is entered, so anything it raises escapes that except block, the per-call try AND the batch loop:
+ # a model-typed URL `urlsplit` chokes on would abort the run where main produced a clean tool_error
+ # and carried on. `urlsplit` parses the port and the IPv6 brackets lazily, on attribute access, so
+ # a non-numeric port, an out-of-range one and an unclosed bracket each raise inside the scrub.
+ # The backslash URL is the other half: `urlsplit` does not treat `\` as a path separator, so it
+ # keeps `host\signin\TOKEN` whole as the "host" and the token survives the scrub into the record —
+ # while a browser normalizes the `\` to `/` and navigates there, so the model does type these.
+ token = "BEARER-TOKEN-abc123"
+ backslash_url = f"https://good.example.test\\signin\\{token}"
+ unparseable = ["http://example.com:notaport/x", "http://example.com:99999/x", "http://[oops/x"]
+
+ async def navigate_handler(args: dict[str, Any]) -> ToolResult:
+ url = args["url"]
+ if url == backslash_url:
+ # The second call site: a record built from an ERROR result, where the tool returned rather
+ # than raised and `data` still carries a landing the field has to reduce.
+ return ToolResult.error(
+ "navigation did not commit", {"landed_url": backslash_url}, error_class="navigation_failed"
+ )
+ # What production does with these three: navigate() validates the resolved URL near the top.
+ validate_fetch_url(url)
+ raise AssertionError("unreachable: validation accepts none of these")
+
+ tools = [
+ ToolSpec(name="navigate", description="n", parameters={}, handler=navigate_handler),
+ make_finish_tool(),
+ ]
+ script = [
+ *[[("navigate", {"url": url})] for url in unparseable],
+ [("navigate", {"url": backslash_url})],
+ [("finish", {"status": "completed", "reason": "ok"})],
+ ]
+ with capture_logs() as entries:
+ outcome, caller = await _run(script, tools)
+ # RED before: the ValueError escaped the batch loop and the run ended on the exception instead.
+ assert outcome.status == "completed"
+ raised = [entry for entry in entries if entry["event"] == "taskv3 tool handler raised"]
+ assert [entry["requested_url"] for entry in raised] == ["<redacted>"] * len(unparseable)
+ records = [entry for entry in entries if entry["event"] == "taskv3 tool call finished"]
+ navigates = [entry for entry in records if entry["tool"] == "navigate"]
+ assert [entry["requested_url"] for entry in navigates] == ["<redacted>"] * (len(unparseable) + 1)
+ assert navigates[-1]["landed_url"] == "<redacted>"
+ # Each call came back as a tool error the model can read and retry past, not as a dead run.
+ assert [entry["tool_status"] for entry in navigates] == ["error"] * len(navigates)
+ assert caller.calls == len(script)
+ assert token not in _record_dump([*navigates, *raised])
+
+
@pytest.mark.asyncio
async def test_observe_summary_cannot_shadow_the_attribution_fields() -> None:
# A summary key named like a fixed field would otherwise raise at the log call on every observe.
@@ -9308,17 +9486,18 @@ async def test_selector_kind_reports_the_address_the_model_sent_not_the_one_the_
[("click", {"selector": "ref=12"})],
[("click", {"selector": "#plain"})],
[("click", {"mark": 3})],
+ [("click", {"selector": "ref=7", "mark": 0})],
[("finish", {"status": "completed", "reason": "ok"})],
]
with capture_logs() as logs:
outcome, _ = await _run(script, [click, make_finish_tool()])
assert outcome.status == "completed"
records = [e for e in logs if e["event"] == "taskv3 tool call finished" and e["tool"] == "click"]
- assert [e["selector_kind"] for e in records] == ["ref", "css", "mark"]
+ assert [e["selector_kind"] for e in records] == ["ref", "css", "mark", "ref"]
# The mark call carries selector_present=True even though the model sent no selector: the wrapper
# left its resolved selector in `args` and that field is read after dispatch. Pinned rather than
# fixed -- the two fields describe different moments, and a reader of the data needs to know.
- assert [e["selector_present"] for e in records] == [True, True, True]
+ assert [e["selector_present"] for e in records] == [True, True, True, True]
@pytest.mark.asyncio
@@ -10832,3 +11011,85 @@ async def test_navigate_dead_end_verdict_names_the_place_without_its_credentials
names="https://files.example.test/reset/step-two",
hides=("reset:pw@", "token=", "abc123def456", "#frag"),
)
+
+
+def _click_tool_spec() -> ToolSpec:
+ """A spec shaped like the real `click`: two properties, neither required."""
+
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok("clicked")
+
+ return ToolSpec(
+ name="click",
+ description="Click an element by its observe ref, a CSS selector, or mark=N from the last look().",
+ parameters={
+ "type": "object",
+ "properties": {"selector": {"type": "string"}, "mark": {"type": "integer"}},
+ "required": [],
+ },
+ handler=handler,
+ )
+
+
+async def _no_page() -> Any:
+ """A PageProvider that satisfies the declared `Callable[[], Awaitable[Any]]`.
+
+ `lambda: None` also builds the tool set today, but only because nothing awaits the provider --
+ it would fail as a TypeError the moment building one does, and mypy does not cover tests/.
+ """
+ return None
+
+
+def _reachable_tool_specs() -> list[ToolSpec]:
+ """The tool specs a unit test can build without a Task: the browser set plus `finish`.
+
+ NOT the complete set. `build_captcha_tools` and `build_auth_tools` both require a real `Task`,
+ so their specs are not enumerated here. That gap is covered in kind rather than in list:
+ `to_openai_tool` is the only serializer in the v3 loop (one call site, loop.py, building
+ `openai_tools`), so `test_to_openai_tool_states_strict_false_explicitly` already constrains every
+ `ToolSpec` that exists, including those. This list adds the concrete check on top: it catches a
+ spec whose schema drifts, not a spec that skips the serializer.
+ """
+ return [*build_browser_tools(_no_page), make_finish_tool()]
+
+
+def test_to_openai_tool_states_strict_false_explicitly() -> None:
+ """Reds if `strict` is dropped or flipped. An unset key is not equivalent: see GOTCHAS.md "Loop"."""
+ payload = _click_tool_spec().to_openai_tool()
+ assert payload["function"]["strict"] is False, (
+ "function specs must state strict=False; leaving it unset lets an upstream fill every "
+ "optional argument with a type default"
+ )
+
+
+def test_every_reachable_tool_spec_declares_strict_false() -> None:
+ """The guarantee has to hold for every spec a test can build, not just `click`."""
+ specs = _reachable_tool_specs()
+ assert len(specs) > 10, f"expected the reachable tool set, got {len(specs)}"
+ missing = [s.name for s in specs if s.to_openai_tool()["function"].get("strict") is not False]
+ assert not missing, f"these tools do not declare strict=False: {missing}"
+
+
+def test_tool_schemas_declare_only_properties_they_have() -> None:
+ """`required` must not name a property the schema does not declare.
+
+ Deliberately NOT asserted: anything about the schema's shape relative to `strict`. `strict`
+ asks the provider whether to GUARANTEE adherence; it is not a claim that the schema fails
+ strict mode's prerequisites. A closed, fully-required schema is therefore perfectly consistent
+ with `strict: False`, and a tool may want exactly that -- reject unknown arguments, require
+ everything, and still not ask for strict enforcement. Three earlier versions of this test each
+ asserted some part of that non-invariant and each rejected legitimate schemas: that some
+ property be optional (fails `hover`, `select_combobox`, `navigate`, `file_upload`); that
+ `additionalProperties: false` never appear; that it never appear alongside all-required.
+ Nothing about shape protects the behaviour this suite guards -- an explicit `strict: False`
+ does that on its own, whatever the schema looks like.
+ """
+ specs = _reachable_tool_specs()
+ assert len(specs) > 10, f"expected the reachable tool set, got {len(specs)}"
+ for spec in specs:
+ params = spec.to_openai_tool()["function"]["parameters"]
+ declared = set(params.get("properties", {}))
+ required = set(params.get("required", []))
+ assert required <= declared, (
+ f"{spec.name}: required names {sorted(required - declared)}, which it does not declare"
+ )
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index eaef3b443..02d9922c0 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -28,6 +28,7 @@ import pytest
# delay-specific test can exercise the real function while other upload tests skip the sleep.
from playwright.async_api import Error as _PlaywrightError
from playwright.async_api import Frame, Page, Route
+from playwright.async_api import TimeoutError as _PlaywrightTimeout
from structlog.testing import capture_logs
import skyvern.forge.taskv3.loop as taskv3_loop
@@ -40,7 +41,13 @@ from skyvern.forge.taskv3.code_surface import (
apply_surface,
configured_surface,
)
-from skyvern.forge.taskv3.loop import ACTION_OUTCOME_DATA_KEY, CODE_TOOL_NAME, SemanticCommitStats, ToolSpec
+from skyvern.forge.taskv3.loop import (
+ ACTION_OUTCOME_DATA_KEY,
+ CODE_TOOL_NAME,
+ SemanticCommitStats,
+ ToolSpec,
+ _navigate_record_fields,
+)
from skyvern.forge.taskv3.tools import (
_OPAQUE_ID_RUN_RE,
_SEMANTIC_COMMIT_STATE_JS,
@@ -49,6 +56,7 @@ from skyvern.forge.taskv3.tools import (
PAGE_UNAVAILABLE_ERROR,
BlankWorkingPageGuard,
_annotate_screenshot,
+ _exact_tier_key,
_invalid_selector_result,
_is_host_anchored_selector,
_normalize_selector,
@@ -296,12 +304,18 @@ class _StampedRowHandle:
class _FakePage:
+ # document.readyState, which is what navigate's readiness read asks the document. Default
+ # "complete": a page that finished loading, so the readiness note stays empty as it does live.
+ _READY_LEVELS = {"loading": 0, "interactive": 1, "complete": 2}
+ _LEVEL_WANTED = {"domcontentloaded": "interactive", "load": "complete"}
+
def __init__(self) -> None:
self.url = "https://example.test/apply"
self.calls: list[tuple[str, dict[str, Any]]] = []
self.element = _FakeElement(self)
self._request_listeners: list[Any] = []
self._closed = False
+ self.ready_state = "complete"
def is_closed(self) -> bool:
return self._closed
@@ -337,6 +351,8 @@ class _FakePage:
self.calls.append(("hover", {"selector": selector}))
async def evaluate(self, _js: str) -> str:
+ if "document.readyState" in _js:
+ return self.ready_state
return json.dumps(
{
"url": self.url,
@@ -409,6 +425,11 @@ class _FakePage:
async def wait_for_selector(self, selector: str, state: str = "visible", timeout: int | None = None) -> None:
self.calls.append(("wait_for_selector", {"selector": selector, "state": state, "timeout": timeout}))
+ async def wait_for_load_state(self, state: str = "load", timeout: float | None = None) -> None:
+ self.calls.append(("wait_for_load_state", {"state": state, "timeout": timeout}))
+ if self._READY_LEVELS[self.ready_state] < self._READY_LEVELS[self._LEVEL_WANTED[state]]:
+ raise _PlaywrightTimeout(f"Timeout {timeout}ms exceeded")
+
class _KB:
def __init__(self, page: _FakePage) -> None:
self._page = page
@@ -702,6 +723,7 @@ async def test_navigate_refuses_destructive_same_url_reload_with_filled_state(
r = await _tool(tools, "navigate").handler({"url": page.url})
assert r.status == "error", r.content
assert "discard" in r.content
+ assert "navigate here again to confirm" in r.content
assert not any(c[0] == "goto" for c in page.calls) # never reloaded
@@ -812,11 +834,13 @@ async def test_navigate_to_a_different_url_is_never_guarded(monkeypatch: pytest.
@pytest.mark.asyncio
async def test_navigate_same_url_reload_with_no_filled_state_proceeds(monkeypatch: pytest.MonkeyPatch) -> None:
- # Nothing to protect: a same-URL reload of a page with no filled fields proceeds normally.
+ # Nothing to protect: a same-URL reload of a page with no filled fields proceeds normally — one
+ # goto, and the record's `same_page` says the model sent the browser back where it already was.
page, tools = _reload_guard_tools(monkeypatch, filled=0)
r = await _tool(tools, "navigate").handler({"url": page.url})
assert r.status == "ok", r.content
- assert any(c[0] == "goto" for c in page.calls)
+ assert len([c for c in page.calls if c[0] == "goto"]) == 1
+ assert (r.data or {}).get("same_page") is True
@pytest.mark.asyncio
@@ -851,8 +875,9 @@ async def test_navigate_rerefuses_when_at_risk_state_grew_after_refusal(monkeypa
monkeypatch.setattr(tools_module, "_count_filled_fields", _filled)
page = _FakePage()
tools = build_browser_tools(_fixed_page_provider(page))
- assert (await _tool(tools, "navigate").handler({"url": page.url})).status == "error" # filled=2, refuse
- r2 = await _tool(tools, "navigate").handler({"url": page.url}) # filled=3 > 2 → re-refuse
+ nav_args = {"url": page.url}
+ assert (await _tool(tools, "navigate").handler(nav_args)).status == "error" # filled=2, refuse
+ r2 = await _tool(tools, "navigate").handler(nav_args) # filled=3 > 2 → re-refuse
assert r2.status == "error", r2.content
assert not any(c[0] == "goto" for c in page.calls) # never reloaded — the grown state is protected
@@ -875,6 +900,258 @@ async def test_filled_state_probe_counts_an_attached_file_input(tmp_path: Any) -
assert await _count_filled_fields(page) >= 2
+def _readiness_tools(
+ monkeypatch: pytest.MonkeyPatch, ready_state: str, status: int | None = 200, **build_kwargs: Any
+) -> tuple[Any, list[Any]]:
+ """A page whose document reaches `ready_state` and no further, recording each goto's own kwargs."""
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ page = _FakePage()
+ page.ready_state = ready_state
+
+ async def _goto(url: str, timeout: int | None = None, wait_until: str | None = None) -> Any:
+ page.url = url
+ page.calls.append(("goto", {"url": url, "timeout": timeout, "wait_until": wait_until}))
+ return None if status is None else SimpleNamespace(status=status)
+
+ page.goto = _goto # type: ignore[assignment]
+ return page, build_browser_tools(_fixed_page_provider(page), **build_kwargs)
+
+
+def _load_state_waits(page: Any) -> list[dict[str, Any]]:
+ return [args for name, args in page.calls if name == "wait_for_load_state"]
+
+
+async def test_navigate_commits_then_waits_for_readiness_on_the_same_document(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # SKY-16278: one goto at wait_until="commit", then the readiness waits on THAT document — never a
+ # second goto, which refetches a partially arrived bundle from zero. A page that did load reads
+ # exactly as it did before, so the common path gains no caveat.
+ page, tools = _readiness_tools(monkeypatch, "complete")
+ r = await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+ assert r.status == "ok", r.content
+ gotos = [args for name, args in page.calls if name == "goto"]
+ assert len(gotos) == 1 and gotos[0]["wait_until"] == "commit"
+ assert [wait["state"] for wait in _load_state_waits(page)] == ["domcontentloaded", "load"]
+ assert r.content == "navigated to https://jobs.example.test/acme/123 (HTTP 200)"
+ assert r.ok_class == "loaded"
+ assert (r.data or {}).get("readiness_incomplete") is None
+ # The point of splitting the budget: commit plus readiness cannot exceed the single-attempt
+ # ceiling this call used to spend entirely on one wait_until="load" goto.
+ assert gotos[0]["timeout"] + _load_state_waits(page)[0]["timeout"] <= settings.BROWSER_LOADING_TIMEOUT_MS
+
+
+async def test_navigate_reports_a_ready_document_whose_load_never_fired_in_budget(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The failure this ticket exists for: the document parses in under a second and one starved asset
+ # keeps `load` from firing. The wait for load is still made — the readiness budget is the bound,
+ # not the event — and when that budget runs out the tool reports what the document actually
+ # reached instead of raising. RED with the load wait removed: one wait, and no time spent on it.
+ monkeypatch.setattr(settings, "TASK_V3_NAVIGATE_READINESS_TIMEOUT_MS", 1500)
+ page, tools = _readiness_tools(monkeypatch, "interactive")
+
+ async def _load_starves(state: str = "load", timeout: float | None = None) -> None:
+ page.calls.append(("wait_for_load_state", {"state": state, "timeout": timeout}))
+ if state == "load":
+ # What the driver does: burn the timeout it was handed, then refuse.
+ await asyncio.sleep((timeout or 0) / 1000)
+ raise _PlaywrightTimeout(f"Timeout {timeout}ms exceeded")
+
+ page.wait_for_load_state = _load_starves # type: ignore[assignment]
+ started = time.monotonic()
+ r = await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+ waited = time.monotonic() - started
+ assert r.status == "ok", r.content
+ assert r.ok_class == "document_ready"
+ assert [wait["state"] for wait in _load_state_waits(page)] == ["domcontentloaded", "load"]
+ assert waited >= 0.4 # the load wait was made and spent its budget, not skipped
+ assert "https://jobs.example.test/acme/123" in r.content and "(HTTP 200)" in r.content
+ assert "the document is ready" in r.content and "still loading its scripts and resources" in r.content
+ assert "act on what has rendered, or wait for the rest" in r.content
+ assert len([name for name, _args in page.calls if name == "goto"]) == 1 # never re-navigated
+ # A ready document does NOT carry the loop's batch-stop cue: the model may act on what parsed, and
+ # the result text is what tells it the rest is still arriving.
+ assert (r.data or {}).get("readiness_incomplete") is None
+
+
+async def test_navigate_reports_a_document_that_never_became_ready(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A parser-blocking entry bundle starves domcontentloaded too: the response committed and nothing
+ # else happened inside the budget. Still a page STATE the model can act on — observe or wait — not
+ # an exception with no landed URL, status or readiness in it.
+ page, tools = _readiness_tools(monkeypatch, "loading")
+ r = await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+ assert r.status == "ok", r.content
+ assert r.ok_class == "committed_not_loaded"
+ assert "https://jobs.example.test/acme/123" in r.content and "(HTTP 200)" in r.content
+ assert "the document was not ready" in r.content and "still loading its scripts and resources" in r.content
+ assert "act on what has rendered, or wait for the rest" in r.content
+ assert [wait["state"] for wait in _load_state_waits(page)] == ["domcontentloaded"]
+ assert len([name for name, _args in page.calls if name == "goto"]) == 1 # never re-navigated
+ assert (r.data or {}).get("page_state_changed") is True
+ assert (r.data or {}).get("readiness_incomplete") is True
+ # This class carries two different facts, and only this boolean separates them in the index: here
+ # the readyState read SUCCEEDED and said "loading", so a rate over the class is not a probe failure.
+ assert (r.data or {}).get("readiness_read_failed") is False
+
+
+async def test_navigate_that_never_commits_is_an_error_naming_the_url(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A navigation that produced no document stays a failure — but as a tool result the model can read,
+ # carrying the URL it asked for. RED before: the handler re-raised, and the loop reported a bare
+ # "tool_error: TimeoutError" with no target in it.
+ page, tools = _readiness_tools(monkeypatch, "complete")
+
+ async def _dead(url: str, timeout: int | None = None, wait_until: str | None = None) -> Any:
+ page.calls.append(("goto", {"url": url, "timeout": timeout, "wait_until": wait_until}))
+ raise _PlaywrightError(f"Page.goto: net::ERR_CONNECTION_CLOSED at {url}")
+
+ page.goto = _dead # type: ignore[assignment]
+ r = await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+ assert r.status == "error", r.content
+ assert r.content.startswith("navigation to https://jobs.example.test/acme/123")
+ assert "ERR_CONNECTION_CLOSED" in r.content
+ assert r.error_class == "navigation_failed"
+ # The driver's own code, so the loop's record still names WHY a navigation failed without the
+ # traceback the raise used to carry.
+ assert (r.data or {}).get("nav_error_code") == "net::ERR_CONNECTION_CLOSED"
+ assert not _load_state_waits(page) # nothing committed, so nothing to wait on
+
+ # The driver names the URL that failed IN FULL, query string included, and that text is what the
+ # model reads back in its transcript. A sign-in link is a bearer secret there exactly as it is in a
+ # log line, so every URL the driver named is reduced to scheme and host. The model's own argument
+ # is still echoed whole — it typed it, and the message has to say which navigation failed.
+ signed = "https://app.example.test/session?token=SUPERSECRET123"
+ secret_page, secret_tools = _readiness_tools(monkeypatch, "complete")
+
+ async def _dead_signed(url: str, timeout: int | None = None, wait_until: str | None = None) -> Any:
+ raise _PlaywrightError(f"Page.goto: net::ERR_CONNECTION_CLOSED at {url}")
+
+ secret_page.goto = _dead_signed # type: ignore[assignment]
+ secret = await _tool(secret_tools, "navigate").handler({"url": signed})
+ assert secret.status == "error", secret.content
+ assert secret.content.count("SUPERSECRET123") == 1 # the argument echo, and nothing the driver said
+ assert "net::ERR_CONNECTION_CLOSED at https://app.example.test/<redacted>" in secret.content
+
+
+async def test_navigate_logs_the_landing_host_only_however_the_url_was_reached(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # `landed_url` is an INDEXED log field, on a record that is otherwise names, sizes and booleans. A
+ # workflow credential placeholder is substituted into the URL at this boundary, a redirect hands
+ # the landing whatever token it likes, and a URL the MODEL typed is one it copied off the page it
+ # was shown — a signed link is a bearer secret in all three cases. So the field is scheme and host,
+ # unconditionally. RED before: the session token below reached `taskv3 tool call finished` in plain
+ # text whenever the landing was byte-identical to the argument.
+ signed = "https://app.example.test/session?token=SUPERSECRET123"
+ # The model typed the signed URL itself and landed on it verbatim — the case the byte-identical
+ # exemption used to log whole, and the commonest one: the model copies the link off the page.
+ _typed_page, typed_tools = _readiness_tools(monkeypatch, "complete")
+ typed = await _tool(typed_tools, "navigate").handler({"url": signed})
+ assert typed.status == "ok", typed.content
+ assert (typed.data or {})["landed_url"] == "https://app.example.test/<redacted>"
+ # Asserted at the boundary the rule exists for: the indexed record is built from these two fields.
+ # SKY-16374's action-row outcome carries the landing raw by a different rule — it reaches no log
+ # line, and the persistence boundary redacts it against the run's own secret values.
+ assert _navigate_record_fields("navigate", {"url": signed}, typed) == {
+ "requested_url": "https://app.example.test/<redacted>",
+ "landed_url": "https://app.example.test/<redacted>",
+ "same_page": False,
+ }
+ # And a workflow credential placeholder, substituted into the URL at this boundary, whose landing
+ # the model never typed at all.
+ _page, tools = _readiness_tools(
+ monkeypatch,
+ "complete",
+ resolve_typed_text=lambda t: signed if t == "placeholder_link" else t,
+ )
+ r = await _tool(tools, "navigate").handler({"url": "placeholder_link"})
+ assert r.status == "ok", r.content
+ assert (r.data or {})["landed_url"] == "https://app.example.test/<redacted>"
+ assert "SUPERSECRET123" not in json.dumps(_navigate_record_fields("navigate", {"url": "placeholder_link"}, r))
+
+
+async def test_navigate_readiness_probe_cannot_hang_on_a_wedged_renderer(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The readyState read is the one await the loop's deadline cannot interrupt, and a renderer wedged on
+ # a synchronous script never answers it. RED before: the evaluate was unbounded, so this navigate
+ # stayed pending past any ceiling it advertised.
+ monkeypatch.setattr(settings, "TASK_V3_NAVIGATE_READINESS_TIMEOUT_MS", 10)
+ page, tools = _readiness_tools(monkeypatch, "loading")
+
+ async def _wedged(_js: str) -> str:
+ await asyncio.Event().wait()
+ raise AssertionError("unreachable")
+
+ page.evaluate = _wedged # type: ignore[assignment]
+ r = await asyncio.wait_for(
+ _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"}), timeout=15
+ )
+ assert r.status == "ok", r.content
+ assert "could not be read" in r.content
+ assert r.ok_class == "committed_not_loaded"
+ # Same ok_class as a document that genuinely never became ready, so the index needs this to tell
+ # a wedged renderer from a starved bundle — a rate over the class alone silently mixes them.
+ assert (r.data or {}).get("readiness_read_failed") is True
+ assert _navigate_record_fields("navigate", {"url": "https://jobs.example.test/acme/123"}, r) == {
+ "requested_url": "https://jobs.example.test/<redacted>",
+ "landed_url": "https://jobs.example.test/<redacted>",
+ "same_page": False,
+ "readiness_read_failed": True,
+ }
+
+ # A read that RAISES is the same fact as one that never answers, and lands on the same boolean.
+ raising_page, raising_tools = _readiness_tools(monkeypatch, "loading")
+
+ async def _raises(_js: str) -> str:
+ raise _PlaywrightError("Execution context was destroyed")
+
+ raising_page.evaluate = _raises # type: ignore[assignment]
+ raised = await _tool(raising_tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+ assert raised.ok_class == "committed_not_loaded"
+ assert (raised.data or {}).get("readiness_read_failed") is True
+
+
+async def test_navigate_onto_a_page_that_closed_while_loading_is_an_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The readiness wait leaves every driver refusal to the readyState read, so a page that DIED inside
+ # it would otherwise be reported as a committed page the model can still observe — and a finish
+ # batched behind this navigate would run its settle gate against it.
+ page, tools = _readiness_tools(monkeypatch, "complete")
+
+ async def _closing_wait(state: str = "load", timeout: float | None = None) -> None:
+ page._closed = True
+ raise _PlaywrightError("Target page, context or browser has been closed")
+
+ page.wait_for_load_state = _closing_wait # type: ignore[assignment]
+ r = await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+ assert r.status == "error", r.content
+ assert "the page closed" in r.content and r.error_class == "navigation_failed"
+
+
+async def test_navigate_keeps_the_traceback_for_a_failure_no_driver_reported(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Only a driver's own refusal is a navigation verdict. A defect in this repo's own navigation path
+ # raises and keeps its traceback through the loop's `taskv3 tool handler raised` line, rather than
+ # being flattened into a navigation_failed carrying no cause at all.
+ page, tools = _readiness_tools(monkeypatch, "complete")
+
+ async def _bug(url: str, timeout: int | None = None, wait_until: str | None = None) -> Any:
+ raise AttributeError("'NoneType' object has no attribute 'send'")
+
+ page.goto = _bug # type: ignore[assignment]
+ with pytest.raises(AttributeError):
+ await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+
+
@pytest.mark.asyncio
async def test_navigate_validates_url_before_goto(monkeypatch: pytest.MonkeyPatch) -> None:
# A model-chosen URL must go through the repo's SSRF/URL validation before page.goto.
@@ -8272,6 +8549,18 @@ _SEGMENTED_DATE_SKINNED_SUBPIXEL_HTML = """
[
# Focus lands, then the widget moves the caret to the next segment: keys fill the wrong field.
("year.addEventListener('focus', () => document.getElementById('month').focus());", "2023"),
+ # Focus lands AND holds, but the widget routes the characters to the segment its own cursor is
+ # on. document.activeElement never stops being the target, so nothing before the read-back can
+ # tell this apart from a fill -- and the keys are already in the sibling by then.
+ (
+ "year.addEventListener('beforeinput', (e) => {"
+ " e.preventDefault();"
+ " const m = document.getElementById('month');"
+ " m.value += (e.data || '');"
+ " m.dispatchEvent(new Event('input', {bubbles: true}));"
+ "});",
+ "2023",
+ ),
# Focus lands and stays, but the widget swallows every key.
(
"year.addEventListener('keydown', (e) => e.preventDefault());"
@@ -8283,7 +8572,13 @@ _SEGMENTED_DATE_SKINNED_SUBPIXEL_HTML = """
# The widget trims what it was given, so the field no longer holds the requested text.
("year.addEventListener('input', () => { year.value = year.value.trim(); });", "2023 "),
],
- ids=["keys-land-in-sibling-segment", "keys-dropped", "cleared-after-typing", "trimmed"],
+ ids=[
+ "keys-land-in-sibling-segment",
+ "keys-rerouted-while-focus-holds",
+ "keys-dropped",
+ "cleared-after-typing",
+ "trimmed",
+ ],
)
@pytest.mark.parametrize(
"template", [_SEGMENTED_DATE_HTML, _SEGMENTED_DATE_SKINNED_SUBPIXEL_HTML], ids=["unclickable", "skinned-subpixel"]
@@ -8375,6 +8670,307 @@ async def test_type_date_widget_clamping_a_segment_on_blur_is_not_reported_as_fi
# The same unclickable shape on a field that only commits a picked suggestion: the raw query sits in
# the input until blur, so reading it back proves nothing.
+# A refusal only proves the target does not hold EXACTLY what was typed -- not that the keystrokes
+# never reached it. Both shapes below refuse, and in both the sibling's value is the page's own work,
+# so taking it back would destroy state no one else can recover.
+_SEGMENTED_DATE_AUTO_ADVANCE_HTML = """
+<div role="group" aria-label="Start date" style="display:flex;width:240px;height:30px">
+ <div style="position:relative;width:60px;height:30px">
+ <input id="month" type="text" role="spinbutton" aria-label="Month" maxlength="2"
+ style="position:absolute;left:4px;top:4px;width:1px;height:0.5px;padding:0;border:0;box-sizing:border-box">
+ <div aria-hidden="true" style="position:absolute;inset:0;z-index:1;background:#fff">MM</div>
+ </div>
+ <div style="position:relative;width:60px;height:30px">
+ <input id="year" type="text" role="spinbutton" aria-label="Year" maxlength="4"
+ style="position:absolute;left:4px;top:4px;width:1px;height:0.5px;padding:0;border:0;box-sizing:border-box">
+ <div aria-hidden="true" style="position:absolute;inset:0;z-index:1;background:#fff">YYYY</div>
+ </div>
+</div>
+<script>
+ const month = document.getElementById("month");
+ const year = document.getElementById("year");
+ month.addEventListener("beforeinput", (e) => {
+ if (month.value.length >= 2) { e.preventDefault(); year.value += (e.data || ""); }
+ });
+</script>
+"""
+
+
+# The widget takes the text, then cascade-fills a sibling from it and replaces the query with its own
+# label -- so the target moved, and the dial code beside it is the page's answer to a value it DID get.
+_CASCADE_SIBLING_HTML = """
+<div role="group" aria-label="Phone">
+ <div style="position:relative;width:300px;height:30px;overflow:hidden">
+ <div aria-hidden="true" style="position:absolute;inset:0;background:#fff">Country</div>
+ <input id="country" type="text" tabindex="-1" aria-label="Country"
+ style="position:absolute;left:-500px;top:0;width:200px;height:30px">
+ </div>
+ <input id="dial" type="text" aria-label="Dial code" style="width:80px">
+</div>
+<script>
+ const country = document.getElementById("country");
+ country.addEventListener("input", () => {
+ if (!country.value) return;
+ document.getElementById("dial").value = "+1";
+ // Canonicalises the query into its own label, so the field no longer holds what was typed.
+ if (country.value !== "Springfield (US)") { country.value = "Springfield (US)"; }
+ });
+</script>
+"""
+
+
+@_skip_no_browser
+ ("template", "selector", "text", "sibling", "expected"),
+ [
+ (_SEGMENTED_DATE_AUTO_ADVANCE_HTML, "#month", "012026", "#year", "2026"),
+ (_CASCADE_SIBLING_HTML, "#country", "Springfield", "#dial", "+1"),
+ ],
+ ids=["segment-auto-advance", "page-cascade"],
+)
+async def test_a_refusal_never_takes_back_a_sibling_the_page_itself_wrote(
+ template: str, selector: str, text: str, sibling: str, expected: str
+) -> None:
+ # The keystroke-collateral restore may only fire when the target proves it never took the keys.
+ # Widen it to "the target does not hold exactly what I typed" and it erases a correctly filled
+ # date segment, or a cascade-filled dial code -- neither of which the run can recover.
+ async with _content_page(template) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": selector, "text": text})
+ assert await page.eval_on_selector(sibling, "el => el.value") == expected
+
+
+# Two siblings the reroute moves at once, each holding a DIFFERENT prior value. Restoring "something"
+# is not enough -- each field has to get its OWN value back, which a mispaired tag would not do.
+_SEGMENTED_DATE_TWO_VICTIMS_HTML = """
+<div role="group" aria-label="Start date" style="display:flex;width:300px;height:30px">
+ <div style="position:relative;width:60px;height:30px">
+ <input id="month" type="text" role="spinbutton" aria-label="Month"
+ style="position:absolute;left:4px;top:4px;width:1px;height:0.5px;padding:0;border:0;box-sizing:border-box">
+ <div aria-hidden="true" style="position:absolute;inset:0;z-index:1;background:#fff">MM</div>
+ </div>
+ <input id="day" type="text" aria-label="Day" value="07" style="width:40px">
+ <input id="year" type="text" aria-label="Year" value="1999" style="width:60px">
+</div>
+<script>
+ const month = document.getElementById("month");
+ let n = 0;
+ month.addEventListener("beforeinput", (e) => {
+ e.preventDefault();
+ const target = (n++ < 2) ? "day" : "year";
+ document.getElementById(target).value += (e.data || "");
+ });
+</script>
+"""
+
+
+@_skip_no_browser
+async def test_a_collateral_restore_hands_each_sibling_back_its_own_value() -> None:
+ # Both siblings are moved by the same refused type. Handing back the right VALUES to the wrong
+ # FIELDS repairs neither, and leaves a form that reads as filled with two values nobody entered.
+ async with _content_page(_SEGMENTED_DATE_TWO_VICTIMS_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": "#month", "text": "2026"})
+ assert await page.eval_on_selector("#day", "el => el.value") == "07"
+ assert await page.eval_on_selector("#year", "el => el.value") == "1999"
+
+
+# The group is declared on a custom element HOST and the segments live in its open shadow root, so
+# `closest` from the field finds no scope without climbing the host chain.
+_SHADOW_GROUP_MISROUTE_HTML = """
+<x-dob id="dob" role="group" aria-label="Date of birth"></x-dob>
+<script>
+ class XDob extends HTMLElement {
+ connectedCallback() {
+ const root = this.attachShadow({ mode: "open" });
+ root.innerHTML =
+ '<div style="position:relative;width:60px;height:30px">' +
+ '<input id="year" type="text" role="spinbutton" aria-label="Year"' +
+ ' style="position:absolute;left:4px;top:4px;width:1px;height:0.5px;padding:0;border:0;box-sizing:border-box">' +
+ '<div aria-hidden="true" style="position:absolute;inset:0;z-index:1;background:#fff">YYYY</div></div>' +
+ '<div style="position:relative;width:40px;height:30px">' +
+ '<input id="month" type="text" role="spinbutton" aria-label="Month"' +
+ ' style="position:absolute;left:4px;top:4px;width:1px;height:0.5px;padding:0;border:0;box-sizing:border-box">' +
+ '<div aria-hidden="true" style="position:absolute;inset:0;z-index:1;background:#fff">MM</div></div>';
+ const year = root.getElementById("year");
+ const month = root.getElementById("month");
+ year.addEventListener("beforeinput", (e) => {
+ e.preventDefault();
+ month.value += (e.data || "");
+ });
+ }
+ }
+ customElements.define("x-dob", XDob);
+</script>
+"""
+
+
+@_skip_no_browser
+async def test_a_group_declared_on_a_shadow_host_still_bounds_the_repair() -> None:
+ # `closest` stops at the shadow boundary, so without climbing to the host no scope is found,
+ # nothing is captured, and the routed characters stay in the sibling -- the repair silently not
+ # happening for a whole class of custom element.
+ async with _content_page(_SHADOW_GROUP_MISROUTE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})
+ held = await page.evaluate("() => document.getElementById('dob').shadowRoot.getElementById('month').value")
+ assert held == ""
+
+
+# The page's own write, resolving ASYNCHRONOUSLY. The capture sits after the focus click so that a
+# focus-driven write is already in the snapshot -- but one that resolves on a timer lands after it, in
+# the window the suggestion poll holds open, and target equality cannot tell it from our keystrokes.
+_ASYNC_PAGE_WRITE_HTML = (
+ _SEGMENTED_DATE_HTML
+ + """
+<script>
+ const _y = document.getElementById("year");
+ _y.addEventListener("keydown", (e) => e.preventDefault());
+ _y.addEventListener(
+ "focus",
+ () => { setTimeout(() => { document.getElementById("month").value = "PAGE"; }, 250); },
+ { once: true }
+ );
+</script>
+"""
+)
+
+
+@_skip_no_browser
+async def test_an_async_page_write_after_the_keys_is_not_collateral() -> None:
+ # The target takes nothing, so `ours` is true and the restore runs -- and the sibling holds a value
+ # the PAGE wrote a quarter-second after the keys stopped. Attribution from the target alone cannot
+ # see the difference; only the timing can, so the moved set is taken the moment the keys stop.
+ async with _content_page(_ASYNC_PAGE_WRITE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": "#year", "text": "2026"})
+ assert await page.eval_on_selector("#month", "el => el.value") == "PAGE"
+
+
+# A field the page owns, OUTSIDE the declared group, rewritten while the keys are being sent. The
+# capture must not see it at all: `getRootNode` on a light-DOM target is the document, so a root test
+# that does not require a shadow host puts the whole page in scope.
+_OUT_OF_GROUP_PAGE_WRITE_HTML = """
+<form id="grp">
+ <div style="position:relative;width:60px;height:30px">
+ <input id="year" type="text" role="spinbutton" aria-label="Year"
+ style="position:absolute;left:-500px;top:0;width:60px;height:30px">
+ </div>
+</form>
+<input id="outside" type="text" aria-label="Outside" value="KEEP" style="width:80px">
+<script>
+ const year = document.getElementById("year");
+ year.addEventListener("keydown", (e) => {
+ e.preventDefault();
+ document.getElementById("outside").value = "PAGE";
+ });
+</script>
+"""
+
+
+@_skip_no_browser
+async def test_a_field_outside_the_declared_group_is_never_collateral() -> None:
+ # The target drops every key, so the refusal and the restore both run -- and a field the page owns
+ # outside the group must not be reachable by that restore at all.
+ async with _content_page(_OUT_OF_GROUP_PAGE_WRITE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": "#year", "text": "2026"})
+ assert await page.eval_on_selector("#outside", "el => el.value") == "PAGE"
+
+
+# The declared group is a LIGHT-dom ancestor and the segments live in a custom element beneath it, so
+# the scope is the form -- which has no shadow root of its own. Without the target's own root in the
+# set, none of its actual siblings are reachable and the repair silently does nothing.
+_LIGHT_GROUP_SHADOW_TARGET_HTML = """
+<form id="grp"><x-seg id="seg"></x-seg></form>
+<script>
+ class XSeg extends HTMLElement {
+ connectedCallback() {
+ const root = this.attachShadow({ mode: "open" });
+ root.innerHTML =
+ '<input id="year" type="text" role="spinbutton" aria-label="Year"' +
+ ' style="position:absolute;left:-500px;top:0;width:60px;height:30px">' +
+ '<input id="month" type="text" role="spinbutton" aria-label="Month" style="width:40px">';
+ const year = root.getElementById("year");
+ const month = root.getElementById("month");
+ year.addEventListener("beforeinput", (e) => {
+ e.preventDefault();
+ month.value += (e.data || "");
+ });
+ }
+ }
+ customElements.define("x-seg", XSeg);
+</script>
+"""
+
+
+@_skip_no_browser
+async def test_a_shadow_target_under_a_light_dom_group_still_reaches_its_siblings() -> None:
+ # The group resolves to the light-dom form, whose own subtree contains no inputs at all -- the
+ # siblings that took our keys are in the target's shadow root, and must be reachable from there.
+ async with _content_page(_LIGHT_GROUP_SHADOW_TARGET_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})
+ held = await page.evaluate("() => document.getElementById('seg').shadowRoot.getElementById('month').value")
+ assert held == ""
+
+
+# The declared group lives INSIDE the component, so it already bounds the scan -- widening to the whole
+# shadow root would put the component's other fields back in range, which is the document over-reach
+# one boundary in.
+_GROUP_INSIDE_SHADOW_ROOT_HTML = """
+<x-panel id="panel"></x-panel>
+<script>
+ class XPanel extends HTMLElement {
+ connectedCallback() {
+ const root = this.attachShadow({ mode: "open" });
+ root.innerHTML =
+ '<fieldset id="grp">' +
+ '<input id="year" type="text" role="spinbutton" aria-label="Year"' +
+ ' style="position:absolute;left:-500px;top:0;width:60px;height:30px">' +
+ '<input id="month" type="text" role="spinbutton" aria-label="Month" style="width:40px">' +
+ '</fieldset>' +
+ '<input id="elsewhere" type="text" aria-label="Elsewhere" value="KEEP" style="width:80px">';
+ const year = root.getElementById("year");
+ const month = root.getElementById("month");
+ year.addEventListener("beforeinput", (e) => {
+ e.preventDefault();
+ month.value += (e.data || "");
+ root.getElementById("elsewhere").value = "PAGE";
+ });
+ }
+ }
+ customElements.define("x-panel", XPanel);
+</script>
+"""
+
+
+@_skip_no_browser
+async def test_a_group_inside_a_shadow_root_still_bounds_the_scan() -> None:
+ # The sibling INSIDE the declared fieldset is ours and comes back; the component's own field
+ # OUTSIDE it is the page's and must be out of range entirely.
+ async with _content_page(_GROUP_INSIDE_SHADOW_ROOT_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ with contextlib.suppress(Exception):
+ await _tool(tools, "type").handler({"selector": "#year", "text": "2023"})
+ root = "() => document.getElementById('panel').shadowRoot"
+ assert await page.evaluate(f"{root}.getElementById('month').value") == ""
+ assert await page.evaluate(f"{root}.getElementById('elsewhere').value") == "PAGE"
+
+
_UNCLICKABLE_TYPEAHEAD_HTML = """
<div style="position:relative;width:300px;height:30px;overflow:hidden">
<div aria-hidden="true" style="position:absolute;inset:0;background:#fff">City</div>
@@ -16595,7 +17191,8 @@ async def test_navigate_derives_a_ref_only_for_a_redirect_reached_through_a_payl
r = await _tool(tools, "navigate").handler({"url": token})
assert r.content == "navigated to chrome-error://chromewebdata/" and len(refs.refs) == 1
# A credential placeholder is substituted too, but it is not payload provenance: a redirect reached
- # through one derives nothing, and its navigation failure is reported as raised.
+ # through one derives nothing, and its navigation failure leads with the placeholder. The driver's
+ # own message still follows, exactly as it did when this path raised.
refs = _refs_for(_SIGNED_REF_URL)
tools = build_browser_tools(
_fixed_page_provider(_RedirectingPage()),
@@ -16606,15 +17203,16 @@ async def test_navigate_derives_a_ref_only_for_a_redirect_reached_through_a_payl
)
r = await _tool(tools, "navigate").handler({"url": "placeholder_sso"})
assert landing not in refs.refs.values() and r.content == f"navigated to {landing}"
- with pytest.raises(RuntimeError):
- tools = build_browser_tools(
- _fixed_page_provider(_FailingPage()),
- resolve_typed_text=refs.chain(
- lambda t: "https://portal.example.test/login?sso=1" if t == "placeholder_sso" else t
- ),
- opaque_refs=refs,
- )
- await _tool(tools, "navigate").handler({"url": "placeholder_sso"})
+ tools = build_browser_tools(
+ _fixed_page_provider(_FailingPage()),
+ resolve_typed_text=refs.chain(
+ lambda t: "https://portal.example.test/login?sso=1" if t == "placeholder_sso" else t
+ ),
+ opaque_refs=refs,
+ )
+ r = await _tool(tools, "navigate").handler({"url": "placeholder_sso"})
+ assert r.status == "error" and "ERR_NAME_NOT_RESOLVED" in r.content
+ assert r.content.startswith("navigation to placeholder_sso")
# A model-chosen live URL that happens to redirect to a signed page has no payload provenance.
refs = _refs_for(_SIGNED_REF_URL)
tools = build_browser_tools(
@@ -17085,6 +17683,31 @@ async def test_the_not_both_guard_still_rejects_a_model_selector_but_not_a_re_di
assert (await _tool(tools, "click").handler(args)).status == "ok"
+@_skip_no_browser
+async def test_a_zero_mark_beside_a_ref_acts_on_the_ref() -> None:
+ # A non-strict provider fills every optional slot, so a ref act arrives as {"selector": "ref=2",
+ # "mark": 0}. look() numbers from 1, so a refusal here refuses every act the model makes.
+ html = (
+ '<input id="user" oninput="document.getElementById(\'go\').disabled = !this.value.trim()">'
+ '<button id="go" disabled onclick="document.body.dataset.sent = 1">Continue</button>'
+ )
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ observed = await _tool(tools, "observe").handler({})
+ user_ref = re.search(r"^(ref=\d+) input", observed.content, re.MULTILINE).group(1)
+ go_ref = re.search(r"^(ref=\d+) button", observed.content, re.MULTILINE).group(1)
+
+ typed = await _tool(tools, "type").handler(
+ {"selector": user_ref, "mark": 0, "text": "demo_user", "clear": True, "press_enter": False}
+ )
+ clicked = await _tool(tools, "click").handler({"selector": go_ref, "mark": 0})
+
+ assert typed.status == "ok", typed.content
+ assert clicked.status == "ok", clicked.content
+ assert await page.evaluate("() => document.body.dataset.sent") == "1"
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_repeating_a_mark_act_leaves_the_page_fingerprint_untouched() -> None:
@@ -19726,6 +20349,1277 @@ async def test_select_combobox_refuses_ambiguous_leading_clause_city_instead_of_
)
+# A server-search postal lookup that searches only the FIRST word of the query and returns at most 20
+# rows. The whole label answers with other rows for the same city, so the exact row is only reachable by
+# searching for the part that singles it out -- which only the caller can pick, whatever the separator.
+_POSTAL_FIRST_WORD_SEARCH_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-controls="zip-list"
+ style="position:absolute;top:20px;left:20px;width:360px;height:24px">
+ <div id="zip-list" role="listbox"
+ style="position:absolute;top:50px;left:20px;width:360px;background:#fff;display:none"></div>
+ <script>
+ var FMT = function (place, code) { return %s; };
+ var ROWS = [];
+ for (var i = 1; i <= 40; i++) {
+ ROWS.push(FMT('Phoenix, Maricopa, Arizona, United States', String(85000 + i)));
+ }
+ ROWS.push(FMT('Rapolla, Potenza, Basilicata, Italy', '85027'));
+ ROWS.push(FMT('Novoviktorivka, Dobropilskyi, Donetska, Ukraine', '85027'));
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ var timer = null;
+ function hide() { list.innerHTML = ''; list.style.display = 'none'; }
+ function render(rows) {
+ list.innerHTML = '';
+ if (!rows.length) { hide(); return; }
+ rows.forEach(function (text) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.style.height = '20px';
+ row.textContent = text;
+ row.addEventListener('click', function () {
+ input.value = text;
+ input.setAttribute('data-committed', text);
+ hide();
+ });
+ list.appendChild(row);
+ });
+ list.style.display = 'block';
+ }
+ input.addEventListener('input', function () {
+ clearTimeout(timer);
+ var word = (input.value.split(/[\\s,]+/).filter(Boolean)[0] || '').toLowerCase();
+ timer = setTimeout(function () {
+ if (!word) { hide(); return; }
+ render(ROWS.filter(function (r) { return r.toLowerCase().indexOf(word) >= 0; }).slice(0, 20));
+ }, 150);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+ ("fmt", "value"),
+ [
+ ("place + ' - ' + code", "Phoenix, Maricopa, Arizona, United States - 85027"),
+ ("place + ' (' + code + ')'", "Phoenix, Maricopa, Arizona, United States (85027)"),
+ ("place + '\u2013' + code", "Phoenix, Maricopa, Arizona, United States\u201385027"),
+ ("place + '/' + code", "Phoenix, Maricopa, Arizona, United States/85027"),
+ ("place + ' [' + code + ']'", "Phoenix, Maricopa, Arizona, United States [85027]"),
+ ],
+ ids=["spaced-dash", "parenthesized", "unspaced-en-dash", "slash", "bracketed"],
+)
+async def test_select_combobox_reaches_a_full_label_through_a_caller_chosen_search(fmt: str, value: str) -> None:
+ # The full label renders only other rows. The refusal must offer a way out other than repeating the
+ # same call, and taking it must commit exactly the requested row, whatever separates the code.
+ async with _live_page(_POSTAL_FIRST_WORD_SEARCH_HTML % fmt) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ refused = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value})
+ assert refused.status == "error", refused.content
+ assert "search" in refused.content, refused.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") is None
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+# A declared lookup that answers an exact code by writing the full label into the field itself, with no rows.
+_CODE_AUTOFILL_HTML = """
+<!doctype html><html><body>
+<input id="zip" type="text" role="combobox" aria-autocomplete="list" aria-controls="zip-list" aria-expanded="false"
+ style="position:absolute;top:20px;left:20px;width:360px;height:24px">
+<div id="zip-list" role="listbox" style="display:none"></div>
+<script>
+ var input = document.getElementById('zip');
+ input.addEventListener('input', function () {
+ if (input.value === '85027') setTimeout(function () { input.value = 'Phoenix, Maricopa, Arizona - 85027'; }, 50);
+ });
+</script></body></html>
+"""
+
+
+# Rows that declare nothing, in the shapes a row's label takes in the DOM. `%(parts)s` builds one row's
+# markup from r = [place, code]; `%(rows)s` is the row data, so identical sibling rows can be expressed.
+_POSTAL_STRUCTURED_ROWS_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:360px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:360px;background:#fff;display:none"></div>
+ <script>
+ var ROWS = %(rows)s;
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ setTimeout(function () {
+ list.innerHTML = '';
+ ROWS.filter(function (r) { return input.value && r[1].indexOf(input.value) >= 0; }).forEach(function (r) {
+ var row = document.createElement('div');
+ row.style.cursor = 'pointer';
+ row.innerHTML = %(parts)s;
+ row.addEventListener('click', function () {
+ input.value = row.innerText.replace(/\\s+/g, ' ');
+ input.setAttribute('data-clicks', String(Number(input.getAttribute('data-clicks') || 0) + 1));
+ input.setAttribute('data-committed', input.value);
+ });
+ list.appendChild(row);
+ });
+ list.style.display = list.children.length ? 'block' : 'none';
+ }, 150);
+ });
+ </script>
+</body></html>
+"""
+
+
+_TWO_CODES = "[['Phoenix, Maricopa, Arizona', '85026'], ['Phoenix, Maricopa, Arizona', '85027']]"
+
+
+@_skip_no_browser
+ ("parts", "value"),
+ [
+ ("r[0] + ' - ' + r[1]", "Phoenix, Maricopa, Arizona - 85027"),
+ ("'<span>' + r[0] + '</span> - <span>' + r[1] + '</span>'", "Phoenix, Maricopa, Arizona - 85027"),
+ ("'<div>' + r[0] + '</div><div>' + r[1] + '</div>'", "Phoenix, Maricopa, Arizona 85027"),
+ ("'<span>' + r[0] + ' - ' + r[1] + '</span>'", "Phoenix, Maricopa, Arizona - 85027"),
+ ("'<div><span>' + r[0] + ' - ' + r[1] + '</span></div>'", "Phoenix, Maricopa, Arizona - 85027"),
+ ("'<span>' + r[0] + ' - ' + r[1] + '</span><span>\\u200b</span>'", "Phoenix, Maricopa, Arizona - 85027"),
+ ("'<span>' + r[0] + '</span> - <span>' + r[1] + '\\u200b</span>'", "Phoenix, Maricopa, Arizona - 85027"),
+ (
+ "'<span>' + r[0].replace('Phoenix', 'Stra\\u00dfe') + '</span> - <span>' + r[1] + '</span>'",
+ "STRASSE, Maricopa, Arizona - 85027",
+ ),
+ ],
+ ids=[
+ "leaf-text",
+ "inline-parts",
+ "stacked-parts",
+ "single-wrapping-child",
+ "nested-wrappers",
+ "wrapping-child-with-invisible-sibling",
+ "zero-width-in-code",
+ "full-casefold",
+ ],
+)
+async def test_select_combobox_search_commits_an_undeclared_row_built_from_parts(parts: str, value: str) -> None:
+ async with _live_page(_POSTAL_STRUCTURED_ROWS_HTML % {"parts": parts, "rows": _TWO_CODES}) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "8502"})
+ assert r.status == "ok", r.content
+ committed = await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')")
+ assert _exact_tier_key(committed) == _exact_tier_key(value)
+
+
+@_skip_no_browser
+async def test_select_combobox_search_never_guesses_between_identical_undeclared_rows() -> None:
+ # Two sibling rows with the same text and nothing else to tell them apart: which one is meant is not
+ # knowable, so neither may be clicked.
+ rows = "[['Phoenix, Maricopa, Arizona', '85027'], ['Phoenix, Maricopa, Arizona', '85027']]"
+ html = _POSTAL_STRUCTURED_ROWS_HTML % {"parts": "'<span>' + r[0] + ' - ' + r[1] + '</span>'", "rows": rows}
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(
+ {"selector": "#zip", "value": "Phoenix, Maricopa, Arizona - 85027", "search": "8502"}
+ )
+ assert r.status == "error", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-clicks')") is None
+
+
+# A field that declares its list, over undeclared nodes that each commit their own text: a node holding
+# several of them reads as one row whose parts add up to the value, but a click on it commits one part.
+_POSTAL_PART_ROWS_HTML = """
+<!doctype html><html><body style="margin:0">
+ <div><input type="hidden" id="zip-value">
+ <input id="zip" type="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-controls="zip-list"
+ style="position:absolute;top:20px;left:20px;width:360px;height:24px"></div>
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:360px;background:#fff;display:none"></div>
+ <script>
+ var PARTS = %s, INTO_HIDDEN = %s, GROUP_VALUE = %s;
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ setTimeout(function () {
+ list.innerHTML = '';
+ if (!input.value) { list.style.display = 'none'; return; }
+ var group = document.createElement('div');
+ if (GROUP_VALUE) group.setAttribute('data-value', GROUP_VALUE);
+ PARTS.forEach(function (text) {
+ var part = document.createElement('div');
+ part.style.height = '20px';
+ part.style.cursor = 'pointer';
+ part.textContent = text;
+ part.addEventListener('click', function () {
+ input.value = INTO_HIDDEN ? '' : text;
+ document.getElementById('zip-value').value = INTO_HIDDEN ? text : '';
+ input.setAttribute('data-committed', text);
+ list.innerHTML = '';
+ list.style.display = 'none';
+ });
+ group.appendChild(part);
+ });
+ list.appendChild(group);
+ list.style.display = 'block';
+ }, 150);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+ ("parts", "value", "search", "into_hidden", "group_value"),
+ [
+ ("['Phoenix', '85027']", "Phoenix 85027", "8502", "false", "null"),
+ ("['Phoenix', 'AZ']", "Phoenix AZ", "Phoe", "false", "null"),
+ ("['Phoenix', '85027']", "Phoenix 85027", "8502", "true", "null"),
+ ("['Phoenix', '85027']", "Phoenix 85027", "85", "false", "'85027'"),
+ ],
+ ids=["overlapping-part", "short-part", "part-into-hidden-input", "group-declares-the-part"],
+)
+async def test_select_combobox_search_never_reports_one_part_of_the_value_as_committed(
+ parts: str, value: str, search: str, into_hidden: str, group_value: str
+) -> None:
+ async with _live_page(_POSTAL_PART_ROWS_HTML % (parts, into_hidden, group_value)) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": search})
+ committed = await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')")
+ assert committed is not None, "the fixture must reach the click for this to test the read-back"
+ assert r.status != "ok", (committed, r.content)
+
+
+# A declared lookup that answers only a two-letter query, where "California" commits its declared code "CA"
+# while another row is labelled "CA".
+_STATE_CODE_COLLISION_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="st" type="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-controls="st-list"
+ style="position:absolute;top:20px;left:20px;width:300px;height:24px">
+ <div id="st-list" role="listbox"
+ style="position:absolute;top:50px;left:20px;width:300px;background:#fff;display:none"></div>
+ <script>
+ var ROWS = [['California', 'CA'], ['CA', 'CA-OTHER']];
+ var input = document.getElementById('st');
+ var list = document.getElementById('st-list');
+ var timer = null;
+ input.addEventListener('input', function () {
+ clearTimeout(timer);
+ var q = input.value.trim().toLowerCase();
+ timer = setTimeout(function () {
+ list.innerHTML = '';
+ var hits = ROWS.filter(function (r) { return q.length && q.length <= 2 && r[0].toLowerCase().indexOf(q) === 0; });
+ hits.forEach(function (r) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('data-value', r[1]);
+ row.style.height = '20px';
+ row.textContent = r[0];
+ row.addEventListener('click', function () {
+ input.value = r[1];
+ input.setAttribute('data-committed', r[0]);
+ list.innerHTML = '';
+ list.style.display = 'none';
+ });
+ list.appendChild(row);
+ });
+ list.style.display = hits.length ? 'block' : 'none';
+ }, 150);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "Ca"], ids=["ladder", "search"])
+async def test_select_combobox_accepts_the_chosen_rows_code_that_another_row_is_labelled(search: str | None) -> None:
+ # The field holds "CA" because the California row committed it; another row wearing that label does not
+ # make the commit someone else's.
+ args = {"selector": "#st", "value": "California"} | ({"search": search} if search else {})
+ async with _live_page(_STATE_CODE_COLLISION_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert await page.eval_on_selector("#st", "el => el.getAttribute('data-committed')") == "California"
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#st", "el => el.value") == "CA"
+
+
+@_skip_no_browser
+async def test_select_combobox_search_never_erases_what_the_widget_wrote() -> None:
+ # Only the search was typed, so a label the page wrote in answer is the page's to keep, whatever the
+ # tool then reports; neither the value's own pieces nor an empty query may be typed over it.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ async with _live_page(_CODE_AUTOFILL_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert await page.eval_on_selector("#zip", "el => el.value") == value
+
+
+@_skip_no_browser
+async def test_select_combobox_reports_the_search_it_typed_when_the_list_is_out_of_reach() -> None:
+ # Inside a component the tool cannot see the list, so its result is only a report of what it typed:
+ # that has to be the search, which is what the field now holds.
+ html = """
+ <div id="host"></div>
+ <script>
+ const root = document.getElementById('host').attachShadow({mode: 'open'});
+ root.innerHTML = '<input id="zip" type="text" style="width:300px;height:24px">';
+ </script>
+ """
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert "could not be seen" in r.content, r.content
+ assert "'85027'" in r.content and repr(value) not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_option_on_a_first_word_lookup_points_to_the_tool_that_takes_a_search() -> None:
+ # select_option's non-native branch lands on the same refusal but has no `search`; the way out it
+ # names has to be one this caller can take, or following it loops.
+ value = "Phoenix, Maricopa, Arizona, United States - 85027"
+ async with _live_page(_POSTAL_FIRST_WORD_SEARCH_HTML % "place + ' - ' + code") as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ refused = await _tool(tools, "select_option").handler({"selector": "#zip", "value": value})
+ assert refused.status == "error", refused.content
+ assert "select_combobox" in refused.content, refused.content
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "ok", r.content
+
+
+# An async lookup that answers a city name or a code, never a full label, and shows a "Searching..." row,
+# marked as nothing but an option, before its results render.
+_POSTAL_LOADING_ROW_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-controls="zip-list"
+ style="position:absolute;top:20px;left:20px;width:360px;height:24px">
+ <div id="zip-list" role="listbox"
+ style="position:absolute;top:50px;left:20px;width:360px;background:#fff;display:none"></div>
+ <script>
+ var ROWS = [
+ ['Rapolla', 'Rapolla, Potenza, Basilicata, Italy - 85027'],
+ ['Novoviktorivka', 'Novoviktorivka, Dobropilskyi, Donetska, Ukraine - 85027'],
+ ['Rapone', 'Rapone, Potenza, Basilicata, Italy - 85020'],
+ ];
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ var timer = null;
+ input.addEventListener('input', function () {
+ clearTimeout(timer);
+ var q = input.value.trim().toLowerCase();
+ list.innerHTML = '<div role="option" style="height:20px">Searching…</div>';
+ list.style.display = 'block';
+ timer = setTimeout(function () {
+ list.innerHTML = '';
+ ROWS.filter(function (r) {
+ return q && (r[0].toLowerCase().indexOf(q) === 0 || r[1].slice(-5) === q);
+ }).forEach(function (r) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.style.height = '20px';
+ row.textContent = r[1];
+ row.addEventListener('click', function () {
+ input.value = r[1];
+ input.setAttribute('data-committed', r[1]);
+ list.innerHTML = '';
+ list.style.display = 'none';
+ });
+ list.appendChild(row);
+ });
+ }, 800);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "Rapolla", "85027"], ids=["ladder", "search-city", "search-code"])
+async def test_select_combobox_waits_past_a_loading_row_for_the_rows(search: str | None) -> None:
+ # The loading row is on screen before any result; taking it as the reaction ends the poll before the
+ # exact row renders, and the call refuses a row the widget does list.
+ value = "Rapolla, Potenza, Basilicata, Italy - 85027"
+ args = {"selector": "#zip", "value": value} | ({"search": search} if search else {})
+ async with _live_page(_POSTAL_LOADING_ROW_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "search"])
+async def test_select_combobox_hands_the_field_back_after_an_ignored_click(search: str | None) -> None:
+ # The row click does nothing and the list stays open: the refusal must not leave our search in the field.
+ click_body = (
+ "input.value = r[1];\n"
+ " input.setAttribute('data-committed', r[1]);\n"
+ " list.innerHTML = '';\n"
+ " list.style.display = 'none';\n"
+ )
+ assert click_body in _POSTAL_LOADING_ROW_HTML
+ html = _POSTAL_LOADING_ROW_HTML.replace(click_body, "")
+ value = "Rapolla, Potenza, Basilicata, Italy - 85027"
+ args = {"selector": "#zip", "value": value} | ({"search": search} if search else {})
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "error", r.content
+ assert await page.eval_on_selector("#zip", "el => el.value") == ""
+
+
+@_skip_no_browser
+async def test_select_combobox_never_commits_a_search_hit_that_is_not_the_value() -> None:
+ # Rows that declare nothing: the finder's single best hit for the search is another place sharing the
+ # code, and a search only brings rows up -- it never names the row to commit.
+ html = (
+ (_POSTAL_FIRST_WORD_SEARCH_HTML % "place + ' - ' + code")
+ .replace("row.setAttribute('role', 'option');", "")
+ .replace(' role="listbox"', "")
+ )
+ value = "Phoenix, Maricopa, Arizona, United States - 85027"
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "Rapolla"})
+ assert r.status == "error", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") is None
+ assert await page.eval_on_selector("#zip", "el => el.value") == "", "the search probe must not be left behind"
+
+
+# --- SKY-16655: gates written for the full-value path must admit the SEARCHED path ---------------
+
+# A server-search lookup whose rows carry a fully-qualified, >80-char label -- the exact shape
+# `search` exists to reach, since the long label is what the caller must commit.
+_LONG_LABEL_SEARCH_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-controls="zip-list"
+ style="position:absolute;top:20px;left:20px;width:900px;height:24px">
+ <div id="zip-list" role="listbox"
+ style="position:absolute;top:50px;left:20px;width:900px;background:#fff;display:none"></div>
+ <script>
+ var ROWS = [
+ 'Phoenix, Maricopa County, Arizona, United States of America (North America) - 85027',
+ 'Phoenix, Maricopa County, Arizona, United States of America (North America) - 85028',
+ 'Phoenixville, Chester County, Pennsylvania, United States of America (North America) - 19460'
+ ];
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ function hide() { list.innerHTML = ''; list.style.display = 'none'; }
+ input.addEventListener('input', function () {
+ var q = input.value.trim().toLowerCase();
+ if (!q) { hide(); return; }
+ var hits = ROWS.filter(function (r) { return r.toLowerCase().indexOf(q) >= 0; });
+ list.innerHTML = '';
+ if (!hits.length) { hide(); return; }
+ hits.forEach(function (text) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.style.height = '20px';
+ row.style.whiteSpace = 'nowrap';
+ row.textContent = text;
+ row.addEventListener('click', function () {
+ input.value = text;
+ input.setAttribute('data-committed', text);
+ hide();
+ });
+ list.appendChild(row);
+ });
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+_LONG_LABEL_VALUE = "Phoenix, Maricopa County, Arizona, United States of America (North America) - 85027"
+
+
+@_skip_no_browser
+async def test_select_combobox_search_reaches_a_label_longer_than_the_row_text_cap() -> None:
+ # The row-text cap is sized for a pool scored by word overlap with the TYPED text. A searched pool
+ # is not scored that way and its labels are long by construction, so the cap has to be measured
+ # from the value the caller will commit -- otherwise `search` cannot reach its own use case.
+ assert len(_LONG_LABEL_VALUE) > 80
+ async with _live_page(_LONG_LABEL_SEARCH_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(
+ {"selector": "#zip", "value": _LONG_LABEL_VALUE, "search": "85027"}
+ )
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == _LONG_LABEL_VALUE
+
+
+# A server search that holds a bare, unclassed `<li role="option">Searching...</li>` in its list while
+# it waits, then renders the real rows past the soft deadline (0.4 * rounds = 3.2s here) but inside the
+# 8s cap. Nothing about that row is visible to a markup probe: no aria-busy, no progressbar, no class.
+_SLOW_UNCLASSED_PLACEHOLDER_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-controls="zip-list"
+ style="position:absolute;top:20px;left:20px;width:600px;height:24px">
+ <ul id="zip-list" role="listbox" style="position:absolute;top:50px;left:20px;width:600px;background:#fff;
+ display:none;margin:0;padding:0;list-style:none"></ul>
+ <script>
+ var ROWS = ['Phoenix, Maricopa, Arizona - 85027', 'Rapolla, Potenza, Basilicata - 85027'];
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ var timer = null;
+ input.addEventListener('input', function () {
+ clearTimeout(timer);
+ if (!input.value.trim()) { list.innerHTML = ''; list.style.display = 'none'; return; }
+ list.innerHTML = '<li role="option" style="height:20px">Searching\\u2026</li>';
+ list.style.display = 'block';
+ timer = setTimeout(function () {
+ list.innerHTML = '';
+ ROWS.forEach(function (text) {
+ var row = document.createElement('li');
+ row.setAttribute('role', 'option');
+ row.style.height = '20px';
+ row.textContent = text;
+ row.addEventListener('click', function () {
+ input.value = text;
+ input.setAttribute('data-committed', text);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ list.appendChild(row);
+ });
+ }, 4200);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_search_waits_out_an_unclassed_loading_row() -> None:
+ # A reaction the caller's own acceptance test REFUSED says the widget is still working -- a
+ # stronger signal than any markup probe, which this placeholder gives nothing to recognise.
+ # Ending the wait on it refuses a row that was seconds away with the cap still unspent.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ async with _live_page(_SLOW_UNCLASSED_PLACEHOLDER_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+# A dropdown that renders its exact hit as a bare block above a role=option result list -- so one
+# declared sibling is enough to route the whole reaction through the declared branch.
+_MIXED_DECLARED_ROWS_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:600px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:600px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ function mk(text, roled) {
+ var row = document.createElement('div');
+ if (roled) row.setAttribute('role', 'option');
+ row.style.height = '20px';
+ row.textContent = text;
+ row.addEventListener('click', function () {
+ input.value = text;
+ input.setAttribute('data-committed', text);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ return row;
+ }
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ list.appendChild(mk('Phoenix, Maricopa, Arizona - 85027', false));
+ list.appendChild(mk('Rapolla, Potenza, Basilicata - 85027', true));
+ list.appendChild(mk('Novoviktorivka, Dobropilskyi, Donetska - 85027', true));
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
+async def test_select_combobox_keeps_a_roleless_match_beside_declared_rows(search: str | None) -> None:
+ # Whether a row is the unit is a per-candidate fact. Asking whether ANY candidate declared one and
+ # then routing every candidate through that branch drops the roleless match -- which is the value --
+ # before the exact matcher reads it, and reports the two rows that are not it as the only options.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_MIXED_DECLARED_ROWS_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+# The same mixed pool, but the bare exact match is DEAD: its click commits nothing and only makes the
+# widget re-search, which strips the row tags while the popup stays open. `aria-haspopup` and the
+# write-back `input` dispatch supply the other two conjuncts of the verifier's declared-row exemption,
+# so the pool's declared siblings are the only thing left that could vouch for this commit.
+_MIXED_POOL_DEAD_BARE_ROW_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off" aria-haspopup="listbox"
+ style="position:absolute;top:20px;left:20px;width:600px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:600px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ function mk(text, roled, dead) {
+ var row = document.createElement('div');
+ if (roled) row.setAttribute('role', 'option');
+ row.style.height = '20px';
+ row.textContent = text;
+ row.addEventListener('click', function () {
+ if (dead) {
+ window.__tv3_dead_clicked = true;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ return;
+ }
+ input.value = text;
+ input.setAttribute('data-committed', text);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ return row;
+ }
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ list.appendChild(mk('Phoenix, Maricopa, Arizona - 85027', false, true));
+ list.appendChild(mk('Rapolla, Potenza, Basilicata - 85027', true, false));
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
+async def test_select_combobox_bare_pick_in_a_mixed_pool_earns_no_declared_row_exemption(search: str | None) -> None:
+ # The verifier's exemption -- a still-open list may read as closed when declared rows, a declared
+ # field and a write-back input event all hold -- is about the row that was CLICKED. Answering it
+ # from the POOL lets a bare pick inherit a declared sibling's standing, and the field still holding
+ # the typed text then reads as the commit: right label, wrong record, status ok.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_MIXED_POOL_DEAD_BARE_ROW_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert await page.evaluate("() => !!window.__tv3_dead_clicked") is True, r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") is None, r.content
+ assert r.status == "error", r.content
+
+
+# A widget that renders each row as highlighted fragments, one child per fragment, and declares no
+# role. `%(roled)s` toggles whether the rows carry role=option -- with it, a fragment promotes to its
+# declared row; without it, the row itself has to survive the candidate gate or nothing reassembles it.
+_POSTAL_FRAGMENT_ROWS_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:900px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:900px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ function row(parts) {
+ var d = document.createElement('div');
+ if (%(roled)s) d.setAttribute('role', 'option');
+ d.style.whiteSpace = 'nowrap';
+ d.style.height = '20px';
+ parts.forEach(function (p) { var s = document.createElement('span'); s.textContent = p; d.appendChild(s); });
+ var full = parts.join('');
+ d.addEventListener('click', function () {
+ input.value = full;
+ input.setAttribute('data-committed', full);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ return d;
+ }
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ list.appendChild(row(['Phoenix', ', ', 'Maricopa', ', ', 'Arizona', ', ', 'United States', ' - ', '850', '27']));
+ list.appendChild(row(['Rapolla', ', ', 'Potenza', ', ', 'Basilicata', ', ', 'Italy', ' - ', '850', '27']));
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("roled", ["true", "false"], ids=["declared-rows", "roleless-rows"])
+async def test_select_combobox_search_reaches_a_row_built_from_many_fragments(roled: str) -> None:
+ # A child COUNT is only a proxy for "container, not row". A searched row a widget builds from
+ # highlighted fragments has a child per fragment and trips it; where nothing declares a row, its
+ # pieces have nothing to promote onto and the label never reaches the matcher whole.
+ value = "Phoenix, Maricopa, Arizona, United States - 85027"
+ async with _live_page(_POSTAL_FRAGMENT_ROWS_HTML % {"roled": roled}) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await page.fill("#zip", "85027")
+ await page.dispatch_event("#zip", "input")
+ kids = await page.evaluate("() => document.querySelector('#zip-list div').children.length")
+ assert kids > 8, f"fixture must trip the child-count gate, got {kids}"
+ await page.fill("#zip", "")
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+# A real multi-row container: many children, and its whole text normalizes to the requested value.
+# Clicking it in a real widget lands on an arbitrary row, so this one commits the WRONG value.
+_POSTAL_STACKED_CONTAINER_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:900px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:900px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ // A heading so the LIST's own text is not the value too -- otherwise the wrapper, not the
+ // container under test, is what the finder would match.
+ var head = document.createElement('div');
+ head.style.height = '14px';
+ head.textContent = 'Best match';
+ list.appendChild(head);
+ var box = document.createElement('div');
+ box.addEventListener('click', function () { input.setAttribute('data-committed', 'WRONG ROW'); });
+ ['Phoenix,', 'Maricopa,', 'Arizona,', 'United', 'States', '-', '850', '2', '7'].forEach(function (p) {
+ var line = document.createElement('div');
+ line.style.height = '11px';
+ line.textContent = p;
+ box.appendChild(line);
+ });
+ list.appendChild(box);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_search_still_refuses_a_stacked_multi_row_container() -> None:
+ # The other side of the same discriminator: children that STACK are a container whose text is the
+ # union of its rows, and clicking one lands on an arbitrary row. Admitting fragment rows must not
+ # admit these -- so the test that matters is that nothing was clicked at all.
+ value = "Phoenix, Maricopa, Arizona, United States - 850 2 7"
+ async with _live_page(_POSTAL_STACKED_CONTAINER_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "error", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") is None
+
+
+# A dropdown whose exact hit is a roleless block WRAPPING a link, beside declared rows. The candidate
+# gate's isNavRow only asks whether the node IS navigational, so the wrapper reaches the pool unflagged.
+_POSTAL_LINK_WRAPPED_HIT_HTML = """
+<!doctype html><html><body style="margin:0">
+ <form onsubmit="window.__tv3_departed = true; return false;">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:900px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:900px;background:#fff;display:none"></div>
+ </form>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var hit = document.createElement('div');
+ hit.style.height = '20px';
+ // DEPARTURE_SEL covers a typeless <button> too -- a dropdown-row idiom that SUBMITS the form.
+ var a = document.createElement(window.__tv3_departure_tag || 'a');
+ if (a.tagName === 'A') a.href = '#left-the-form';
+ a.textContent = 'Phoenix, Maricopa, Arizona - 85027';
+ a.addEventListener('click', function () { window.__tv3_departed = true; });
+ hit.addEventListener('click', function () { window.__tv3_clicked_wrapper = true; });
+ hit.appendChild(a);
+ list.appendChild(hit);
+ ['Rapolla, Potenza, Basilicata - 85027', 'Novoviktorivka, Dobropilskyi, Donetska - 85027'].forEach(function (t) {
+ var d = document.createElement('div');
+ d.setAttribute('role', 'option');
+ d.style.height = '20px';
+ d.textContent = t;
+ d.addEventListener('click', function () {
+ input.value = t; input.setAttribute('data-committed', t);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ list.appendChild(d);
+ });
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
[email protected]("departure_tag", ["a", "button"], ids=["anchor", "typeless-button"])
+async def test_select_combobox_never_clicks_a_roleless_block_wrapping_a_link(
+ search: str | None, departure_tag: str
+) -> None:
+ # Keeping roleless candidates must not smuggle one past the departure gate a promoted row clears:
+ # clicking a block that wraps an <a href> leaves the form mid-fill, which no refusal ever does.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_POSTAL_LINK_WRAPPED_HIT_HTML, f"window.__tv3_departure_tag = {departure_tag!r};") as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "error", r.content
+ # The load-bearing assertion: the wrapper must never be CLICKED. Status and committed-value
+ # both read the same either way -- the click is the only thing the departure gate changes.
+ assert await page.evaluate("() => !!window.__tv3_clicked_wrapper") is False, r.content
+ assert await page.evaluate("() => !!window.__tv3_departed") is False
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") is None
+
+
+# A stale roleless copy of a row, rendered ABOVE the declared list, carrying the same label but
+# committing a different record. Identical text is exactly what the duplicate collapse reads as "one
+# candidate wearing two faces", so nothing but declaredness tells these two apart.
+_POSTAL_TWIN_IDENTITY_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ function commit(code) {
+ input.value = 'Phoenix, Maricopa, Arizona - 85027';
+ input.setAttribute('data-record', code);
+ list.innerHTML = ''; list.style.display = 'none';
+ }
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var stale = document.createElement('div');
+ stale.style.height = '20px';
+ stale.textContent = 'Phoenix, Maricopa, Arizona - 85027';
+ stale.addEventListener('click', function () { commit('WRONG_RECORD'); });
+ list.appendChild(stale);
+ var declared = document.createElement('div');
+ declared.setAttribute('role', 'option');
+ declared.style.height = '20px';
+ declared.textContent = 'Phoenix, Maricopa, Arizona - 85027';
+ declared.addEventListener('click', function () { commit('CORRECT_RECORD'); });
+ list.appendChild(declared);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+# A roleless WRAPPER and the span carrying its label -- one candidate rendered as two nodes, related
+# by ancestry -- beside a declared sibling. Contrast with the two-siblings fixture below: same
+# "two bare exact matches" shape, opposite correct answer.
+_POSTAL_BARE_WRAPPER_AND_LEAF_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var wrap = document.createElement('div');
+ wrap.style.height = '20px';
+ var span = document.createElement('span');
+ span.textContent = 'Phoenix, Maricopa, Arizona - 85027';
+ wrap.appendChild(span);
+ wrap.addEventListener('click', function () {
+ input.value = span.textContent;
+ input.setAttribute('data-committed', span.textContent);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ list.appendChild(wrap);
+ var opt = document.createElement('div');
+ opt.setAttribute('role', 'option');
+ opt.style.height = '20px';
+ opt.textContent = 'Rapolla, Potenza, Basilicata - 85027';
+ list.appendChild(opt);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
+async def test_select_combobox_commits_a_bare_wrapper_and_leaf_as_one_candidate(search: str | None) -> None:
+ # Two bare exact matches, but NESTED: a wrapper and the node carrying its label are one candidate
+ # and the innermost stands for them. Refusing every all-bare pair would lose this; collapsing
+ # every all-bare pair would commit one of two distinct records. Nesting is what separates them.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_POSTAL_BARE_WRAPPER_AND_LEAF_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+def test_shared_taskv3_js_avoids_the_click_fakes_selector_exists_idiom() -> None:
+ # _ClickFakePage.evaluate dispatches on substrings of the REAL js, and its first branch claims the
+ # double-negation return idiom for the selector-exists probe. Any blob shared into _FIND_MENU_JS
+ # that uses it is silently answered with a bool instead of a menu, so six click tests fail for a
+ # reason nothing points at. Caught exactly that way once; this fails at the source instead.
+ from skyvern.forge.taskv3 import tools as _tools # noqa: PLC0415
+
+ idiom = "return " + "!!"
+ for name in ("_ROW_SEMANTICS_JS", "_FIND_MENU_JS", "_CLICK_PRECHECK_JS", "_MENU_AFTER_JS"):
+ blob = getattr(_tools, name)
+ assert idiom not in blob, f"{name} uses the idiom _ClickFakePage reserves for the exists probe"
+
+
+# NOTHING in the reaction declares `role=option`, so the fully-undeclared searched branch runs — the
+# one that hands every reacting node back for the caller's matcher to choose between. `%(body)s` is the
+# hazardous shape under test.
+_POSTAL_UNDECLARED_HAZARD_HTML = """
+<!doctype html><html><body style="margin:0">
+ <form>
+ <input id="other" type="text" value="KEEP" style="position:absolute;top:0;left:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ </form>
+ <script>
+ var T = 'Phoenix, Maricopa, Arizona - 85027';
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var hit = document.createElement('div');
+ hit.style.height = '20px';
+ hit.addEventListener('click', function () { window.__tv3_clicked = true; });
+ %(body)s
+ list.appendChild(hit);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+_UNDECLARED_HAZARD_BODIES = {
+ "departure-link": (
+ "var a = document.createElement('a'); a.href = '#gone'; a.textContent = T;"
+ " a.addEventListener('click', function () { window.__tv3_fired = true; }); hit.appendChild(a);"
+ ),
+ "reset-button": (
+ "var b = document.createElement('button'); b.type = 'reset'; b.textContent = T;"
+ " b.addEventListener('click', function () { window.__tv3_fired = true; }); hit.appendChild(b);"
+ ),
+ "multi-row-container": (
+ "['Phoenix,', 'Maricopa,', 'Arizona - 85027'].forEach(function (p) {"
+ " var d = document.createElement('div'); d.style.height = '18px'; d.textContent = p;"
+ " hit.appendChild(d); });"
+ ),
+}
+
+
+@_skip_no_browser
[email protected]("shape", sorted(_UNDECLARED_HAZARD_BODIES), ids=sorted(_UNDECLARED_HAZARD_BODIES))
+async def test_select_combobox_search_never_clicks_a_hazard_when_nothing_declares_a_row(shape: str) -> None:
+ # With nothing declaring a row there is even LESS vouching for a node than for a bare unit beside
+ # a declared sibling, so the same hazards must be refused here. Status reads error either way --
+ # the click is the channel, because each of these commits nothing and merely damages the page.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ html = _POSTAL_UNDECLARED_HAZARD_HTML % {"body": _UNDECLARED_HAZARD_BODIES[shape]}
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "error", r.content
+ assert await page.evaluate("() => !!window.__tv3_clicked") is False, r.content
+ assert await page.evaluate("() => !!window.__tv3_fired") is False, r.content
+ assert await page.eval_on_selector("#other", "el => el.value") == "KEEP"
+
+
+# A roleless wrapper holding a `<button type="reset">`, beside a declared sibling. A reset control is
+# deliberately NOT a "departure" -- it does not leave the page -- so the departure gate cannot see it.
+_POSTAL_RESET_WRAPPED_HIT_HTML = """
+<!doctype html><html><body style="margin:0">
+ <form>
+ <input id="other" type="text" value="ALREADY TYPED" style="position:absolute;top:0;left:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ </form>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var wrap = document.createElement('div');
+ wrap.style.height = '20px';
+ var b = document.createElement('button');
+ b.type = 'reset';
+ b.textContent = 'Phoenix, Maricopa, Arizona - 85027';
+ b.addEventListener('click', function () { window.__tv3_reset_fired = true; });
+ wrap.appendChild(b);
+ list.appendChild(wrap);
+ var opt = document.createElement('div');
+ opt.setAttribute('role', 'option');
+ opt.style.height = '20px';
+ opt.textContent = 'Rapolla, Potenza, Basilicata - 85027';
+ list.appendChild(opt);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
+async def test_select_combobox_never_clicks_a_bare_wrapper_holding_a_reset_control(search: str | None) -> None:
+ # `DEPARTURE_SEL` excludes type="reset" on purpose, so the departure gate cannot catch this one --
+ # and a reset does not navigate, it ERASES every value already entered. A node admitted purely on
+ # its own text, with no declared row vouching that it is an option, must not be clicked.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_POSTAL_RESET_WRAPPED_HIT_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "error", r.content
+ # The channel: nothing may be tagged or clicked. Status reads error either way.
+ assert await page.evaluate("() => !!window.__tv3_reset_fired") is False, r.content
+ assert "selected suggestion" not in r.content, r.content
+ assert await page.eval_on_selector("#other", "el => el.value") == "ALREADY TYPED"
+
+
+# A suggestion row that renders on TWO lines -- a label over a grey secondary line, an ordinary
+# dropdown layout -- with nothing declaring it, beside a declared sibling.
+_POSTAL_TWO_LINE_ROW_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var row = document.createElement('div');
+ var main = document.createElement('div');
+ main.style.height = '18px';
+ main.textContent = 'Phoenix, Maricopa, Arizona - 85027';
+ var sub = document.createElement('div');
+ sub.style.height = '14px';
+ sub.style.color = '#888';
+ sub.textContent = 'United States';
+ row.appendChild(main);
+ row.appendChild(sub);
+ row.addEventListener('click', function () {
+ input.value = 'Phoenix, Maricopa, Arizona - 85027 United States';
+ input.setAttribute('data-committed', input.value);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ list.appendChild(row);
+ var opt = document.createElement('div');
+ opt.setAttribute('role', 'option');
+ opt.style.height = '20px';
+ opt.textContent = 'Rapolla, Potenza, Basilicata - 85027';
+ list.appendChild(opt);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_search_reaches_a_two_line_suggestion_row() -> None:
+ # The container test must not treat a label-over-secondary row as a multi-row box. The row-size
+ # gate a few lines above it already allows a 2-line row; a container is three or more stacked
+ # text lines, whose text is the union of its rows.
+ value = "Phoenix, Maricopa, Arizona - 85027 United States"
+ async with _live_page(_POSTAL_TWO_LINE_ROW_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#zip", "el => el.getAttribute('data-committed')") == value
+
+
+# A roleless container with only THREE stacked children -- so the child-COUNT gate never fires -- whose
+# aggregate text is the requested value, beside a declared sibling. The declared sibling is what routes
+# the whole pool through the branch where bare units live, and the searched pool keeps containers.
+_POSTAL_BARE_CONTAINER_BESIDE_DECLARED_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ var box = document.createElement('div');
+ // A container click lands on an arbitrary one of its rows.
+ box.addEventListener('click', function () { input.setAttribute('data-record', 'ARBITRARY_ROW'); });
+ // `wrapped` puts the rows one level down, so the container has a single direct child -- a walk
+ // over direct children alone then sees one line and calls the box a row.
+ var host = window.__tv3_wrapped ? document.createElement('div') : box;
+ ['Phoenix,', 'Maricopa,', 'Arizona - 85027'].forEach(function (p) {
+ var line = document.createElement('div');
+ line.style.height = '18px';
+ line.textContent = p;
+ host.appendChild(line);
+ });
+ if (host !== box) box.appendChild(host);
+ list.appendChild(box);
+ var opt = document.createElement('div');
+ opt.setAttribute('role', 'option');
+ opt.style.height = '20px';
+ opt.textContent = 'Rapolla, Potenza, Basilicata - 85027';
+ opt.addEventListener('click', function () { input.setAttribute('data-record', 'RAPOLLA'); });
+ list.appendChild(opt);
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("wrapped", [False, True], ids=["direct-children", "one-wrapper"])
+async def test_select_combobox_never_clicks_a_bare_multi_row_container(wrapped: bool) -> None:
+ # Keeping roleless candidates must not admit CONTAINERS. The searched pool keeps them on purpose
+ # so a fragment-built row survives, so the multi-row test the undeclared branch applies has to be
+ # applied here too -- a box whose aggregate text is the value is not a row, and clicking it lands
+ # on an arbitrary one. Status reads error either way; the click is the channel. The `one-wrapper`
+ # case is the one a direct-children walk misses: the rows sit one level down, so the box itself
+ # has a single child and reads as a single line.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ async with _live_page(
+ _POSTAL_BARE_CONTAINER_BESIDE_DECLARED_HTML, f"window.__tv3_wrapped = {str(wrapped).lower()};"
+ ) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#zip", "value": value, "search": "85027"})
+ record = await page.eval_on_selector("#zip", "el => el.getAttribute('data-record')")
+ assert record is None, f"clicked a multi-row container: {record}"
+ assert r.status == "error", r.content
+
+
+# Two roleless rows wearing the requested label, each a DIFFERENT record, beside one unrelated
+# declared row. Nothing declared matches, so nothing outranks either twin.
+_POSTAL_TWO_BARE_TWINS_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="zip" type="text" autocomplete="off"
+ style="position:absolute;top:20px;left:20px;width:700px;height:24px">
+ <div id="zip-list" style="position:absolute;top:50px;left:20px;width:700px;background:#fff;display:none"></div>
+ <script>
+ var input = document.getElementById('zip');
+ var list = document.getElementById('zip-list');
+ function row(text, record, roled) {
+ var d = document.createElement('div');
+ if (roled) d.setAttribute('role', 'option');
+ d.style.height = '20px';
+ d.textContent = text;
+ d.addEventListener('click', function () {
+ input.value = text; input.setAttribute('data-record', record);
+ list.innerHTML = ''; list.style.display = 'none';
+ });
+ return d;
+ }
+ input.addEventListener('input', function () {
+ list.innerHTML = '';
+ if (!input.value.trim()) { list.style.display = 'none'; return; }
+ list.appendChild(row('Phoenix, Maricopa, Arizona - 85027', 'RECORD_A', false));
+ list.appendChild(row('Phoenix, Maricopa, Arizona - 85027', 'RECORD_B', false));
+ list.appendChild(row('Rapolla, Potenza, Basilicata - 85027', 'RECORD_C', true));
+ list.style.display = 'block';
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
+async def test_select_combobox_refuses_two_bare_rows_wearing_one_label(search: str | None) -> None:
+ # The duplicate collapse reads TEXT agreement and vetoes on declared identity. Bare rows carry
+ # none, so two distinct records under one label would collapse to a single candidate and commit
+ # whichever came first — reported as success. Preferring a declared row must not reach here at
+ # all: with nothing declared matching, the ambiguity IS the answer.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_POSTAL_TWO_BARE_TWINS_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "error", r.content
+ record = await page.eval_on_selector("#zip", "el => el.getAttribute('data-record')")
+ assert record is None, f"committed one of two distinct records under a shared label: {record}"
+
+
+@_skip_no_browser
[email protected]("search", [None, "85027"], ids=["full-value", "searched"])
+async def test_select_combobox_declared_row_outranks_a_bare_twin_with_the_same_label(search: str | None) -> None:
+ # The failure this guards is silent: both units carry the requested label, so whichever is clicked
+ # the tool reports success and the field reads correctly -- only the RECORD behind it differs.
+ # Asserting the status or the committed text would pass either way; the record is the channel.
+ value = "Phoenix, Maricopa, Arizona - 85027"
+ args: dict[str, Any] = {"selector": "#zip", "value": value}
+ if search is not None:
+ args["search"] = search
+ async with _live_page(_POSTAL_TWIN_IDENTITY_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler(args)
+ assert r.status == "ok", r.content
+ record = await page.eval_on_selector("#zip", "el => el.getAttribute('data-record')")
+ assert record == "CORRECT_RECORD", f"committed the bare twin's record, not the declared row's: {record}"
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_select_combobox_refuses_prefix_hit_that_names_two_rows_across_windows() -> None: