Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Treat a terminating worker tail as committed and let lone replicas migrate (#8366)
LawyZheng0a0dbc9d7e80
diff --git a/skyvern/browser_extension/extension/debugger_router.js b/skyvern/browser_extension/extension/debugger_router.jsindex 6c80d040a..0ed9383ec 100644--- a/skyvern/browser_extension/extension/debugger_router.js+++ b/skyvern/browser_extension/extension/debugger_router.js@@ -18,6 +18,11 @@ const LEAF_TARGET_TYPES = new Set(["shared_worker","worker",]);+const URL_CHANGING_CDP_METHODS = new Set([+ "Page.navigate",+ "Page.navigateToHistoryEntry",+ "Page.reload",+]);function debuggerErrorReason(error) {const reason = error instanceof Error ? error.message.trim() : "";@@ -309,6 +314,19 @@ export class DebuggerRouter {"CDP parameters must be an object.",);}+ let urlChangeGranted = false;+ if (URL_CHANGING_CDP_METHODS.has(values.method)) {+ // Page.navigate binds the grant to its target URL; history/reload+ // navigations have no knowable target, so their grant matches any+ // single URL change.+ lease.allowUrlChange(+ values.method === "Page.navigate" &&+ typeof values.params?.url === "string"+ ? values.params.url+ : null,+ );+ urlChangeGranted = true;+ }const childTarget = this.childTargets.get(values.sessionId);if (values.method === "Target.setAutoAttach" &&@@ -347,6 +365,9 @@ export class DebuggerRouter {commandTimeoutMs,));} catch (error) {+ if (urlChangeGranted) {+ lease.revokeUrlChange();+ }if (error instanceof ProtocolError &&error.code === ERROR_CODES.COMMAND_TIMEOUTdiff --git a/skyvern/browser_extension/extension/tab_scope.js b/skyvern/browser_extension/extension/tab_scope.jsindex abef542cf..6ea42a8a6 100644--- a/skyvern/browser_extension/extension/tab_scope.js+++ b/skyvern/browser_extension/extension/tab_scope.js@@ -37,6 +37,18 @@ function isScopeRevocation(error) {);}+// Unparseable URLs fail closed: the change cancels the operation.+function urlChangeMatchesExpected(expectedUrl, url) {+ if (expectedUrl === null || expectedUrl === url) {+ return true;+ }+ try {+ return new URL(expectedUrl).href === new URL(url).href;+ } catch {+ return false;+ }+}+export class TabScope {constructor({ sendEvent, operationTimeoutMs = TAB_OPERATION_TIMEOUT_MS }) {this.sendEvent = sendEvent;@@ -206,9 +218,11 @@ export class TabScope {return this.quarantinedTabIds.has(tabId);}- cancelTabOperations(tabId, error) {+ cancelTabOperations(tabId, error, shouldCancel = null) {for (const lease of this.tabOperationLeases.get(tabId) ?? []) {- lease.cancel(error);+ if (shouldCancel === null || shouldCancel(lease)) {+ lease.cancel(error);+ }}}trackTabOperationLease(tabId, lease) {@@ -240,8 +254,10 @@ export class TabScope {? "Chrome does not allow controlling this URL.": "The page changed while the extension operation was running.",),+ restricted+ ? null+ : (lease) => !lease.consumeUrlChangeGrant(changeInfo.url),);- return;}if (Object.hasOwn(changeInfo, "groupId") &&@@ -1081,6 +1097,7 @@ export class TabScope {let rejectInvalidated;let cancelled = false;let cancellationError = null;+ let pendingUrlChangeGrant = null;const invalidated = new Promise((_, reject) => {rejectInvalidated = reject;});@@ -1089,6 +1106,21 @@ export class TabScope {invalidated,isCurrent: () => !cancelled && generation === this.operationGeneration,remainingMs: () => Math.max(0, deadlineMs - Date.now()),+ // One grant per commanded navigation: consumed by the first URL-change+ // decision, revoked when the command fails, never carried past either.+ allowUrlChange: (expectedUrl = null) => {+ pendingUrlChangeGrant = { expectedUrl };+ },+ revokeUrlChange: () => {+ pendingUrlChangeGrant = null;+ },+ consumeUrlChangeGrant: (url) => {+ const grant = pendingUrlChangeGrant;+ pendingUrlChangeGrant = null;+ return (+ grant !== null && urlChangeMatchesExpected(grant.expectedUrl, url)+ );+ },assertCurrent: () => {if (cancelled || generation !== this.operationGeneration) {throw (diff --git a/tests/smoke_tests/browser_extension/run_extension_smoke.py b/tests/smoke_tests/browser_extension/run_extension_smoke.pyindex 2eef4b04d..2bab1490c 100644--- a/tests/smoke_tests/browser_extension/run_extension_smoke.py+++ b/tests/smoke_tests/browser_extension/run_extension_smoke.py@@ -29,6 +29,7 @@ EXPECTED_EXTENSION_ID = EXTENSION_IDTOKEN_ENV = "SKYVERN_BROWSER_EXTENSION_TOKEN"PORT_ENV = "SKYVERN_BROWSER_EXTENSION_PORT"BROKER_ENV = "SKYVERN_BROWSER_EXTENSION_BROKER"+CHROME_FOR_TESTING_PATH_ENV = "CHROME_FOR_TESTING_PATH"SMOKE_TEXT = "Skyvern extension bridge smoke"CHECKS = ("setup",@@ -325,6 +326,17 @@ async def _wait_for_popup_connection(popup_page: Page, timeout_seconds: float =raise TimeoutError(f"extension did not reconnect to MCP relay; popup error: {error or 'none'}")+async def _wait_for_popup_disconnection(popup_page: Page, timeout_seconds: float = 15.0) -> None:+ loop = asyncio.get_running_loop()+ deadline = loop.time() + timeout_seconds+ while loop.time() < deadline:+ status = (await popup_page.locator("#status-label").text_content() or "").strip()+ if status not in {"Connected", "Client attached"}:+ return+ await asyncio.sleep(0.1)+ raise TimeoutError("extension popup did not observe relay shutdown")++async def _wait_for_fixture_page(context: BrowserContext, fixture_url: str, timeout_seconds: float = 15.0) -> Page:loop = asyncio.get_running_loop()deadline = loop.time() + timeout_seconds@@ -596,9 +608,15 @@ async def run_smoke(*, legacy_mode: bool) -> int:playwright = await async_playwright().start()profile_dir = tempfile.TemporaryDirectory(prefix="skyvern-extension-smoke-profile-")extension_path = str(extension_dir)+ chrome_path_value = os.environ.get(CHROME_FOR_TESTING_PATH_ENV)+ if not chrome_path_value:+ raise RuntimeError(f"{CHROME_FOR_TESTING_PATH_ENV} must point to Chrome for Testing 138 or later")+ chrome_path = Path(chrome_path_value).expanduser().resolve()+ if not chrome_path.is_file() or not os.access(chrome_path, os.X_OK):+ raise RuntimeError(f"{CHROME_FOR_TESTING_PATH_ENV} is not an executable file: {chrome_path}")persistent_context = await playwright.chromium.launch_persistent_context(profile_dir.name,- channel="chromium",+ executable_path=str(chrome_path),headless=False,args=[f"--disable-extensions-except={extension_path}",@@ -652,11 +670,13 @@ async def run_smoke(*, legacy_mode: bool) -> int:report.pass_check("chrome survives disconnect")await runtime.shutdown()+ await _wait_for_popup_disconnection(popup_page)runtime = None+ mcp_fixture_url = f"{fixture_servers.outer_url}?phase=mcp"await _run_mcp_phase(persistent_context,popup_page,- fixture_servers.outer_url,+ mcp_fixture_url,relay_port,pairing_token,legacy_mode,diff --git a/tests/unit/browser_extension/test_extension_bridge_hardening.py b/tests/unit/browser_extension/test_extension_bridge_hardening.pyindex e2750b062..23dc68938 100644--- a/tests/unit/browser_extension/test_extension_bridge_hardening.py+++ b/tests/unit/browser_extension/test_extension_bridge_hardening.py@@ -114,9 +114,16 @@ bridge.kick = async () => {{ alarmKicks += 1; }};alarmListeners.forEach((listener) => listener({{ name: BRIDGE_ALARM_NAME }}));await waitUntil(() => alarmKicks === 1);+const allowedUrlChanges = [];+let revokedUrlChangeCount = 0;const tabScope = {{async runTabOperation(_tabId, operation) {{- return operation({{ isCurrent: () => true, assertCurrent() {{}} }});+ return operation({{+ isCurrent: () => true,+ assertCurrent() {{}},+ allowUrlChange(expectedUrl = null) {{ allowedUrlChanges.push(expectedUrl); }},+ revokeUrlChange() {{ revokedUrlChangeCount += 1; }},+ }});}},async assertControllableLocked() {{}},async assertScoped() {{}},@@ -194,6 +201,35 @@ const healthy = await router.send({{ tabId: 22, method: "Runtime.evaluate", paraif (healthy.result.method !== "Runtime.evaluate") {{throw new Error("healthy tab command was blocked by a wedged tab");}}+for (const [method, params] of [+ ["Page.navigate", {{ url: "https://example.test/next" }}],+ ["Page.navigateToHistoryEntry", {{ entryId: 1 }}],+ ["Page.reload", {{}}],+]) {{+ const navigation = await router.send({{ tabId: 22, method, params }});+ if (navigation.result.method !== method) {{+ throw new Error(`${{method}} did not complete`);+ }}+}}+if (JSON.stringify(allowedUrlChanges) !== JSON.stringify(["https://example.test/next", null, null])) {{+ throw new Error(`URL-changing CDP methods granted the wrong URL bindings: ${{JSON.stringify(allowedUrlChanges)}}`);+}}+if (revokedUrlChangeCount !== 0) {{+ throw new Error("successful navigations must not revoke their URL-change grants");+}}+chrome.debugger.sendCommand = () => Promise.reject(new Error("navigation rejected"));+let failedNavigationError;+try {{+ await router.send({{ tabId: 22, method: "Page.navigate", params: {{ url: "https://example.test/failed" }} }});+}} catch (error) {{+ failedNavigationError = error;+}}+if (failedNavigationError?.code !== ERROR_CODES.CDP_ERROR) {{+ throw new Error(`failed navigation was not structured: ${{failedNavigationError?.code}}`);+}}+if (revokedUrlChangeCount !== 1) {{+ throw new Error("failed navigation did not revoke its URL-change grant");+}}"""result = subprocess.run(@@ -476,6 +512,167 @@ tabs.delete(18);tabs.delete(19);+// A navigation command may cause its own URL event without cancelling itself.+tabs.set(23, {{ id: 23, windowId: 2, groupId: 700, url: "https://before.example" }});+scope.scopedTabIds.add(23);+scope.scopedGroupIds.set(23, 700);+let expectedNavigationStarted = false;+let releaseExpectedNavigation;+const expectedNavigation = scope.runTabOperation(23, async (lease) => {{+ lease.allowUrlChange("https://after.example");+ expectedNavigationStarted = true;+ await new Promise((resolve) => {{ releaseExpectedNavigation = resolve; }});+ lease.assertCurrent();+ return "navigated";+}});+await waitUntil(() => expectedNavigationStarted);+tabs.get(23).url = "https://after.example";+listeners.updated.forEach((listener) =>+ listener(23, {{ url: "https://after.example" }}),+);+releaseExpectedNavigation();+if ((await settleWithin(expectedNavigation)) !== "navigated") {{+ throw new Error("expected navigation URL change cancelled its own operation");+}}+await waitUntil(() => !scope.tabOperations.has(23));+scope.scopedTabIds.delete(23);+scope.scopedGroupIds.delete(23);+tabs.delete(23);++// An unrelated operation must still fail when the page URL changes.+tabs.set(24, {{ id: 24, windowId: 2, groupId: 700, url: "https://before.example" }});+scope.scopedTabIds.add(24);+scope.scopedGroupIds.set(24, 700);+let unrelatedOperationStarted = false;+const unrelatedOperation = scope.runTabOperation(24, async () => {{+ unrelatedOperationStarted = true;+ return new Promise(() => undefined);+}}).then(() => null, (error) => error);+await waitUntil(() => unrelatedOperationStarted);+tabs.get(24).url = "https://after.example";+listeners.updated.forEach((listener) =>+ listener(24, {{ url: "https://after.example" }}),+);+const unrelatedOperationError = await settleWithin(unrelatedOperation);+if (unrelatedOperationError?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{+ throw new Error(`unrelated URL change did not cancel active work: ${{unrelatedOperationError?.code}}`);+}}+await waitUntil(() => !scope.tabOperations.has(24));+scope.scopedTabIds.delete(24);+scope.scopedGroupIds.delete(24);+tabs.delete(24);++// Restricted URLs cancel even an operation that expects a navigation event.+tabs.set(25, {{ id: 25, windowId: 2, groupId: 700, url: "https://before.example" }});+scope.scopedTabIds.add(25);+scope.scopedGroupIds.set(25, 700);+let restrictedNavigationStarted = false;+const restrictedNavigation = scope.runTabOperation(25, async (lease) => {{+ lease.allowUrlChange();+ restrictedNavigationStarted = true;+ return new Promise(() => undefined);+}}).then(() => null, (error) => error);+await waitUntil(() => restrictedNavigationStarted);+tabs.get(25).url = "chrome://settings";+listeners.updated.forEach((listener) =>+ listener(25, {{ url: "chrome://settings" }}),+);+const restrictedNavigationError = await settleWithin(restrictedNavigation);+if (restrictedNavigationError?.code !== ERROR_CODES.RESTRICTED_URL) {{+ throw new Error(`restricted navigation did not cancel active work: ${{restrictedNavigationError?.code}}`);+}}+await waitUntil(() => !scope.scopedTabIds.has(25));+tabs.delete(25);++// A coalesced URL and group event must prioritize group revocation.+tabs.set(26, {{ id: 26, windowId: 2, groupId: 700, url: "https://before.example" }});+scope.scopedTabIds.add(26);+scope.scopedGroupIds.set(26, 700);+let coalescedNavigationStarted = false;+const coalescedNavigation = scope.runTabOperation(26, async (lease) => {{+ lease.allowUrlChange();+ coalescedNavigationStarted = true;+ return new Promise(() => undefined);+}}).then(() => null, (error) => error);+await waitUntil(() => coalescedNavigationStarted);+tabs.get(26).url = "https://after.example";+tabs.get(26).groupId = -1;+listeners.updated.forEach((listener) =>+ listener(26, {{ url: "https://after.example", groupId: -1 }}),+);+const coalescedNavigationError = await settleWithin(coalescedNavigation);+if (coalescedNavigationError?.code !== ERROR_CODES.TAB_NOT_SCOPED) {{+ throw new Error(`coalesced group revocation did not cancel active work: ${{coalescedNavigationError?.code}}`);+}}+await waitUntil(() => !scope.scopedTabIds.has(26));+tabs.delete(26);+++// A URL-change grant is consumed by one URL event; a replay must cancel, not survive.+tabs.set(27, {{ id: 27, windowId: 2, groupId: 700, url: "https://before.example" }});+scope.scopedTabIds.add(27);+scope.scopedGroupIds.set(27, 700);+let consumedNavigationStarted = false;+let releaseConsumedNavigation;+const consumedNavigation = scope.runTabOperation(27, async (lease) => {{+ lease.allowUrlChange("https://after.example");+ consumedNavigationStarted = true;+ await new Promise((resolve) => {{ releaseConsumedNavigation = resolve; }});+ lease.assertCurrent();+ return "survived";+}}).then((value) => value, (error) => error);+await waitUntil(() => consumedNavigationStarted);+tabs.get(27).url = "https://after.example";+listeners.updated.forEach((listener) =>+ listener(27, {{ url: "https://after.example" }}),+);+listeners.updated.forEach((listener) =>+ listener(27, {{ url: "https://after.example" }}),+);+releaseConsumedNavigation();+const consumedNavigationOutcome = await settleWithin(consumedNavigation);+if (consumedNavigationOutcome === "survived") {{+ throw new Error("URL-change grant survived a second URL event instead of being consumed");+}}+if (consumedNavigationOutcome?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{+ throw new Error(`consumed grant replay was not structured: ${{consumedNavigationOutcome?.code}}`);+}}+await waitUntil(() => !scope.tabOperations.has(27));+scope.scopedTabIds.delete(27);+scope.scopedGroupIds.delete(27);+tabs.delete(27);++// A grant bound to one URL must not spare a navigation to a different URL.+tabs.set(28, {{ id: 28, windowId: 2, groupId: 700, url: "https://before.example" }});+scope.scopedTabIds.add(28);+scope.scopedGroupIds.set(28, 700);+let mismatchedNavigationStarted = false;+let releaseMismatchedNavigation;+const mismatchedNavigation = scope.runTabOperation(28, async (lease) => {{+ lease.allowUrlChange("https://intended.example");+ mismatchedNavigationStarted = true;+ await new Promise((resolve) => {{ releaseMismatchedNavigation = resolve; }});+ lease.assertCurrent();+ return "survived";+}}).then((value) => value, (error) => error);+await waitUntil(() => mismatchedNavigationStarted);+tabs.get(28).url = "https://user.example";+listeners.updated.forEach((listener) =>+ listener(28, {{ url: "https://user.example" }}),+);+releaseMismatchedNavigation();+const mismatchedNavigationOutcome = await settleWithin(mismatchedNavigation);+if (mismatchedNavigationOutcome === "survived") {{+ throw new Error("URL-change grant spared a navigation it was not bound to");+}}+if (mismatchedNavigationOutcome?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{+ throw new Error(`mismatched URL change was not structured: ${{mismatchedNavigationOutcome?.code}}`);+}}+await waitUntil(() => !scope.tabOperations.has(28));+scope.scopedTabIds.delete(28);+scope.scopedGroupIds.delete(28);+tabs.delete(28);+// Closing a just-created tab must cancel its create operation after Chrome returns the tab id.const originalAddToScopeLocked = scope.addToScopeLocked.bind(scope);let addToScopeStarted = false;