Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep a saved dialog handler in force for the whole workflow run on the secure runner (SKY-16343) (#8609)
Andrew Neilsonb992b311dcc3
diff --git a/skyvern/webeye/dialog_handler.py b/skyvern/webeye/dialog_handler.pyindex 89bf2350f..552d5cbce 100644--- a/skyvern/webeye/dialog_handler.py+++ b/skyvern/webeye/dialog_handler.py@@ -4,6 +4,7 @@ import asyncioimport functoolsimport jsonimport weakref+from collections.abc import Iterablefrom dataclasses import dataclassfrom typing import Any@@ -80,12 +81,14 @@ DIALOG_POLICY_HELPER_CONTRACT: dict[str, Any] = {"The declaring call runs before any dialog fires, so records come back on the NEXT call: ""declare, drive the page, then call again to read what fired. An alert is recorded but ""answered by its own branch rather than by the policy. On the secure CodeBlock runner a "- "page.on('dialog', ...) registration is the same call and also consumes the pending "- "records when it is sent, ahead of the block's next page call."+ "page.on('dialog', ...) registration returns no records, and a dialog it answers is not recorded."),"lifetime": (- "The policy covers the whole browser context for the rest of the block -- sibling and popup "- "pages included -- and is revoked at block end, restoring default dialog handling. It answers "+ "The policy covers the whole browser context -- sibling and popup pages included. A "+ "set_dialog_policy call lasts for the rest of the block and is revoked at block end; on the secure "+ "CodeBlock runner a page.on('dialog', ...) registration lasts for the rest of the workflow run, "+ "like the listener it replaces; within a block, whichever of the two was declared later answers. "+ "Once neither is in force, default dialog handling resumes. It answers ""confirm and prompt only: beforeunload is always accepted so that a declared 'dismiss' cannot ""cancel the block's own navigation, and is recorded like any other dialog. Revocation wins a ""tie: a dialog the page schedules as the block ends may be answered by default handling and "@@ -97,6 +100,10 @@ DIALOG_POLICY_HELPER_CONTRACT: dict[str, Any] = {# attribute access, so a weak key taken from one would be dead before the next dialog fired._dialog_policies: weakref.WeakKeyDictionary[BrowserContext, DialogPolicy] = weakref.WeakKeyDictionary()_dialog_records: weakref.WeakKeyDictionary[BrowserContext, list[dict[str, str]]] = weakref.WeakKeyDictionary()+# Run-scoped answers keyed by the declaring run id; the most recent declaration answers. The owner is never+# read from the SkyvernContext at dialog time: Playwright dispatches events with the context of whoever+# started the driver, not the run now on the page, so stale owners are dropped when a run acquires the context.+_run_dialog_policies: weakref.WeakKeyDictionary[BrowserContext, dict[str, DialogPolicy]] = weakref.WeakKeyDictionary()def _policy_key(browser_context: BrowserContext) -> BrowserContext | None:@@ -130,6 +137,44 @@ def clear_dialog_policy(browser_context: BrowserContext) -> None:_dialog_records.pop(key, None)+def set_run_dialog_policy(+ browser_context: BrowserContext, action: str, prompt_text: str | None, workflow_run_id: str+) -> None:+ if action not in DIALOG_POLICY_ACTIONS:+ raise ValueError(f"unsupported dialog policy action: {action!r}")+ # The later declaration wins, so this one replaces a block answer armed earlier in the block.+ _dialog_policies.pop(browser_context, None)+ owners = _run_dialog_policies.setdefault(browser_context, {})+ owners.pop(workflow_run_id, None)+ owners[workflow_run_id] = DialogPolicy(action=action, prompt_text=prompt_text)+++def retain_run_dialog_policies(browser_context: BrowserContext, owner_run_ids: Iterable[str | None]) -> None:+ """Drop run answers on this context declared by any run outside ``owner_run_ids``."""+ key = _policy_key(browser_context)+ owners = _run_dialog_policies.get(key) if key is not None else None+ if not owners:+ return+ keep = set(owner_run_ids)+ for run_id in [run_id for run_id in owners if run_id not in keep]:+ del owners[run_id]+++def clear_run_dialog_policies(workflow_run_ids: Iterable[str]) -> None:+ """Drop these runs' answers from every context, since a context can outlive the run that armed it."""+ run_ids = set(workflow_run_ids)+ for owners in list(_run_dialog_policies.values()):+ for run_id in run_ids:+ owners.pop(run_id, None)+++def clear_context_run_dialog_policies(browser_context: BrowserContext) -> None:+ """Drop every run answer on a context no other live run shares, including a grandchild's the caller cannot name."""+ key = _policy_key(browser_context)+ if key is not None:+ _run_dialog_policies.pop(key, None)++def take_dialog_records(browser_context: BrowserContext) -> list[dict[str, str]]:"""Dialogs OBSERVED since the previous take, as plain data — never a live Dialog. An alert isobserved but not answered by the policy: it has one possible response and takes its own branch."""@@ -166,6 +211,7 @@ async def _handle_dialog(dialog: Dialog, page: Page | None = None) -> None:default_value = dialog.default_valuepolicy: DialogPolicy | None = None+ policy_scope = "block"policy_context = _policy_key(page.context) if page is not None else Noneif policy_context is not None:policy = _dialog_policies.get(policy_context)@@ -176,6 +222,9 @@ async def _handle_dialog(dialog: Dialog, page: Page | None = None) -> None:records = _dialog_records.setdefault(policy_context, [])records.append({"type": dialog_type, "message": recorded_message})del records[:-MAX_DIALOG_POLICY_RECORDS]+ elif run_policies := _run_dialog_policies.get(policy_context):+ policy = next(reversed(run_policies.values()))+ policy_scope = "run"ctx = skyvern_context.current()organization_id = ctx.organization_id if ctx else None@@ -232,7 +281,7 @@ async def _handle_dialog(dialog: Dialog, page: Page | None = None) -> None:await _respond("accept")returnif policy is not None:- log.info("Dialog answered by declared policy", policy_action=policy.action)+ log.info("Dialog answered by declared policy", policy_action=policy.action, policy_scope=policy_scope)await _respond(policy.action, policy.prompt_text)returndiff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.pyindex ebb4993ef..113b577d6 100644--- a/skyvern/webeye/real_browser_manager.py+++ b/skyvern/webeye/real_browser_manager.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport functoolsimport os-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Iterablefrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, replacefrom datetime import UTC, datetime@@ -48,6 +48,11 @@ from skyvern.webeye.cdp_frame_publisher import (stream_key_for_task,stream_key_for_workflow_run,)+from skyvern.webeye.dialog_handler import (+ clear_context_run_dialog_policies,+ clear_run_dialog_policies,+ retain_run_dialog_policies,+)from skyvern.webeye.display_recorder import (DisplayRecorder,stop_display_recorders_for_owner,@@ -236,12 +241,35 @@ async def _rebind_pbs_download_dir()+def _retain_run_dialog_answers(+ browser_state: BrowserState,+ workflow_run_id: str | None,+ parent_workflow_run_id: str | None = None,+ live_run_ids: Iterable[str] = (),+) -> None:+ if browser_state.browser_context is None:+ return+ context = skyvern_context.current()+ retain_run_dialog_policies(+ browser_state.browser_context,+ (+ workflow_run_id,+ parent_workflow_run_id,+ context.root_workflow_run_id if context else None,+ *live_run_ids,+ ),+ )++async def _on_browser_state_acquired(browser_state: BrowserState,workflow_run_id: str | None,+ parent_workflow_run_id: str | None = None,+ live_run_ids: Iterable[str] = (),) -> BrowserState:browser_context = browser_state.browser_contextif browser_context is not None:+ _retain_run_dialog_answers(browser_state, workflow_run_id, parent_workflow_run_id, live_run_ids)await app.AGENT_FUNCTION.on_browser_context_acquired(browser_context, workflow_run_id)return browser_state@@ -815,7 +843,9 @@ class RealBrowserManager(BrowserManager):self.pages.pop(stale_key, None)browser_state = Noneelse:- return await _on_browser_state_acquired(browser_state, task.workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state, task.workflow_run_id, live_run_ids=self._live_run_ids_sharing(browser_state)+ )if browser_session_id:if not task.organization_id:@@ -877,6 +907,9 @@ class RealBrowserManager(BrowserManager):LOG.info("User to occupy browser session here", browser_session_id=browser_session_id)else:LOG.warning("Organization ID is not set for task", task_id=task.task_id)+ _retain_run_dialog_answers(+ browser_state, task.workflow_run_id, live_run_ids=self._live_run_ids_sharing(browser_state)+ )await _rebind_pbs_download_dir(browser_state, download_run_id, browser_session_id)self._store_session_lease(expected_runnable_id,@@ -953,7 +986,9 @@ class RealBrowserManager(BrowserManager):task_id=task.task_id,organization_id=task.organization_id,)- return await _on_browser_state_acquired(browser_state, task.workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state, task.workflow_run_id, live_run_ids=self._live_run_ids_sharing(browser_state)+ )async def get_or_create_for_workflow_run(self,@@ -986,7 +1021,9 @@ class RealBrowserManager(BrowserManager):browser_state = Noneelse:LOG.debug("Returning cached browser state for workflow run", workflow_run_id=workflow_run_id)- return await _on_browser_state_acquired(browser_state, workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state, workflow_run_id, parent_workflow_run_id, self._live_run_ids_sharing(browser_state)+ )# When an explicit browser_session_id is provided (e.g. from a workflow# trigger block), skip the parent workflow lookup so the child uses the@@ -1040,7 +1077,12 @@ class RealBrowserManager(BrowserManager):workflow_run_id=workflow_run_id,organization_id=workflow_run.organization_id,)- return await _on_browser_state_acquired(browser_state, workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state,+ workflow_run_id,+ parent_workflow_run_id,+ self._live_run_ids_sharing(browser_state),+ )# The inherited state is genuinely torn down (disconnected and page-less).# Drop the stale entry and fall through to create a fresh browser for this run.LOG.warning(@@ -1096,6 +1138,12 @@ class RealBrowserManager(BrowserManager):)if browser_state is not None:LOG.info("Used to occupy browser session here", browser_session_id=browser_session_id)+ _retain_run_dialog_answers(+ browser_state,+ workflow_run_id,+ parent_workflow_run_id,+ self._live_run_ids_sharing(browser_state),+ )# An SDK-minted synthetic run only reads a session owned by another runnable.# It cannot rebind that runnable's download directory or acquire a cleanup lease.if expected_runnable_id is not None:@@ -1162,6 +1210,12 @@ class RealBrowserManager(BrowserManager):)if browser_state is None:raise+ _retain_run_dialog_answers(+ browser_state,+ workflow_run_id,+ parent_workflow_run_id,+ self._live_run_ids_sharing(browser_state),+ )if expected_runnable_id is not None:self._store_session_lease(workflow_run.workflow_run_id,@@ -1260,7 +1314,9 @@ class RealBrowserManager(BrowserManager):workflow_run_id=workflow_run.workflow_run_id,organization_id=workflow_run.organization_id,)- return await _on_browser_state_acquired(browser_state, workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state, workflow_run_id, parent_workflow_run_id, self._live_run_ids_sharing(browser_state)+ )def get_for_workflow_run(self, workflow_run_id: str, parent_workflow_run_id: str | None = None@@ -1518,6 +1574,18 @@ class RealBrowserManager(BrowserManager):return browser_state_to_close+ def _live_run_ids_sharing(self, browser_state: BrowserState) -> set[str]:+ """Workflow runs live in this process that hold this exact state: an acquiring run's whole+ ancestor chain when nested runs share a browser, rather than only the parent and root it can+ name, and a live sibling on the same browser too."""+ return {+ page_id+ for page_id, state in self.pages.items()+ if page_id.startswith(_WORKFLOW_RUN_KEY_PREFIX)+ and state is browser_state+ and app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context(page_id)+ }+def _shared_with_another_workflow_run(self, workflow_run_id: str, browser_state_to_close: BrowserState) -> bool:# NON-PBS ONLY. Python-object sharing of an ephemeral BrowserState is process-local, so an# alias may veto the terminal close only when it denotes ANOTHER workflow run that is@@ -1554,6 +1622,7 @@ class RealBrowserManager(BrowserManager):# observed below, or sees CLOSING. The tombstone also holds the session lease immediately,# before deferred-close parameters exist, until complete_stream_teardown releases it.mark_stream_closing(workflow_run_id)+ clear_run_dialog_policies((workflow_run_id, *(child_workflow_run_ids or ())))browser_state_to_close = self.pages.get(workflow_run_id)session_lease = self._persistent_session_leases.get(workflow_run_id)recording_finalized = False@@ -1596,6 +1665,8 @@ class RealBrowserManager(BrowserManager):sampling=True,workflow_run_id=workflow_run_id,)+ elif browser_state_to_close.browser_context:+ clear_context_run_dialog_policies(browser_state_to_close.browser_context)# Stop tracing before closing the browser if tracing is enabled.# Skip when the browser is shared — Playwright supports only one active@@ -1789,7 +1860,9 @@ class RealBrowserManager(BrowserManager):workflow_run_id = context.workflow_run_id if context else Nonebrowser_state = self.get_for_script(script_id=script_id)if browser_state:- return await _on_browser_state_acquired(browser_state, workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state, workflow_run_id, live_run_ids=self._live_run_ids_sharing(browser_state)+ )if browser_session_id:# Fail closed: look the session up under its real organization_id (release's symmetric key).@@ -1871,7 +1944,9 @@ class RealBrowserManager(BrowserManager):browser_session_id=browser_session_id,)- return await _on_browser_state_acquired(browser_state, workflow_run_id)+ return await _on_browser_state_acquired(+ browser_state, workflow_run_id, live_run_ids=self._live_run_ids_sharing(browser_state)+ )async def cleanup_for_script(self,diff --git a/tests/unit/test_dialog_handler_records_to_context.py b/tests/unit/test_dialog_handler_records_to_context.pyindex 023fedd11..9b4c818e1 100644--- a/tests/unit/test_dialog_handler_records_to_context.py+++ b/tests/unit/test_dialog_handler_records_to_context.py@@ -413,6 +413,63 @@ class TestDeclaredDialogPolicy:with pytest.raises(ValueError):dialog_handler.set_dialog_policy(MagicMock(), "ignore")+ @pytest.mark.parametrize("run_declared_first", [True, False], ids=["run-then-block", "block-then-run"])+ @pytest.mark.asyncio+ async def test_the_later_declaration_answers_during_the_block_and_the_run_answer_outlives_it(+ self,+ isolated_context: SkyvernContext,+ armed_page: MagicMock,+ monkeypatch: pytest.MonkeyPatch,+ run_declared_first: bool,+ ) -> None:+ isolated_context.navigation_goal = "goal"+ monkeypatch.setattr(+ dialog_handler.app, "SECONDARY_LLM_API_HANDLER", AsyncMock(side_effect=AssertionError("LLM consulted"))+ )+ run_id = "wr_test"+ if run_declared_first:+ dialog_handler.set_run_dialog_policy(armed_page.context, "accept", "from the run", run_id)+ try:+ dialog_handler.set_dialog_policy(armed_page.context, "dismiss")+ if not run_declared_first:+ dialog_handler.set_run_dialog_policy(armed_page.context, "accept", "from the run", run_id)+ during_block = _make_dialog("prompt", "Delete?")+ await dialog_handler._handle_dialog(during_block, page=armed_page)+ dialog_handler.clear_dialog_policy(armed_page.context)+ after_block = _make_dialog("prompt", "Name?")+ await dialog_handler._handle_dialog(after_block, page=armed_page)+ finally:+ dialog_handler.clear_run_dialog_policies([run_id])++ if run_declared_first:+ during_block.dismiss.assert_awaited_once_with()+ during_block.accept.assert_not_awaited()+ else:+ during_block.accept.assert_awaited_once_with("from the run")+ during_block.dismiss.assert_not_awaited()+ after_block.accept.assert_awaited_once_with("from the run")+ assert dialog_handler.take_dialog_records(armed_page.context) == []++ @pytest.mark.asyncio+ async def test_clearing_a_child_run_answer_restores_the_parent_then_default_handling(+ self, isolated_context: SkyvernContext, armed_page: MagicMock+ ) -> None:+ dialog_handler.set_run_dialog_policy(armed_page.context, "accept", "parent", "wr_parent_answer")+ dialog_handler.set_run_dialog_policy(armed_page.context, "dismiss", None, "wr_child_answer")+ answers = [_make_dialog("prompt", "Name?", default_value="default") for _ in range(3)]+ try:+ await dialog_handler._handle_dialog(answers[0], page=armed_page)+ dialog_handler.clear_run_dialog_policies(["wr_child_answer"])+ await dialog_handler._handle_dialog(answers[1], page=armed_page)+ dialog_handler.clear_run_dialog_policies(["wr_parent_answer"])+ await dialog_handler._handle_dialog(answers[2], page=armed_page)+ finally:+ dialog_handler.clear_run_dialog_policies(["wr_parent_answer", "wr_child_answer"])++ answers[0].dismiss.assert_awaited_once_with()+ answers[1].accept.assert_awaited_once_with("parent")+ answers[2].accept.assert_awaited_once_with("default")+class _DriverError(Exception):"""Stands in for the deployed driver's error type, which is deliberately NOT thediff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.pyindex 9d8068836..d6e8c09d3 100644--- a/tests/unit/test_real_browser_manager.py+++ b/tests/unit/test_real_browser_manager.py@@ -20,7 +20,7 @@ from skyvern.forge.sdk.artifact.storage.recording_test_helpers import fake_prepafrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.streaming import registries-from skyvern.webeye import real_browser_manager+from skyvern.webeye import dialog_handler, real_browser_managerfrom skyvern.webeye.browser_artifacts import (BrowserArtifacts,DownloadBinding,@@ -3007,3 +3007,155 @@ async def test_workflow_sweep_cancel_still_sweeps_siblings_releases_session_and_assert sorted(swept) == ["tsk_owned", "wr_run"] # sibling still swept despite the first owner's mid-sweep cancelrelease.assert_awaited_once() # session release ran onceteardown.assert_called_once_with("wr_run") # stream teardown completed once++[email protected]("run_state_present", [True, False], ids=["run-browser-deferred", "task-browser-only"])+async def test_workflow_run_cleanup_clears_run_dialog_answers_even_when_the_browser_survives(+ monkeypatch: pytest.MonkeyPatch, run_state_present: bool+) -> None:+ manager = RealBrowserManager()+ browser_state = MagicMock()+ browser_state.browser_artifacts.traces_dir = None+ browser_state.browser_artifacts.browser_session_dir = "/tmp/fake_profile"+ browser_state.close = AsyncMock()+ if run_state_present:+ manager.pages["wr_dialog_run"] = browser_state+ manager.pages["tsk_dialog_run"] = browser_state+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.persist_session_cookies", AsyncMock())+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.stream_ref_active", lambda wrid: True)+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.set_deferred_close_params", MagicMock(return_value=True))+ context = MagicMock()+ for run_id in ("wr_dialog_run", "wr_dialog_child", "wr_dialog_other"):+ dialog_handler.set_run_dialog_policy(context, "accept", None, run_id)++ try:+ await manager.cleanup_for_workflow_run(+ "wr_dialog_run",+ task_ids=["tsk_dialog_run"],+ close_browser_on_completion=False,+ child_workflow_run_ids=["wr_dialog_child"],+ )+ remaining = list(dialog_handler._run_dialog_policies[context])+ finally:+ dialog_handler.clear_run_dialog_policies(["wr_dialog_other"])++ browser_state.close.assert_not_awaited()+ assert remaining == ["wr_dialog_other"]++[email protected]("shared", [False, True], ids=["unshared", "shared-with-another-run"])+async def test_workflow_run_cleanup_drops_unnamed_run_answers_only_from_an_unshared_context(+ monkeypatch: pytest.MonkeyPatch, shared: bool+) -> None:+ manager = RealBrowserManager()+ context = MagicMock()+ browser_state = MagicMock()+ browser_state.browser_context = context+ browser_state.browser_artifacts.traces_dir = None+ browser_state.close = AsyncMock()+ manager.pages["wr_dialog_top"] = browser_state+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.stream_ref_active", lambda wrid: False)+ monkeypatch.setattr(manager, "_shared_with_another_workflow_run", lambda *_args: shared)+ dialog_handler.set_run_dialog_policy(context, "accept", None, "wr_dialog_grandchild")++ try:+ await manager.cleanup_for_workflow_run("wr_dialog_top", task_ids=[], close_browser_on_completion=False)+ remaining = list(dialog_handler._run_dialog_policies.get(context, {}))+ finally:+ dialog_handler.clear_run_dialog_policies(["wr_dialog_grandchild"])++ assert remaining == (["wr_dialog_grandchild"] if shared else [])+++async def test_a_run_occupying_a_persistent_session_drops_a_previous_runs_dialog_answer() -> None:+ manager = RealBrowserManager()+ context = MagicMock()+ pbs_state = MagicMock()+ pbs_state.browser_context = context+ pbs_state.get_working_page = AsyncMock(return_value=MagicMock())+ pbs_state.get_or_create_page = AsyncMock()+ answers_at_navigation: list[list[str]] = []+ pbs_state.navigate_to_url = AsyncMock(+ side_effect=lambda **_kwargs: answers_at_navigation.append(+ list(dialog_handler._run_dialog_policies.get(context, {}))+ )+ )+ dialog_handler.set_run_dialog_policy(context, "dismiss", None, "wr_dialog_previous")++ try:+ with patch("skyvern.webeye.real_browser_manager.app") as mock_app:+ configure_browser_context_acquired_hook(mock_app)+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=pbs_state)+ mock_app.PERSISTENT_SESSIONS_MANAGER.set_browser_state = AsyncMock()+ await manager.get_or_create_for_workflow_run(+ workflow_run=make_workflow_run("wr_dialog_next"),+ url="https://example.com",+ browser_session_id="bs_dialog",+ )+ remaining = list(dialog_handler._run_dialog_policies.get(context, {}))+ finally:+ dialog_handler.clear_run_dialog_policies(["wr_dialog_previous"])++ assert answers_at_navigation == [[]]+ assert remaining == []+++async def test_a_child_run_inheriting_its_parents_browser_keeps_the_parents_dialog_answer() -> None:+ manager = RealBrowserManager()+ context = MagicMock()+ parent_state = MagicMock()+ parent_state.browser_context = context+ parent_state.get_working_page = AsyncMock(return_value=MagicMock())+ manager.pages["wr_dialog_parent"] = parent_state+ dialog_handler.set_run_dialog_policy(context, "dismiss", None, "wr_dialog_unrelated")+ dialog_handler.set_run_dialog_policy(context, "accept", None, "wr_dialog_parent")++ try:+ with patch("skyvern.webeye.real_browser_manager.app") as mock_app:+ configure_browser_context_acquired_hook(mock_app)+ with patch.object(manager, "_start_frame_publisher", AsyncMock()):+ result = await manager.get_or_create_for_workflow_run(+ workflow_run=make_workflow_run("wr_dialog_child", parent_workflow_run_id="wr_dialog_parent"),+ url="https://example.com",+ )+ remaining = list(dialog_handler._run_dialog_policies.get(context, {}))+ finally:+ dialog_handler.clear_run_dialog_policies(["wr_dialog_parent", "wr_dialog_unrelated"])++ assert result is parent_state+ assert remaining == ["wr_dialog_parent"]+++async def test_a_nested_run_keeps_every_live_ancestors_dialog_answer() -> None:+ """Runs A -> B -> C -> D on one browser: D's acquisition must not drop B, which it cannot name."""+ manager = RealBrowserManager()+ context = MagicMock()+ shared_state = MagicMock()+ shared_state.browser_context = context+ shared_state.get_working_page = AsyncMock(return_value=MagicMock())+ live = {"wr_dialog_a", "wr_dialog_b", "wr_dialog_c"}+ # wr_dialog_gone finished but left its page entry behind, so liveness decides, not the entry.+ for run_id in (*live, "wr_dialog_gone"):+ manager.pages[run_id] = shared_state+ for run_id in ("wr_dialog_b", "wr_dialog_gone"):+ dialog_handler.set_run_dialog_policy(context, "accept", None, run_id)++ try:+ with patch("skyvern.webeye.real_browser_manager.app") as mock_app:+ configure_browser_context_acquired_hook(mock_app)+ mock_app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context = lambda run_id: run_id in live+ with patch.object(manager, "_start_frame_publisher", AsyncMock()):+ await manager.get_or_create_for_workflow_run(+ workflow_run=make_workflow_run("wr_dialog_d", parent_workflow_run_id="wr_dialog_c"),+ url="https://example.com",+ )+ remaining = list(dialog_handler._run_dialog_policies.get(context, {}))+ finally:+ dialog_handler.clear_run_dialog_policies(["wr_dialog_b", "wr_dialog_gone"])++ assert remaining == ["wr_dialog_b"]