Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Release the copilot turn's cached browser driver when the turn exits (SKY-16220) (#8541)
Andrew Neilson9870858fed8e
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 88ed288b0..139cf35e9 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1176,6 +1176,7 @@ class AgentFunction:block_label: str | None,browser_session_id: str | None,code: str | None = None,+ authored_code: str | None = None,) -> bool:"""Whether a workflow CodeBlock run should execute in the secure runner.diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 43ab97547..6c6dc9613 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -196,10 +196,14 @@ from skyvern.forge.sdk.copilot.run_outcome import (select_run_outcome_anchor,)from skyvern.forge.sdk.copilot.runtime import (+ AgentContext,BrowserProbeOutcome,_browser_context_attachability,close_browser_session_quietly,+ record_attached_browser_driver,resolve_persistent_browser_state,+ start_browser_driver_release,+ wait_for_driver_releases,)from skyvern.forge.sdk.copilot.runtime_authoring_repair import (OBSTRUCTION_SUMMARY_MAX_CHARS,@@ -372,7 +376,9 @@ def _manager_can_probe_registered_browser_state() -> bool:return app.PERSISTENT_SESSIONS_MANAGER.can_probe_registered_browser_state()-async def _registered_browser_state_liveness(session_id: str, organization_id: str) -> BrowserProbeOutcome | None:+async def _registered_browser_state_liveness(+ session_id: str, organization_id: str, ctx: AgentContext+) -> BrowserProbeOutcome | None:"""None means this manager cannot answer at all, which is a capability, not a liveness verdict."""if not _manager_can_probe_registered_browser_state():return None@@ -383,12 +389,16 @@ async def _registered_browser_state_liveness(session_id: str, organization_id: s)if state is None:return BrowserProbeOutcome.positively_unreachable+ # This probe attaches through the same cache as every other lookup, so the turn owns the driver+ # it left behind whether or not the turn goes on to use the session.+ record_attached_browser_driver(ctx, session_id, state)return _browser_context_attachability(state.browser_context)async def _resolve_live_browser_session_id(chat_request: WorkflowCopilotChatRequest,organization_id: str,+ ctx: AgentContext,) -> str | None:"""Ownership failures fail closed. A liveness lookup that could not complete keeps the session,since failing to reach the browser is not evidence about the browser."""@@ -435,7 +445,7 @@ async def _resolve_live_browser_session_id(has_live_browser = bool(persistent and persistent.is_browser_ready and persistent.cdp_unreachable_at is None)registered_liveness: BrowserProbeOutcome | None = Noneif persistent is not None and not is_final_status(persistent.status) and not has_live_browser:- registered_liveness = await _registered_browser_state_liveness(requested, organization_id)+ registered_liveness = await _registered_browser_state_liveness(requested, organization_id, ctx)if registered_liveness == BrowserProbeOutcome.could_not_determine:LOG.warning("Copilot browser session health signal unavailable; keeping the supplied session",@@ -4981,6 +4991,18 @@ async def run_copilot_agent(finally:turn_end_ctx = ctx_sink[0] if ctx_sink else Nonefinalize_outcome_verification_trace(turn_end_ctx, turn_span)+ if turn_end_ctx is not None and turn_end_ctx.attached_browser_drivers:+ # Concurrently, so one session's wedged detach can neither skip the sessions+ # behind it nor stack another cleanup timeout onto the turn's exit.+ releases = [+ start_browser_driver_release(+ organization_id,+ attached,+ unwinding_operations=turn_end_ctx.admitted_browser_operations.get(attached.session_id),+ )+ for attached in list(turn_end_ctx.attached_browser_drivers.values())+ ]+ await wait_for_driver_releases(releases)except asyncio.CancelledError:if eval_mode == CopilotEvalMode.BROWSER_ABLATION and ctx_sink:browser_session_id = ctx_sink[0].browser_session_id@@ -5135,6 +5157,10 @@ async def _run_copilot_turn_impl(label: set(fingerprints) for label, fingerprints in (prior_executed_block_fingerprints or {}).items()},)+ # Reading the origin run below can attach a browser driver; the finalizer only releases what it+ # can see on the sunk context, so expose it before any await that might attach.+ if ctx_sink is not None:+ ctx_sink.append(ctx)if chat_request.product_action == "diagnose_run":await restore_pending_workflow_proposal(ctx,@@ -5190,8 +5216,6 @@ async def _run_copilot_turn_impl(raise RuntimeError(f"CopilotContext.turn_id ({ctx.turn_id!r}) diverged from route-supplied turn_id ({turn_id!r})")- if ctx_sink is not None:- ctx_sink.append(ctx)policy_inputs = RequestPolicyGuardrailInputs(user_message=chat_request.message,workflow_yaml=safe_workflow_yaml,@@ -5342,7 +5366,7 @@ async def _run_copilot_turn_impl(get_skyvern_mcp_alias_map,)- validated_browser_session_id = await _resolve_live_browser_session_id(chat_request, organization_id)+ validated_browser_session_id = await _resolve_live_browser_session_id(chat_request, organization_id, ctx)ctx.browser_session_id = validated_browser_session_iddirect_test_handoff = Nonediff --git a/skyvern/forge/sdk/copilot/code_block_security.py b/skyvern/forge/sdk/copilot/code_block_security.pyindex 77dc31939..7a8b6eeeb 100644--- a/skyvern/forge/sdk/copilot/code_block_security.py+++ b/skyvern/forge/sdk/copilot/code_block_security.py@@ -1,12 +1,6 @@"""Deterministic AST denylist over Copilot-synthesized code blocks, enforced at authoring and at runtime pre-dispatch.--`page.request` and `page.context` remain denied at both seams because they reach the live browser session's HTTP-client and its BrowserContext (cookies, `storage_state`, new pages, route interception), so prompt-injected-synthesized code could exfiltrate session credentials out of band. Retaining them does not mitigate exfiltration-through `page.evaluate`, which can read page-visible data and egress it directly from in-page JS; this module is a-guardrail on one code path, not a sandbox, and Copilot code still executes in-process with credentials resolved-before the run until out-of-process isolation lands.-"""+Denies `page.request`, `page.context` and the dynamic attribute/namespace builtins that reach the live session's+credentials; a guardrail on one code path, not a sandbox, and it does not cover exfiltration through `page.evaluate`."""from __future__ import annotations@@ -24,6 +18,9 @@ _RUNTIME_ATTR_REASONS = {"request": "RUNTIME_PAGE_REQUEST","context": "RUNTIME_PAGE_CONTEXT",}+_DYNAMIC_ATTRIBUTE_BUILTINS = frozenset({"getattr", "setattr", "delattr", "vars", "globals", "locals"})+_AUTHOR_DYNAMIC_ATTRIBUTE_REASON = "AUTHOR_DYNAMIC_ATTRIBUTE"+_RUNTIME_DYNAMIC_ATTRIBUTE_REASON = "RUNTIME_DYNAMIC_ATTRIBUTE"@dataclass(frozen=True)@@ -58,7 +55,7 @@ def author_time_code_security_errors(*, label: str, code: str) -> list[CodeBlocktree = ast.parse(code)except SyntaxError:return [_error(label, "AUTHOR_SYNTAX_ERROR")]- return _security_errors_for_tree(label, tree, _AUTHOR_ATTR_REASONS)+ return _security_errors_for_tree(label, tree, _AUTHOR_ATTR_REASONS, _AUTHOR_DYNAMIC_ATTRIBUTE_REASON)def runtime_code_security_errors(@@ -76,18 +73,96 @@ def runtime_code_security_errors(except SyntaxError:errors.append(_error(block.label, "RUNTIME_SYNTAX_ERROR"))continue- errors.extend(_security_errors_for_tree(block.label, tree, _RUNTIME_ATTR_REASONS))+ errors.extend(+ _security_errors_for_tree(block.label, tree, _RUNTIME_ATTR_REASONS, _RUNTIME_DYNAMIC_ATTRIBUTE_REASON)+ )return errors-def _security_errors_for_tree(label: str, tree: ast.AST, attr_reasons: dict[str, str]) -> list[CodeBlockSecurityError]:+INERT_SLOT_NAME = "__skyvern_slot__"+_PARAMETER_CODE_REASON = "RUNTIME_PARAMETER_CODE"+++def rendering_introduced_security_errors(+ *, label: str, authored_code: str | None, rendered_code: str+) -> list[CodeBlockSecurityError]:+ """Refuse a render whose parameter values contributed anything but literals. `authored_code` is the same template+ rendered under the same control flow with every value slot replaced by `INERT_SLOT_NAME`; None fails closed.+ Byte equality of the two renders is never a pass: a value equal to the marker produces identical text."""+ try:+ rendered_tree = ast.parse(rendered_code)+ except SyntaxError:+ return []+ if authored_code is None:+ return [_error(label, _PARAMETER_CODE_REASON)]+ try:+ authored_tree = ast.parse(authored_code)+ except SyntaxError:+ return [_error(label, _PARAMETER_CODE_REASON)]+ if _slots_hold_only_literals(authored_tree, rendered_tree):+ return []+ return [_error(label, _PARAMETER_CODE_REASON)]+++def _slots_hold_only_literals(authored: ast.AST, rendered: ast.AST) -> bool:+ if isinstance(authored, ast.Name) and authored.id == INERT_SLOT_NAME:+ return _is_literal(rendered)+ if isinstance(authored, ast.Constant) and isinstance(authored.value, str) and INERT_SLOT_NAME in authored.value:+ return isinstance(rendered, ast.Constant) and isinstance(rendered.value, str)+ if type(authored) is not type(rendered):+ return False+ for field, authored_value in ast.iter_fields(authored):+ rendered_value = getattr(rendered, field, None)+ if isinstance(authored_value, ast.AST):+ if not isinstance(rendered_value, ast.AST) or not _slots_hold_only_literals(authored_value, rendered_value):+ return False+ elif isinstance(authored_value, list):+ if not isinstance(rendered_value, list) or len(authored_value) != len(rendered_value):+ return False+ for authored_item, rendered_item in zip(authored_value, rendered_value, strict=True):+ if isinstance(authored_item, ast.AST):+ if not isinstance(rendered_item, ast.AST) or not _slots_hold_only_literals(+ authored_item, rendered_item+ ):+ return False+ elif authored_item != rendered_item:+ return False+ elif authored_value != rendered_value:+ return False+ return True+++def _is_literal(node: ast.AST) -> bool:+ if isinstance(node, ast.Constant):+ return True+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):+ return all(_is_literal(element) for element in node.elts)+ if isinstance(node, ast.Dict):+ return all(key is not None and _is_literal(key) for key in node.keys) and all(+ _is_literal(value) for value in node.values+ )+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):+ return _is_literal(node.operand)+ return False+++def _security_errors_for_tree(+ label: str, tree: ast.AST, attr_reasons: dict[str, str], dynamic_attribute_reason: str+) -> list[CodeBlockSecurityError]:errors: list[CodeBlockSecurityError] = []seen: set[str] = set()for node in ast.walk(tree):- # This AST layer catches direct attribute access. The sandbox's private-attribute- # and builtins restrictions remain the backstop for dynamic forms.+ reasons: list[str] = []if isinstance(node, ast.Attribute) and node.attr in attr_reasons:- reason = attr_reasons[node.attr]+ reasons.append(attr_reasons[node.attr])+ # A class pattern reads `page.context` through getattr with no ast.Attribute node.+ elif isinstance(node, ast.MatchClass):+ reasons.extend(attr_reasons[attr] for attr in node.kwd_attrs if attr in attr_reasons)+ # The sandbox's getattr/vars wrappers strip only private names and globals() exposes the+ # builtins dict, so a string-built public name would reach the denied members.+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id in _DYNAMIC_ATTRIBUTE_BUILTINS:+ reasons.append(dynamic_attribute_reason)+ for reason in reasons:if reason not in seen:errors.append(_error(label, reason))seen.add(reason)@@ -111,10 +186,19 @@ def _surface_for_reason(reason_code: str) -> str:return "page.context"if reason_code.endswith("PAGE_EVALUATE"):return "page.evaluate"+ if reason_code.endswith("DYNAMIC_ATTRIBUTE"):+ return f"dynamic attribute access ({'/'.join(sorted(_DYNAMIC_ATTRIBUTE_BUILTINS))})"+ if reason_code == _PARAMETER_CODE_REASON:+ return "code from a parameter value"return "python_ast"def _message_for_reason(*, label: str, reason_code: str, surface: str) -> str:+ if reason_code == _PARAMETER_CODE_REASON:+ return (+ f"Code block `{label}` was blocked before browser dispatch: a parameter value contributes code; "+ "only a literal value (string, number, boolean, null, or JSON list/object) may be rendered into code."+ )if reason_code == "AUTHOR_SYNTAX_ERROR":return f"Code block `{label}` failed the Copilot code security check: the code does not parse as Python."if reason_code.startswith("AUTHOR_"):diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 71aa849ce..a5e32378f 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport asyncioimport time-from collections.abc import AsyncIterator, Callable, Iterator, Mapping+from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mappingfrom contextlib import asynccontextmanager, contextmanagerfrom contextvars import ContextVarfrom copy import deepcopy@@ -125,6 +125,16 @@ _BROWSER_BOOT_POLL_INTERVAL_SECONDS = 0.25# a vendor replacement was measured booting in 13.5s, so this leaves room to have one ready._FIXED_DEADLINE_REPLACEMENT_MARGIN_SECONDS = 60.0_ABANDONED_BROWSER_STATE_RESOLVES: set[asyncio.Task[BrowserState | None]] = set()+_ABANDONED_DRIVER_RELEASES: set[asyncio.Task[bool] | asyncio.Task[None]] = set()+# Per session: attached turns in this process, and the newest generation any of them attached.+# Only the last one out releases, and it retires that newest generation rather than its own.+_ATTACHED_TURNS_PER_SESSION: dict[str, tuple[int, BrowserState]] = {}+# Set while a last-out release has popped its ledger entry but the evict has not finished; an attach+# in that window would record the generation the evict is about to retire.+_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] = {}# 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@@ -368,6 +378,12 @@ class ScoutedInteraction(TypedDict):element_fingerprint_probed: NotRequired[str]+@dataclass(frozen=True)+class AttachedBrowserDriver:+ session_id: str+ browser_state: BrowserState++@dataclassclass AgentContext:organization_id: str@@ -383,6 +399,12 @@ class AgentContext:work_plan: list[str] | None = Noneturn_origin: TurnOrigin = TurnOrigin.interactiveinjected_browser_state: BrowserState | None = None+ # Keyed by session id, so a later rebind of ``browser_session_id`` cannot aim the turn-exit+ # release at a session this turn never attached. ``dataclasses.replace`` shares this dict.+ attached_browser_drivers: dict[str, AttachedBrowserDriver] = field(default_factory=dict)+ # Tool tasks this turn has inside an admitted browser operation. A cancelled turn reaches its+ # finalizer before those tasks finish unwinding, and the manager refuses to retire a busy generation.+ admitted_browser_operations: dict[str, set[asyncio.Task[object]]] = field(default_factory=dict)heal_workflow_run_id: str | None = None# The deadline the current model stream runs under, published by the enforcement loop so a tool# that parks on a user decision can suspend it instead of being cancelled mid-question.@@ -967,7 +989,7 @@ async def resolve_browser_state_for_context(return Noneif ctx.turn_origin == TurnOrigin.runtime_self_heal or is_self_heal_session_id(resolved_session_id):try:- _resolved_session_id, browser_state, _ = await _resolve_self_heal_browser_state(ctx)+ _resolved_session_id, injected_state, _ = await _resolve_self_heal_browser_state(ctx)if _resolved_session_id != resolved_session_id:LOG.info("Resolved self-heal browser session id differs from requested",@@ -975,13 +997,18 @@ async def resolve_browser_state_for_context(resolved_session_id=_resolved_session_id,organization_id=ctx.organization_id,)- return browser_state+ return injected_stateexcept HealAdoptionFailed:return None- return await resolve_persistent_browser_state(+ browser_state = await resolve_persistent_browser_state(session_id=resolved_session_id,organization_id=ctx.organization_id,)+ if browser_state is not None:+ # Only this branch's state lives in the pod's cache; the self-heal branch above returns the+ # healer's injected state, which the turn-exit release would look for and never find.+ record_attached_browser_driver(ctx, resolved_session_id, browser_state)+ return browser_statedef _abandonable_browser_state_resolve(session_id: str, organization_id: str) -> asyncio.Task[BrowserState | None]:@@ -1021,7 +1048,62 @@ async def resolve_persistent_browser_state(Every caller still issues its OWN lookup. A determination that is merely stuck must never beinherited by a later attach, which is the oracle and has to be free to answer on its own."""- return await asyncio.shield(_abandonable_browser_state_resolve(session_id, organization_id))+ while True:+ release_in_flight = _DRIVER_RELEASES_IN_FLIGHT.get(session_id)+ if release_in_flight is not None:+ await release_in_flight.wait()+ epoch_before_lookup = _DRIVER_RELEASE_EPOCHS.get(session_id, 0)+ resolve = _abandonable_browser_state_resolve(session_id, organization_id)+ try:+ browser_state = await asyncio.shield(resolve)+ except asyncio.CancelledError:+ _release_driver_attached_after_abandonment(resolve, session_id, organization_id)+ raise+ # 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+) -> 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."""++ def _release(finished: asyncio.Task[BrowserState | None]) -> None:+ if finished.cancelled() or finished.exception() is not None:+ return+ browser_state = finished.result()+ if browser_state is None:+ return+ _hold_attached_browser_driver(session_id, browser_state, new_holder=True)+ start_browser_driver_release(organization_id, AttachedBrowserDriver(session_id, browser_state))++ resolve.add_done_callback(_release)+++def start_browser_driver_release(+ organization_id: str,+ attached: AttachedBrowserDriver,+ *,+ unwinding_operations: set[asyncio.Task[object]] | None = None,+) -> asyncio.Task[None]:+ """The release runs as its own task so a cancel landing on the caller's await cannot stop it+ before it hands back the attach count; a stuck count skips every later release on that session."""+ release = asyncio.ensure_future(+ release_browser_driver_quietly(organization_id, attached, unwinding_operations=unwinding_operations)+ )+ _ABANDONED_DRIVER_RELEASES.add(release)+ release.add_done_callback(_discard_finished_driver_release)+ return release+++async def wait_for_driver_releases(releases: Iterable[asyncio.Task[None]]) -> None:+ """Bounded here, not in the release: a slow unwind delays the detach, never the turn's exit."""+ pending = [release for release in releases if not release.done()]+ if pending:+ await asyncio.wait(pending, timeout=_SESSION_CLEANUP_TIMEOUT_SECONDS)async def close_browser_session_quietly(@@ -1041,6 +1123,100 @@ async def close_browser_session_quietly(LOG.debug("Failed to close browser session", session_id=session_id, exc_info=True)+def _discard_finished_driver_release(task: asyncio.Task[bool] | asyncio.Task[None]) -> None:+ _ABANDONED_DRIVER_RELEASES.discard(task)+ if not task.cancelled():+ task.exception()+++def _hold_attached_browser_driver(session_id: str, browser_state: BrowserState, *, new_holder: bool) -> None:+ turns, _ = _ATTACHED_TURNS_PER_SESSION.get(session_id, (0, browser_state))+ _ATTACHED_TURNS_PER_SESSION[session_id] = (turns + 1 if new_holder else turns, browser_state)+++def record_attached_browser_driver(ctx: AgentContext, session_id: str, browser_state: BrowserState) -> None:+ _hold_attached_browser_driver(session_id, browser_state, new_holder=session_id not in ctx.attached_browser_drivers)+ ctx.attached_browser_drivers[session_id] = AttachedBrowserDriver(session_id, browser_state)+++async def release_browser_driver_quietly(+ organization_id: str,+ attached: AttachedBrowserDriver,+ *,+ unwinding_operations: set[asyncio.Task[object]] | None = None,+) -> None:+ """Detach the driver this turn attached, leaving the persistent session itself running. The+ evict is shielded because it pops the cache entry before awaiting the detach, so a cancelled+ wait would strand the popped driver."""+ # The manager refuses to retire a generation with an admitted operation, and this turn's own+ # tool task can still be unwinding one; a refusal taken as done would leave the driver cached.+ # Unbounded on purpose: an operation that never ends is still using the driver, and this task+ # runs off the turn, whose exit is bounded by its caller.+ pending = {task for task in unwinding_operations or () if task is not asyncio.current_task() and not task.done()}+ if pending:+ await asyncio.wait(pending)+ turns, latest_browser_state = _ATTACHED_TURNS_PER_SESSION.get(attached.session_id, (1, attached.browser_state))+ still_attached = turns - 1+ if still_attached > 0:+ _ATTACHED_TURNS_PER_SESSION[attached.session_id] = (still_attached, latest_browser_state)+ LOG.info(+ "copilot_browser_driver_released",+ session_id=attached.session_id,+ had_cached_driver=False,+ concurrent_turns_still_attached=still_attached,+ )+ return+ _ATTACHED_TURNS_PER_SESSION.pop(attached.session_id, None)+ manager = app.PERSISTENT_SESSIONS_MANAGER+ if not manager.supports_evict_and_reconnect():+ # This process drives the browser itself; detaching its driver would strand the browser+ # and leave the session uncacheable for the rest of its life.+ return+ evict: asyncio.Task[bool] | None = None+ try:+ evict = asyncio.ensure_future(+ manager.evict_cached_browser_state(+ attached.session_id,+ organization_id,+ expected=latest_browser_state,+ detach_remote_driver=True,+ only_if_unleased=True,+ )+ )+ _ABANDONED_DRIVER_RELEASES.add(evict)+ evict.add_done_callback(_discard_finished_driver_release)+ # The marker must outlive this wait: a resolve admitted after a timed-out wait but before+ # the evict pops the entry would still be handed the generation being retired.+ _DRIVER_RELEASE_EPOCHS[attached.session_id] = _DRIVER_RELEASE_EPOCHS.get(attached.session_id, 0) + 1+ releasing = asyncio.Event()+ _DRIVER_RELEASES_IN_FLIGHT[attached.session_id] = releasing++ def _release_marker(_task: asyncio.Task[bool]) -> None:+ if _DRIVER_RELEASES_IN_FLIGHT.get(attached.session_id) is releasing:+ del _DRIVER_RELEASES_IN_FLIGHT[attached.session_id]+ releasing.set()++ evict.add_done_callback(_release_marker)+ had_cached_driver = await asyncio.wait_for(asyncio.shield(evict), timeout=_SESSION_CLEANUP_TIMEOUT_SECONDS)+ except (asyncio.CancelledError, Exception) as exc:+ LOG.warning(+ "Failed to release browser driver",+ session_id=attached.session_id,+ error_type=type(exc).__name__,+ error=str(exc)[:200],+ )+ # A cancel the evict did not raise itself is this turn being cancelled mid-cleanup, and+ # swallowing it would report a task that finished when the caller asked it to stop.+ if isinstance(exc, asyncio.CancelledError) and (evict is None or not evict.cancelled()):+ raise+ return+ LOG.info(+ "copilot_browser_driver_released",+ session_id=attached.session_id,+ had_cached_driver=had_cached_driver,+ )++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 alreadyreplaced it — nulling a live replacement would discard the session this exists to protect."""@@ -1251,6 +1427,7 @@ async def mcp_browser_context(ctx: AgentContext, *, session_id_override: str | Nraise CopilotBrowserGenerationRetired(browser_session_id, operation.reason)if operation_task is None:raise RuntimeError("A Copilot browser context requires an asyncio task")+ ctx.admitted_browser_operations.setdefault(browser_session_id, set()).add(operation_task)scope_token = _ACTIVE_MCP_BROWSER_CONTEXT.set(_ActiveMcpBrowserContext(task=operation_task,@@ -1274,6 +1451,7 @@ async def mcp_browser_context(ctx: AgentContext, *, session_id_override: str | N_raise_if_browser_generation_retired(operation_task, operation.retirement, browser_session_id)finally:_ACTIVE_MCP_BROWSER_CONTEXT.reset(scope_token)+ ctx.admitted_browser_operations.get(browser_session_id, set()).discard(operation_task)async def _attach_current_browser_generation(ctx: AgentContext) -> None:@@ -1438,6 +1616,7 @@ async def _provision_browser_session(ctx: AgentContext) -> BuildTestConnectFailuorganization_id=ctx.organization_id,)if state and _browser_context_is_attachable(state.browser_context):+ record_attached_browser_driver(ctx, ctx.browser_session_id, state)breakawait asyncio.sleep(_BROWSER_BOOT_POLL_INTERVAL_SECONDS)diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex dac17d6dc..87f68eddc 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -153,6 +153,7 @@ from skyvern.forge.sdk.copilot.runtime import (RegisteredArtifactEvidence,browser_page_custody_lock,ensure_build_test_browser_session,+ record_attached_browser_driver,record_sensitive_origin_run_taint,register_sensitive_origin_run_lease,release_sensitive_origin_run_lease,@@ -2132,6 +2133,7 @@ async def _observe_authored_locators(return "run_browser_unavailable"if browser_state is None:return "run_browser_unavailable"+ record_attached_browser_driver(ctx, run_session_id, browser_state)# Creating one would count every authored selector against a blank page, so a run whose# page has since closed would report as a dead locator rather than an unobserved one.try:@@ -2880,6 +2882,7 @@ async def _attach_post_run_browser_enrichment(organization_id=ctx.organization_id,)if browser_state:+ record_attached_browser_driver(ctx, run_session_id, browser_state)page = await browser_state.get_or_create_page()if SettingsManager.get_settings().BROWSER_CURSOR_VISUALIZATION:try:diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex a70c8a397..0f89ae7a4 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -143,6 +143,7 @@ from skyvern.forge.sdk.api.llm.exceptions import (from skyvern.forge.sdk.api.llm.schema_validator import validate_schemafrom skyvern.forge.sdk.artifact.models import ArtifactTypefrom skyvern.forge.sdk.copilot.block_goal_wrapping import compose_mini_goal+from skyvern.forge.sdk.copilot.code_block_security import INERT_SLOT_NAMEfrom skyvern.forge.sdk.copilot.reached_download_target import (REGISTERED_DOWNLOAD_OUTPUT_KEYS,block_output_has_registered_download,@@ -5706,6 +5707,33 @@ async def wrapper({default_args}):for_generated_code=True,)+ def render_code_with_reference(self, workflow_run_context: WorkflowRunContext) -> str | None:+ """Render `code` in place and return its inert-slot reference, rendered from a snapshot of the template+ inputs taken before the real render so a stateful `{% set %}` is not evaluated twice against live data."""+ persisted_code = self.code+ try:+ reference_context: WorkflowRunContext | None = _template_context_snapshot(workflow_run_context)+ except Exception:+ reference_context = None+ self.format_potential_template_parameters(workflow_run_context)+ if reference_context is None:+ return None+ return self.render_code_with_inert_slots(persisted_code, reference_context)++ def render_code_with_inert_slots(self, source: str, workflow_run_context: WorkflowRunContext) -> str | None:+ """The author's code under this run's template control flow, every value slot replaced by an inert name; None+ when the slotted template still emits a value or fails to render, which the caller treats as untrusted."""+ masked_code, masked_comments = mask_jinja_in_python_comments(source)+ slotted = _JINJA_VALUE_SLOT_RE.sub(rf'{{{{\1 "{INERT_SLOT_NAME}" \2}}}}', masked_code)+ slotted = _JINJA_PRINT_SLOT_RE.sub(rf'{{%\1 print "{INERT_SLOT_NAME}" \2%}}', slotted)+ try:+ if not _template_emits_only_inert_slots(slotted):+ return None+ rendered = self.render_templatable_field("code", slotted, workflow_run_context)+ except Exception:+ return None+ return restore_jinja_masked_comments(rendered, masked_comments)+async def _claim_session_download_artifacts(self,*,@@ -7877,7 +7905,7 @@ async def wrapper({default_args}):)try:- self.format_potential_template_parameters(workflow_run_context)+ authored_code = self.render_code_with_reference(workflow_run_context)except Exception as e:return await self._template_format_failure_result(e,@@ -7996,6 +8024,7 @@ async def wrapper({default_args}):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(@@ -15796,6 +15825,49 @@ def _align_branch_evaluations(# Pattern to find Jinja template blocks like {{ variable_name }}_JINJA_BLOCK_RE = re.compile(r"\{\{(.*?)\}\}")+# Value slots only; the delimiters and their whitespace-control markers stay so both renders trim identically.+_JINJA_VALUE_SLOT_RE = re.compile(r"\{\{(-?).*?(-?)\}\}", re.DOTALL)+_JINJA_PRINT_SLOT_RE = re.compile(r"\{%(-?)\s*print\b.*?(-?)%\}", re.DOTALL)+++def _template_context_snapshot(workflow_run_context: WorkflowRunContext) -> WorkflowRunContext:+ """A context whose list/dict inputs are copies, so a reference render cannot mutate what the real render+ already consumed (the sandboxed environment lets a `{% set %}` call `pop()` or `update()`)."""+ snapshot = copy.copy(workflow_run_context)+ snapshot.values = _isolated_containers(workflow_run_context.values)+ snapshot.workflow_run_outputs = _isolated_containers(workflow_run_context.workflow_run_outputs)+ return snapshot+++def _isolated_containers(value: Any) -> Any:+ if isinstance(value, dict):+ return {key: _isolated_containers(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_isolated_containers(item) for item in value]+ return value+++def _template_emits_only_inert_slots(template_source: str) -> bool:+ """Jinja's own parse is the authority on what a value can shape: every emitted expression must be the inert+ constant, and a filter block may transform authored text only with constant arguments."""+ template = jinja_json_finalize_strict_env.parse(template_source)+ for output in template.find_all(nodes.Output):+ for child in output.nodes:+ if isinstance(child, nodes.TemplateData):+ continue+ if not (isinstance(child, nodes.Const) and child.value == INERT_SLOT_NAME):+ return False+ for filter_block in template.find_all(nodes.FilterBlock):+ for applied in (filter_block.filter, *filter_block.filter.find_all(nodes.Filter)):+ if applied.dyn_args is not None or applied.dyn_kwargs is not None:+ return False+ if not all(isinstance(argument, nodes.Const) for argument in applied.args):+ return False+ if not all(isinstance(keyword.value, nodes.Const) for keyword in applied.kwargs):+ return False+ return True++# Marker inserted into rendered expressions when a Jinja variable resolved to# an empty/whitespace-only value. The LLM uses this to reason about emptiness._EMPTY_VALUE_MARKER = "(empty value)"diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.pyindex eb1e104a4..2f8d21fc3 100644--- a/skyvern/webeye/default_persistent_sessions_manager.py+++ b/skyvern/webeye/default_persistent_sessions_manager.py@@ -564,19 +564,22 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):expected: BrowserState | None = None,*,detach_remote_driver: bool = False,- ) -> None:+ only_if_unleased: bool = False,+ ) -> bool:cached = self._browser_sessions.get(session_id)if cached is None:- return+ return Falseif expected is not None and cached.browser_state is not expected:- return+ return False+ if only_if_unleased and cached.active_browser_operations:+ return Falsecached = self._retire_browser_session(session_id,expected=cached,reason=BrowserRetirementReason.session_ending,)if cached is None:- return+ return Falsetry:if detach_remote_driver:await cached.browser_state.detach_remote_driver()@@ -593,6 +596,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):session_id=session_id,exc_info=True,)+ return Trueasync def get_session(self, session_id: str, organization_id: str) -> PersistentBrowserSession | None:"""Get a specific browser session by session ID."""diff --git a/skyvern/webeye/persistent_sessions_manager.py b/skyvern/webeye/persistent_sessions_manager.pyindex 3417cfde1..f72e6eff9 100644--- a/skyvern/webeye/persistent_sessions_manager.py+++ b/skyvern/webeye/persistent_sessions_manager.py@@ -284,8 +284,10 @@ class PersistentSessionsManager(Protocol):expected: BrowserState | None = None,*,detach_remote_driver: bool = False,- ) -> None:- """Drop any in-process cache entry so the next lookup reconnects.+ only_if_unleased: bool = False,+ ) -> bool:+ """Drop any in-process cache entry so the next lookup reconnects, reporting whether a+ live entry was actually evicted.When ``expected`` is provided the eviction is race-safe: callers can pass thestale BrowserState they just navigated against, and the manager skips eviction@@ -296,6 +298,8 @@ class PersistentSessionsManager(Protocol):``detach_remote_driver`` is for a known local CDP-client loss while the remotepersistent browser remains healthy. It stops only the adopted Playwright driverinstead of closing the remote context that another proxy client may still use.+ ``only_if_unleased`` refuses the eviction while an admitted operation or a run on this+ process still leases the cached generation, since retiring it would cut that work off."""...diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex 777fec40b..4bec5abce 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -148,6 +148,21 @@ def reset_collapse_xp_assignment_memo():_clear()[email protected](autouse=True)+def reset_copilot_driver_ledgers() -> Iterator[None]:+ # A holder count leaked by one test makes a later test's turn-exit release silently skip its evict.+ def _clear() -> None:+ runtime = sys.modules.get("skyvern.forge.sdk.copilot.runtime")+ if runtime is not None:+ runtime._ATTACHED_TURNS_PER_SESSION.clear()+ runtime._DRIVER_RELEASES_IN_FLIGHT.clear()+ runtime._DRIVER_RELEASE_EPOCHS.clear()++ _clear()+ yield+ _clear()++@pytest.fixture(autouse=True)def restore_interpreter_traceback_hooks() -> Iterator[None]:"""setup_logger() replaces the three interpreter hooks process-wide.diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.pyindex e633162ec..e27c5ee2b 100644--- a/tests/unit/copilot_test_helpers.py+++ b/tests/unit/copilot_test_helpers.py@@ -3,9 +3,12 @@from __future__ import annotationsimport asyncio+import jsonfrom collections.abc import Awaitable, Callable+from contextlib import suppressfrom dataclasses import replacefrom datetime import UTC, datetime, timedelta, timezone+from itertools import countfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -14,9 +17,13 @@ import pytestfrom skyvern.forge import app as forge_appfrom skyvern.forge.sdk.artifact.models import ArtifactType+from skyvern.forge.sdk.copilot import agent as copilot_agent+from skyvern.forge.sdk.copilot import runtime as copilot_runtimefrom skyvern.forge.sdk.copilot.active_run_session import ActiveRunSessionAssociation+from skyvern.forge.sdk.copilot.agent import run_copilot_agent+from skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalModefrom skyvern.forge.sdk.copilot.build_test_outcome import RecordedBuildTestOutcome-from skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContextfrom skyvern.forge.sdk.copilot.diagnosis_repair_contract import (DiagnosisInput,DiagnosisRepairContract,@@ -25,11 +32,15 @@ from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (RepairNextAction,VerificationResult,)+from skyvern.forge.sdk.copilot.enforcement import CopilotTotalTimeoutError, _mark_copilot_total_timeout+from skyvern.forge.sdk.copilot.repair_origin_run import RepairOriginBindingfrom skyvern.forge.sdk.copilot.request_policy import CompletionCriterionfrom skyvern.forge.sdk.copilot.runtime import record_sensitive_origin_run_taint, register_sensitive_origin_run_leasefrom skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module+from skyvern.forge.sdk.copilot.turn_origin import TurnOriginfrom skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml as process_workflow_yamlfrom skyvern.forge.sdk.schemas.organizations import Organization+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequestfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlockfrom skyvern.forge.sdk.workflow.models.parameter import OutputParameter, WorkflowParameterfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus@@ -701,3 +712,225 @@ def remove_sensitive_disclosure_prerequisite(ctx: Any, arm: str) -> None:record_sensitive_origin_run_taint(ctx, workflow_run_id="wr_earlier", session_id=ctx.browser_session_id)else:raise AssertionError(f"unknown arm {arm}")+++TURN_EXIT_PATHS = ("normal", "model_error", "deadline", "cancel")+++async def run_turn_to_exit(+ monkeypatch: pytest.MonkeyPatch,+ *,+ manager: MagicMock,+ exit_path: str,+ session_id: str | None = "pbs_turn",+ browser_state: MagicMock | None = None,+ resolve_session_id: str | None = None,+ eval_mode: CopilotEvalMode | None = None,+ turn_origin: TurnOrigin = TurnOrigin.interactive,+ attach_through: str = "resolve",+ on_attached: Callable[[CopilotContext], Awaitable[None]] | None = None,+ get_browser_state: AsyncMock | None = None,+) -> tuple[AgentResult | None, BaseException | None]:+ """Drive one real ``run_copilot_agent`` turn to ``exit_path`` against ``manager``, attaching+ through the real resolve funnel so the finalizer releases only what that funnel recorded."""+ manager.get_browser_state = get_browser_state or AsyncMock(return_value=browser_state)+ if turn_origin == TurnOrigin.runtime_self_heal and browser_state is not None:+ browser_state.get_working_page = AsyncMock(return_value=MagicMock())++ async def _exit(ctx: CopilotContext) -> None:+ if on_attached is not None:+ await on_attached(ctx)+ if exit_path == "model_error":+ raise RuntimeError("model stream failed")+ if exit_path == "deadline":+ _mark_copilot_total_timeout(ctx, elapsed_seconds=901.0, iteration=1)+ raise CopilotTotalTimeoutError()+ if exit_path == "cancel":+ raise asyncio.CancelledError()++ async def fake_turn(**kwargs: Any) -> SimpleNamespace:+ ctx = kwargs["ctx"]+ ctx.browser_session_id = session_id+ ctx.turn_origin = turn_origin+ ctx.injected_browser_state = browser_state+ ctx.heal_workflow_run_id = "wr_heal"+ if attach_through == "liveness_probe":+ assert session_id is not None+ await copilot_agent._registered_browser_state_liveness(session_id, ctx.organization_id, ctx)+ elif attach_through == "resolve":+ await copilot_runtime.resolve_browser_state_for_context(ctx, session_id=resolve_session_id)+ await _exit(ctx)+ return SimpleNamespace(final_output=json.dumps({"type": "REPLY", "user_response": "ok"}), new_items=[])++ stub_copilot_agent_loop(monkeypatch, fake_turn)+ workflow_run_id: str | None = None+ if attach_through == "prior_run_hydration":+ assert session_id is not None+ workflow_run_id = "wr_origin"+ origin = RepairOriginBinding(+ workflow_run_id=workflow_run_id,+ browser_session_id=session_id,+ refusal=None,+ status=WorkflowRunStatus.failed,+ )+ monkeypatch.setattr(copilot_agent, "seed_repair_origin_run", AsyncMock(return_value=origin))++ async def hydrate_and_exit(ctx: CopilotContext, *, workflow_run_id: str | None) -> None:+ await copilot_runtime.resolve_browser_state_for_context(ctx, session_id=session_id)+ await _exit(ctx)++ monkeypatch.setattr(copilot_agent, "hydrate_prior_run_packet", hydrate_and_exit)+ mock_app = MagicMock()+ mock_app.PERSISTENT_SESSIONS_MANAGER = manager+ monkeypatch.setattr(copilot_runtime, "app", mock_app)+ monkeypatch.setattr(copilot_agent, "_manager_can_probe_registered_browser_state", lambda: True)++ try:+ result = await run_copilot_agent(+ stream=MagicMock(),+ organization_id="org-1",+ chat_request=WorkflowCopilotChatRequest(+ workflow_permanent_id="wfp-1",+ workflow_id="wf-1",+ workflow_copilot_chat_id="chat-1",+ message="read the page title and tell me what it is",+ workflow_yaml="",+ workflow_run_id=workflow_run_id,+ ),+ chat_history=[],+ global_llm_context=None,+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),+ raw_secret_safety_handler=AsyncMock(+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}+ ),+ api_key="sk-test",+ eval_mode=eval_mode,+ )+ except BaseException as exc:+ return None, exc+ return result, None+++async def run_concurrent_turns_on_one_session(+ monkeypatch: pytest.MonkeyPatch,+ *,+ manager: MagicMock,+ browser_states: tuple[MagicMock, MagicMock],+ exit_order: tuple[int, int] = (0, 1),+ after_first_exit: Callable[[], None] = lambda: None,+) -> None:+ """Two turns attached to one session, each on its own generation, released in ``exit_order``;+ ``after_first_exit`` is the point where only the earlier turn's release has run."""+ attached = (asyncio.Event(), asyncio.Event())+ may_exit = (asyncio.Event(), asyncio.Event())+ arrivals = count()++ async def _gate() -> None:+ index = next(arrivals)+ attached[index].set()+ await may_exit[index].wait()++ def _turn(index: int) -> asyncio.Task[tuple[AgentResult | None, BaseException | None]]:+ return asyncio.ensure_future(+ run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=browser_states[index],+ on_attached=lambda _ctx: _gate(),+ )+ )++ first = _turn(0)+ await asyncio.wait_for(attached[0].wait(), 5)+ second = _turn(1)+ await asyncio.wait_for(attached[1].wait(), 5)+ turns = (first, second)++ may_exit[exit_order[0]].set()+ await turns[exit_order[0]]+ after_first_exit()+ may_exit[exit_order[1]].set()+ await turns[exit_order[1]]+++async def run_turn_attaching_during_release(+ monkeypatch: pytest.MonkeyPatch,+ *,+ manager: MagicMock,+ browser_states: tuple[MagicMock, MagicMock],+ lookup_already_in_flight: bool = False,+) -> None:+ """A second turn resolves the session while the first turn's exit evict is still in flight.+ The manager hands out the first generation until that evict completes and the second after.+ With ``lookup_already_in_flight`` the second turn's lookup was issued before the release began+ and only answers once the evict is under way."""+ first_attached, evicting, evicted, contested = (asyncio.Event() for _ in range(4))++ async def _evict(*_args: object, **_kwargs: object) -> bool:+ if evicted.is_set():+ return True+ evicting.set()+ with suppress(TimeoutError):+ await asyncio.wait_for(contested.wait(), 1.0)+ evicted.set()+ return True++ async def _current_generation(**_kwargs: object) -> MagicMock:+ first_attached.set()+ if evicting.is_set() and not evicted.is_set():+ contested.set()+ return browser_states[1] if evicted.is_set() else browser_states[0]++ async def _generation_answered_mid_release(**kwargs: object) -> MagicMock:+ await asyncio.wait_for(evicting.wait(), 5)+ return await _current_generation(**kwargs)++ manager.evict_cached_browser_state = AsyncMock(side_effect=_evict)+ first = asyncio.ensure_future(+ run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=browser_states[0],+ get_browser_state=AsyncMock(side_effect=_current_generation),+ )+ )+ second_lookup = _current_generation+ if lookup_already_in_flight:+ await asyncio.wait_for(first_attached.wait(), 5)+ second_lookup = _generation_answered_mid_release+ else:+ await asyncio.wait_for(evicting.wait(), 5)+ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=browser_states[1],+ get_browser_state=AsyncMock(side_effect=second_lookup),+ )+ await first+++async def run_turn_cancelled_during_cleanup(+ monkeypatch: pytest.MonkeyPatch,+ *,+ manager: MagicMock,+ browser_state: MagicMock,+ evicting: asyncio.Event,+ on_attached: Callable[[CopilotContext], Awaitable[None]] | None = None,+) -> tuple[AgentResult | None, BaseException | None]:+ """Cancel the turn once its exit release has reached the manager, which is the only window in+ which a cancel can land on the finalizer rather than on the turn's own work."""+ turn = asyncio.ensure_future(+ run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=browser_state,+ on_attached=on_attached,+ )+ )+ await asyncio.wait_for(evicting.wait(), 5)+ turn.cancel()+ return await turndiff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.pyindex 48f8637bd..d946a92d1 100644--- a/tests/unit/test_code_block_sandbox.py+++ b/tests/unit/test_code_block_sandbox.py@@ -8,6 +8,7 @@ Verifies that the CodeBlock safety layer:import asyncioimport json+import refrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom datetime import UTC, datetime, timezone@@ -20,13 +21,18 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutErrorimport skyvern.forge.sdk.workflow.models.block as block_modulefrom skyvern.config import settings+from skyvern.forge.sdk.copilot.code_block_security import rendering_introduced_security_errorsfrom skyvern.forge.sdk.workflow.code_block_safety import (ALWAYS_DENIED_BUILTINS,SANDBOX_ONLY_BUILTINS,is_safe_script_code,safe_builtins,)-from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected, MissingJinjaVariables+from skyvern.forge.sdk.workflow.exceptions import (+ FailedToFormatJinjaStyleParameter,+ InsecureCodeDetected,+ MissingJinjaVariables,+)from skyvern.forge.sdk.workflow.models.block import (CODE_BLOCK_TAB_OPEN_FAILURE_REASON,BranchEvaluationContext,@@ -3064,3 +3070,154 @@ class TestClearBrowserDataHelperBinding:("DOMStorage.clear", {"storageId": {"securityOrigin": expected_origin, "isLocalStorage": False}}),]assert session.detached+++class TestInertSlotRenderIsTheSpliceReference:+ """The gate compares the real render against the same template rendered with inert value slots, so a slot may+ hold a literal and nothing else; no template shape or value can cancel that out."""++ def _block(self, code: str) -> CodeBlock:+ now = datetime.now(UTC)+ return CodeBlock(+ label="read",+ code=code,+ output_parameter=OutputParameter(+ parameter_type=ParameterType.OUTPUT,+ key="read_output",+ description="",+ output_parameter_id="op_read",+ workflow_id="w_test",+ created_at=now,+ modified_at=now,+ ),+ )++ _EXFIL = "await page.context.cookies()"++ @pytest.mark.parametrize(+ ("template", "values", "expect_refused"),+ [+ pytest.param("jar = {{ exfil }}\nresult = jar\n", {"exfil": _EXFIL}, True, id="single-line-slot"),+ pytest.param("jar = {{\nexfil\n}}\nresult = jar\n", {"exfil": _EXFIL}, True, id="multiline-slot"),+ pytest.param("jar = {{- exfil }}\nresult = jar\n", {"exfil": _EXFIL}, True, id="whitespace-control-slot"),+ pytest.param(+ "total = {{- count -}}\n + 1\n", {"count": 41}, False, id="trim-markers-apply-to-both-renders"+ ),+ pytest.param("result = {% print exfil %}\n", {"exfil": _EXFIL}, True, id="print-statement-slot"),+ pytest.param("result = {%- print exfil -%}\n", {"exfil": _EXFIL}, True, id="print-statement-trim-slot"),+ pytest.param("result = {% print count %}\n", {"count": 7}, False, id="print-statement-literal"),+ pytest.param(+ '{% filter replace("SLOT", payload) %}result = SLOT{% endfilter %}\n',+ {"payload": _EXFIL},+ True,+ id="filter-block-with-value-argument",+ ),+ pytest.param(+ '{% filter replace(old="SLOT", new=payload) %}result = SLOT{% endfilter %}\n',+ {"payload": _EXFIL},+ True,+ id="filter-block-with-value-keyword",+ ),+ pytest.param(+ '{% filter replace("SLOT", "7") | upper %}RESULT = SLOT\n{% endfilter %}',+ {},+ False,+ id="filter-block-with-constant-arguments",+ ),+ pytest.param(+ "{% macro emit(v) %}result = {{ v }}{% endmacro %}{{ emit(payload) }}\n",+ {"payload": _EXFIL},+ True,+ id="macro-emitting-a-value",+ ),+ pytest.param(+ "{% macro wrap() %}result = {{ caller() }}{% endmacro %}{% call wrap() %}{{ payload }}{% endcall %}\n",+ {"payload": _EXFIL},+ True,+ id="call-block-emitting-a-value",+ ),+ pytest.param(+ "{% set n %}{{ count }}{% endset %}result = {{ n }}\n",+ {"count": 7},+ False,+ id="set-block-then-literal-slot",+ ),+ pytest.param(+ "{% if flag %}page.context.set_default_timeout(1)\n{% endif %}jar = {{ exfil }}\n",+ {"flag": False, "exfil": _EXFIL},+ True,+ id="false-branch-decoy",+ ),+ pytest.param(+ "ctx = page.context\nresult = {{ payload }}\n",+ {"payload": "await ctx.cookies()"},+ True,+ id="authored-alias-consumed-by-value",+ ),+ pytest.param(+ "__skyvern_slot__ = page.context\nresult = await {{ alias }}.cookies()\n",+ {"alias": "__skyvern_slot__"},+ True,+ id="value-equal-to-the-inert-marker",+ ),+ pytest.param(+ "x = {{ payload }}; page.context.set_default_timeout(1)\n",+ {"payload": f"{_EXFIL} or None #"},+ True,+ id="value-comments-out-authored-statement",+ ),+ pytest.param("total = {{ count }} + 1\n", {"count": 41}, False, id="number-slot"),+ pytest.param('url = "{{ base }}/x"\n', {"base": "https://a.example"}, False, id="slot-inside-string"),+ pytest.param("flag = {{ on }}\n", {"on": True}, False, id="bool-slot"),+ pytest.param(+ "rows = []\n{% for r in items %}rows.append({{ r }})\n{% endfor %}",+ {"items": [{"a": 1}, {"a": "b"}]},+ False,+ id="json-literal-per-loop-iteration",+ ),+ pytest.param(+ "# note {{ exfil }}\nresult = 1\n", {"exfil": _EXFIL}, False, id="slot-inside-comment-is-masked"+ ),+ pytest.param("result = await page.context.cookies()\n", {}, False, id="no-slots-authored-read"),+ ],+ )+ def test_slots_may_hold_literals_only(self, template: str, values: dict[str, object], expect_refused: bool) -> None:+ block = self._block(template)++ authored = block.render_code_with_reference(FakeWorkflowRunContext(values=values))++ errors = rendering_introduced_security_errors(label="read", authored_code=authored, rendered_code=block.code)+ assert bool(errors) is expect_refused, (authored, block.code)++ def test_reference_render_does_not_consume_what_the_real_render_consumed(self) -> None:+ block = self._block("{% set item = items.pop() %}result = {{ item }}\n")+ context = FakeWorkflowRunContext(values={"items": [7]})++ authored = block.render_code_with_reference(context)++ assert block.code.strip() == "result = 7"+ assert authored is not None+ assert (+ rendering_introduced_security_errors(label="read", authored_code=authored, rendered_code=block.code) == []+ )+ assert context.values["items"] == []++ def test_template_that_pulls_in_another_template_fails_before_the_gate(self) -> None:+ block = self._block('{% include "other" %}result = 1\n')++ with pytest.raises(FailedToFormatJinjaStyleParameter):+ block.format_potential_template_parameters(FakeWorkflowRunContext(values={}))++ def test_slot_form_the_rewrite_misses_is_rejected_by_the_parse(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(block_module, "_JINJA_PRINT_SLOT_RE", re.compile(r"(?!x)(x)(y)"))+ block = self._block("result = {% print exfil %}\n")++ assert block.render_code_with_inert_slots(block.code, FakeWorkflowRunContext(values={"exfil": "1"})) is None++ def test_prompt_and_error_mapping_still_render_after_code(self) -> None:+ block = self._block("result = 1\n")+ block.prompt = "hello {{ name }}"++ block.format_potential_template_parameters(FakeWorkflowRunContext(values={"name": "world"}))++ assert block.prompt == "hello world"diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 267d81160..fdc31e957 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -32,7 +32,11 @@ from skyvern.forge.sdk.copilot.code_block_preflight import (author_time_code_block_diagnostics,preflight_code_block,)-from skyvern.forge.sdk.copilot.code_block_security import author_time_code_security_errors+from skyvern.forge.sdk.copilot.code_block_security import (+ CodeBlockSecurityInput,+ author_time_code_security_errors,+ runtime_code_security_errors,+)from skyvern.forge.sdk.copilot.code_block_synthesis import (_DOWNLOAD_VAR_BASE,_ENTRY_RESUME_AFTER_AUTH_VAR,@@ -2014,6 +2018,43 @@ class TestPreflightSurfacesSyntaxError:assert [diagnostic.code for diagnostic in diagnostics if diagnostic.code.startswith("AUTHOR_PAGE_")] == [reason]assert any("not allowed in persisted workflow code blocks" in diagnostic.message for diagnostic in diagnostics)+ @pytest.mark.parametrize(+ "code",+ [+ 'ctx = getattr(page, "con" + "text"); result = await ctx.cookies()',+ 'setattr(page, "con" + "text", None)',+ 'delattr(page, "con" + "text")',+ 'ctx = vars(page)["context"]; result = await ctx.cookies()',+ "lookup = getattr; ctx = lookup(page, 'context')",+ 'ga = globals()["__buil" + "tins__"]["get" + "attr"]; ctx = ga(page, "con" + "text")',+ 'ns = locals(); ctx = ns["page"]',+ ],+ )+ def test_dynamic_attribute_builtins_are_refused_at_both_seams(self, code: str) -> None:+ author_errors = author_time_code_security_errors(label="search_registry", code=code)+ runtime_errors = runtime_code_security_errors([CodeBlockSecurityInput(label="search_registry", code=code)])++ assert [error.reason_code for error in author_errors] == ["AUTHOR_DYNAMIC_ATTRIBUTE"]+ assert [error.reason_code for error in runtime_errors] == ["RUNTIME_DYNAMIC_ATTRIBUTE"]+ assert [d.code for d in preflight_code_block(code, parameter_keys=()) if d.code.startswith("AUTHOR_")] == [+ "AUTHOR_DYNAMIC_ATTRIBUTE"+ ]++ def test_match_class_pattern_reading_context_is_refused_at_both_seams(self) -> None:+ code = "match page:\n case object(context=ctx):\n result = await ctx.cookies()\n"++ author_errors = author_time_code_security_errors(label="search_registry", code=code)+ runtime_errors = runtime_code_security_errors([CodeBlockSecurityInput(label="search_registry", code=code)])++ assert [error.reason_code for error in author_errors] == ["AUTHOR_PAGE_CONTEXT"]+ assert [error.reason_code for error in runtime_errors] == ["RUNTIME_PAGE_CONTEXT"]++ def test_literal_attribute_block_has_no_dynamic_attribute_error(self) -> None:+ code = 'await page.goto("https://example.com/")\ntitle = await page.title()'++ assert author_time_code_security_errors(label="search_registry", code=code) == []+ assert runtime_code_security_errors([CodeBlockSecurityInput(label="search_registry", code=code)]) == []+@pytest.mark.parametrize("code",[diff --git a/tests/unit/test_copilot_live_session_helper.py b/tests/unit/test_copilot_live_session_helper.pyindex 85bce549f..7d8e6e816 100644--- a/tests/unit/test_copilot_live_session_helper.py+++ b/tests/unit/test_copilot_live_session_helper.py@@ -4,7 +4,7 @@ from collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom datetime import UTC, datetimefrom types import SimpleNamespace-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, MagicMockimport pytestfrom sqlalchemy.exc import TimeoutError as SQLATimeoutError@@ -12,6 +12,7 @@ from sqlalchemy.exc import TimeoutError as SQLATimeoutErrorimport skyvern.forge.sdk.copilot.agent as agent_modulefrom skyvern.forge import appfrom skyvern.forge.sdk.copilot.agent import _resolve_live_browser_session_id+from skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSessionfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequestfrom skyvern.webeye.persistent_sessions_manager import BrowserOperation, BrowserRetirement@@ -19,6 +20,17 @@ from skyvern.webeye.persistent_sessions_manager import BrowserOperation, Browser_UNSET_UPSTREAM = "<unset>"+def _ctx() -> AgentContext:+ return AgentContext(+ organization_id="org-1",+ workflow_id="wf-1",+ workflow_permanent_id="wpid-1",+ workflow_yaml="",+ browser_session_id=None,+ stream=MagicMock(),+ )++class _FakeBrowser:def is_connected(self) -> bool:return True@@ -81,7 +93,9 @@ async def test_no_id_returns_none_and_does_not_call_db(monkeypatch: pytest.MonkeSimpleNamespace(get_debug_session_by_browser_session_id=debug_mock),)- result = await _resolve_live_browser_session_id(_request(browser_session_id=None), organization_id="org-1")+ result = await _resolve_live_browser_session_id(+ _request(browser_session_id=None), organization_id="org-1", ctx=_ctx()+ )assert result is Nonedebug_mock.assert_not_awaited()@@ -95,7 +109,9 @@ async def test_unknown_id_falls_back(monkeypatch: pytest.MonkeyPatch) -> None:SimpleNamespace(get_debug_session_by_browser_session_id=AsyncMock(return_value=None)),)- result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_unknown"), organization_id="org-1")+ result = await _resolve_live_browser_session_id(+ _request(browser_session_id="pbs_unknown"), organization_id="org-1", ctx=_ctx()+ )assert result is None@@ -115,6 +131,7 @@ async def test_wrong_workflow_falls_back(monkeypatch: pytest.MonkeyPatch) -> Nonresult = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_foreign", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result is None@@ -143,6 +160,7 @@ async def test_persistent_row_missing_falls_back(monkeypatch: pytest.MonkeyPatchresult = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_unknown_persistent", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result is None@@ -173,6 +191,7 @@ async def test_status_in_final_state_falls_back(monkeypatch: pytest.MonkeyPatch)result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_done", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result is None@@ -203,6 +222,7 @@ async def test_browser_address_unset_falls_back(monkeypatch: pytest.MonkeyPatch)result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_booting", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result is None@@ -232,6 +252,7 @@ async def test_default_manager_registered_browser_state_allows_missing_browser_aresult = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_booted_local", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result == "pbs_booted_local"@@ -262,6 +283,7 @@ async def test_default_manager_unattachable_registered_browser_state_falls_back(result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_not_ready", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result is None@@ -291,6 +313,7 @@ async def test_owned_and_running_returns_id(monkeypatch: pytest.MonkeyPatch) ->result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_live", wpid="wpid-1"),organization_id="org-1",+ ctx=_ctx(),)assert result == "pbs_live"@@ -308,7 +331,9 @@ async def test_db_exception_falls_back(monkeypatch: pytest.MonkeyPatch) -> None:),)- result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_x"), organization_id="org-1")+ result = await _resolve_live_browser_session_id(+ _request(browser_session_id="pbs_x"), organization_id="org-1", ctx=_ctx()+ )assert result is None@@ -380,7 +405,9 @@ async def test_liveness_lookup_failure_keeps_the_session(monkeypatch: pytest.MonAsyncMock(side_effect=SQLATimeoutError("QueuePool limit of size 20 overflow 20 reached")),)- result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_live"), organization_id="org-1")+ result = await _resolve_live_browser_session_id(+ _request(browser_session_id="pbs_live"), organization_id="org-1", ctx=_ctx()+ )assert result == "pbs_live"@@ -423,7 +450,9 @@ async def test_unavailable_health_signal_keeps_the_session_at_the_first_gate(state = SimpleNamespace(browser_context=_RaisingContext())monkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "get_browser_state", AsyncMock(return_value=state))- result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_live"), organization_id="org-1")+ result = await _resolve_live_browser_session_id(+ _request(browser_session_id="pbs_live"), organization_id="org-1", ctx=_ctx()+ )assert result == "pbs_live"@@ -467,6 +496,8 @@ async def test_a_session_the_relay_declared_unreachable_is_not_reused(monkeypatcmonkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "get_session", AsyncMock(return_value=dead))monkeypatch.setattr(agent_module, "_manager_can_probe_registered_browser_state", lambda: False)- result = await _resolve_live_browser_session_id(_request(browser_session_id="pbs_test"), organization_id="org-1")+ result = await _resolve_live_browser_session_id(+ _request(browser_session_id="pbs_test"), organization_id="org-1", ctx=_ctx()+ )assert result is Nonediff --git a/tests/unit/test_copilot_locator_inspection.py b/tests/unit/test_copilot_locator_inspection.pyindex 1d8ed979c..4920e66c8 100644--- a/tests/unit/test_copilot_locator_inspection.py+++ b/tests/unit/test_copilot_locator_inspection.py@@ -607,7 +607,7 @@ async def test_a_closed_run_page_reports_nothing_rather_than_zero_matches(monkeypatch.setattr(run_execution, "resolve_persistent_browser_state", _resolve)observed = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_gone",failed_block_code='page.locator("#rate").inner_text()',)@@ -681,7 +681,7 @@ async def test_worker_owned_observation_types_every_selector_without_resolving_amonkeypatch.setattr(run_execution, "resolve_persistent_browser_state", resolver)rows = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_worker",failed_block_code='page.locator("#first")\npage.locator("#first")\npage.locator("text=Second")',worker_owned=True,@@ -700,7 +700,7 @@ async def test_missing_browser_and_missing_page_have_distinct_typed_reasons(monkmonkeypatch.setattr(run_execution, "resolve_persistent_browser_state", AsyncMock(return_value=None))missing_browser = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_missing",failed_block_code='page.locator("#target")',)@@ -710,7 +710,7 @@ async def test_missing_browser_and_missing_page_have_distinct_typed_reasons(monkAsyncMock(return_value=_observation_browser(None)),)missing_page = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_closed",failed_block_code='page.locator("#target")',)@@ -737,7 +737,7 @@ async def test_resolution_and_identity_failures_never_become_zero_matches(monkey)rows = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_1",failed_block_code=('page.locator("bad engine")\npage.locator("#identity")\npage.locator("#absent")'),)@@ -773,7 +773,7 @@ async def test_ordinary_observation_exception_is_typed_without_losing_the_failur)rows = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_1",failed_block_code='page.locator("#failure")\npage.locator("#absent")',)@@ -805,7 +805,7 @@ async def test_observation_cancellation_is_not_converted_to_typed_absence(with pytest.raises(asyncio.CancelledError):await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_1",failed_block_code='page.locator("#cancelled")',)@@ -832,7 +832,7 @@ async def test_observation_deadline_preserves_partial_rows_and_types_every_remaimonkeypatch.setattr(run_execution, "_OBSERVED_LOCATOR_BUDGET_SECONDS", 0.01)rows = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_1",failed_block_code='page.locator("#done")\npage.locator("#wedged")\npage.locator("#later")',)@@ -858,7 +858,7 @@ async def test_observer_packet_and_sanitizer_preserve_typed_rows_and_exact_omissAsyncMock(return_value=_observation_browser(page)),)rows = await run_execution._observe_authored_locators(- SimpleNamespace(organization_id="org-1"), # type: ignore[arg-type]+ SimpleNamespace(organization_id="org-1", attached_browser_drivers={}), # type: ignore[arg-type]run_session_id="pbs_1",failed_block_code="\n".join(f'page.locator("{selector}")' for selector in selectors),)diff --git a/tests/unit/test_copilot_outcome_verification_trace.py b/tests/unit/test_copilot_outcome_verification_trace.pyindex cfd540e68..aab21985c 100644--- a/tests/unit/test_copilot_outcome_verification_trace.py+++ b/tests/unit/test_copilot_outcome_verification_trace.py@@ -217,6 +217,7 @@ async def test_run_copilot_agent_finalizes_false_gate_on_turn_span(ctx = SimpleNamespace(workflow_verification_evidence=WorkflowVerificationEvidence(test_attempted_but_incomplete=True),request_policy=RequestPolicy(),+ attached_browser_drivers={},)record_gate_decision(ctx,diff --git a/tests/unit/test_copilot_runtime.py b/tests/unit/test_copilot_runtime.pyindex f747c5491..879e8e63e 100644--- a/tests/unit/test_copilot_runtime.py+++ b/tests/unit/test_copilot_runtime.py@@ -37,6 +37,7 @@ from skyvern.forge.sdk.copilot.runtime import (mcp_browser_context,mcp_to_copilot,)+from skyvern.forge.sdk.copilot.tools import run_executionfrom skyvern.forge.sdk.copilot.unrecoverable_tool_error import _is_unrecoverable_browser_session_errorfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSessionfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus@@ -47,6 +48,14 @@ from skyvern.webeye.persistent_sessions_manager import (BrowserRetirement,BrowserSessionCreditAdmissionRefusal,)+from tests.unit.copilot_test_helpers import (+ TURN_EXIT_PATHS,+ make_copilot_ctx,+ run_concurrent_turns_on_one_session,+ run_turn_attaching_during_release,+ run_turn_cancelled_during_cleanup,+ run_turn_to_exit,+)from tests.unit.test_copilot_secret_scrub import _make_server@@ -346,6 +355,7 @@ async def test_ensure_browser_session_waits_for_browser_context(monkeypatch: pytassert result is Noneassert ctx.browser_session_id == "bs_1"assert mock_manager.get_browser_state.await_count == 3+ assert ctx.attached_browser_drivers == {"bs_1": runtime.AttachedBrowserDriver("bs_1", ready_state)}@pytest.mark.asyncio@@ -828,6 +838,7 @@ async def test_a_cancelled_caller_leaves_the_determination_running_and_never_inhmock_manager = MagicMock()mock_manager.get_browser_state = AsyncMock(side_effect=_get_browser_state)+ mock_manager.supports_evict_and_reconnect = MagicMock(return_value=False)mock_app = MagicMock()mock_app.PERSISTENT_SESSIONS_MANAGER = mock_managermonkeypatch.setattr(runtime, "app", mock_app)@@ -860,6 +871,7 @@ async def test_a_cancelled_caller_leaves_the_determination_running_and_never_inh_COPILOT_PACKAGE = Path(__file__).resolve().parents[2] / "skyvern" / "forge" / "sdk" / "copilot"_MANAGER_ENTRY_POINTS = frozenset({+ "evict_cached_browser_state","resolve_persistent_browser_state","resolve_browser_state_for_context","_resolve_self_heal_browser_state",@@ -871,11 +883,9 @@ _MANAGER_ENTRY_POINTS = frozenset()-# Copilot legitimately bounds two LIFECYCLE calls: the create-and-boot poll (the OSS default-# manager returns before Chrome exists) and the quiet close (the backend is usually why we are-# closing). Both are recorded in cloud_docs/persistent-browser-sessions/BOUNDS.md. Every other-# clock around a manager call is the shape decision 0032 forbids, so adding one means adding its-# constant here - a visible line in the diff, not a silent exemption.+# Three LIFECYCLE calls are legitimately bounded and recorded in BOUNDS.md: the create-and-boot+# poll, the quiet close, and the turn-exit driver release. Every other clock around a manager call+# is the shape decision 0032 forbids, so adding one means adding its constant here._DOCUMENTED_LIFECYCLE_BOUNDS = frozenset({"_BROWSER_BOOT_WAIT_SECONDS", "_SESSION_CLEANUP_TIMEOUT_SECONDS"})@@ -898,6 +908,9 @@ def _called_name(node: ast.AST) -> str | None:node = node.valueif not isinstance(node, ast.Call):return None+ # A shield is transparent to this rule: the bound still lands on the manager call inside it.+ if isinstance(node.func, ast.Attribute) and node.func.attr == "shield" and node.args:+ return _called_name(node.args[0])if isinstance(node.func, ast.Name):return node.func.idif isinstance(node.func, ast.Attribute):@@ -905,6 +918,20 @@ def _called_name(node: ast.AST) -> str | None:return None+def _calls_in_own_scope(fn: ast.AsyncFunctionDef | ast.FunctionDef) -> list[ast.Call]:+ """Calls this function makes itself; a nested function owns its own calls."""+ calls: list[ast.Call] = []+ stack: list[ast.AST] = list(fn.body)+ while stack:+ node = stack.pop()+ if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef, ast.Lambda)):+ continue+ if isinstance(node, ast.Call):+ calls.append(node)+ stack.extend(ast.iter_child_nodes(node))+ return calls++def _wait_for_bound(node: ast.Call) -> str:"""The constant bounding an `asyncio.wait_for(...)` call, as its keyword or trailing argument."""argument = next((kw.value for kw in node.keywords if kw.arg == "timeout"), None)@@ -1544,3 +1571,766 @@ async def test_owner_refusing_the_replacement_retires_the_session_and_leaves_a_rmonkeypatch.setattr(runtime, "ensure_build_test_browser_session", provision)assert await runtime.verify_build_test_browser_session_by_attaching(ctx) is Noneprovision.assert_awaited_once()+++_TURN_EXIT_TERMINAL_REASONS = {+ "normal": None,+ "model_error": "unexpected_error",+ "deadline": "timeout",+ "cancel": "cancel",+}+++def _release_manager(*, evict: AsyncMock | None = None, supported: bool = True) -> MagicMock:+ manager = MagicMock()+ manager.supports_evict_and_reconnect = MagicMock(return_value=supported)+ manager.evict_cached_browser_state = evict or AsyncMock(return_value=True)+ manager.close_session = AsyncMock()+ return manager++[email protected]("exit_path", TURN_EXIT_PATHS)+async def test_every_turn_exit_releases_the_driver_it_attached(monkeypatch: pytest.MonkeyPatch, exit_path: str) -> None:+ attached = MagicMock()+ manager = _release_manager()++ with capture_logs() as logs:+ result, _ = await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path=exit_path,+ session_id="pbs_turn",+ browser_state=attached,+ )++ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_turn",+ "org-1",+ expected=attached,+ detach_remote_driver=True,+ only_if_unleased=True,+ )+ manager.close_session.assert_not_awaited()+ released = [log for log in logs if log["event"] == "copilot_browser_driver_released"]+ assert [(log["session_id"], log["had_cached_driver"]) for log in released] == [("pbs_turn", True)]+ assert result is not None+ assert result.turn_outcome.terminal_reason == _TURN_EXIT_TERMINAL_REASONS[exit_path]+++async def test_a_cancel_during_prior_run_hydration_still_releases_the_driver_it_attached(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Reading the origin run attaches to that run's browser before the model loop starts; a+ cancel landing there must still reach the finalizer with the attach on record."""+ attached = MagicMock()+ manager = _release_manager()++ with capture_logs() as logs:+ result, raised = await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="cancel",+ session_id="pbs_origin_run",+ browser_state=attached,+ attach_through="prior_run_hydration",+ )++ assert result is None+ assert isinstance(raised, asyncio.CancelledError)+ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_origin_run",+ "org-1",+ expected=attached,+ detach_remote_driver=True,+ only_if_unleased=True,+ )+ manager.close_session.assert_not_awaited()+ released = [log for log in logs if log["event"] == "copilot_browser_driver_released"]+ assert [(log["session_id"], log["had_cached_driver"]) for log in released] == [("pbs_origin_run", True)]+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}++[email protected]("session_id", [None, "pbs_turn"])+async def test_a_turn_that_attached_nothing_releases_nothing(+ monkeypatch: pytest.MonkeyPatch, session_id: str | None+) -> None:+ """A turn that never attached must not retire a generation a concurrent turn is driving."""+ manager = _release_manager()++ await run_turn_to_exit(monkeypatch, manager=manager, exit_path="normal", session_id=session_id, browser_state=None)++ manager.evict_cached_browser_state.assert_not_awaited()+++async def test_a_manager_that_cannot_reconnect_after_eviction_is_left_alone(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The OSS default manager drives the browser in-process: detaching its driver would strand+ the browser and leave the session uncacheable for the rest of its life."""+ manager = _release_manager(supported=False)++ await run_turn_to_exit(monkeypatch, manager=manager, exit_path="normal", browser_state=MagicMock())++ manager.evict_cached_browser_state.assert_not_awaited()++[email protected]("failure", ["raises", "hangs", "cancelled"])[email protected]("exit_path", TURN_EXIT_PATHS)+async def test_a_failed_release_does_not_replace_the_turns_own_terminal(+ monkeypatch: pytest.MonkeyPatch, failure: str, exit_path: str+) -> None:+ detached = asyncio.Event()++ async def _hang(*args: object, **kwargs: object) -> bool:+ await asyncio.sleep(runtime._SESSION_CLEANUP_TIMEOUT_SECONDS * 4)+ detached.set()+ return True++ evicts = {+ "raises": AsyncMock(side_effect=RuntimeError("evict exploded")),+ "hangs": AsyncMock(side_effect=_hang),+ "cancelled": AsyncMock(side_effect=asyncio.CancelledError()),+ }+ monkeypatch.setattr(runtime, "_SESSION_CLEANUP_TIMEOUT_SECONDS", 0.01)++ with capture_logs() as logs:+ result, raised = await run_turn_to_exit(+ monkeypatch,+ manager=_release_manager(evict=evicts[failure]),+ exit_path=exit_path,+ browser_state=MagicMock(),+ )++ assert [log for log in logs if log["event"] == "copilot_browser_driver_released"] == []+ assert raised is None+ assert result is not None+ assert result.turn_outcome.terminal_reason == _TURN_EXIT_TERMINAL_REASONS[exit_path]+ if failure == "hangs":+ # The detach outliving the caller's bound is the shield: without it the timed-out wait+ # cancels the evict and strands the popped cache entry this release exists to drop.+ await asyncio.wait_for(detached.wait(), timeout=2)+++async def test_a_resolve_for_another_session_is_released_by_the_turn_that_attached_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A tool resolving a run's own session caches that driver on this pod exactly like the chat+ session's, so the turn that attached it is the only thing that will ever hand it back."""+ attached = MagicMock()+ manager = _release_manager()++ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ session_id="pbs_turn",+ resolve_session_id="pbs_other",+ browser_state=attached,+ )++ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_other", "org-1", expected=attached, detach_remote_driver=True, only_if_unleased=True+ )+++async def test_a_self_heal_turn_leaves_the_healers_injected_driver_alone(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The healer's injected browser state never entered this pod's cache, so evicting it could+ only retire a generation this turn does not own."""+ manager = _release_manager()++ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=MagicMock(),+ turn_origin=runtime.TurnOrigin.runtime_self_heal,+ )++ manager.evict_cached_browser_state.assert_not_awaited()+++async def test_only_the_last_concurrent_turn_on_a_session_releases_its_driver(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Retiring the cached generation cancels its admitted operations, so a turn that exits while+ a sibling turn is still attached to the same session must leave the driver where it is."""+ state = MagicMock()+ manager = _release_manager()++ def _after_first_exit() -> None:+ manager.evict_cached_browser_state.assert_not_awaited()++ await run_concurrent_turns_on_one_session(+ monkeypatch, manager=manager, browser_states=(state, state), after_first_exit=_after_first_exit+ )++ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_turn", "org-1", expected=state, detach_remote_driver=True, only_if_unleased=True+ )+++async def test_a_cancel_delivered_while_the_release_waits_is_not_swallowed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A turn cancelled mid-cleanup must still report as cancelled, and the detach it already+ started must finish rather than stranding the popped cache entry."""+ evicting = asyncio.Event()+ detached = asyncio.Event()++ async def _slow_evict(*args: object, **kwargs: object) -> bool:+ evicting.set()+ await asyncio.sleep(0.05)+ detached.set()+ return True++ result, raised = await run_turn_cancelled_during_cleanup(+ monkeypatch,+ manager=_release_manager(evict=AsyncMock(side_effect=_slow_evict)),+ browser_state=MagicMock(),+ evicting=evicting,+ )++ assert result is None+ assert isinstance(raised, asyncio.CancelledError)+ await asyncio.wait_for(detached.wait(), timeout=2)+++async def test_a_turn_that_only_probed_the_session_still_releases_the_driver_it_attached(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The liveness probe attaches through the same cache as every other lookup, so a turn that+ never touched the browser afterwards still owns the driver the probe left behind."""+ attached = MagicMock()+ manager = _release_manager()++ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=attached,+ attach_through="liveness_probe",+ )++ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_turn", "org-1", expected=attached, detach_remote_driver=True, only_if_unleased=True+ )+++async def test_a_build_test_run_on_the_turns_own_session_records_the_driver_it_attached(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A build test that reuses the chat's own browser resolves it outside the tool funnel, so+ without its own recording the turn exits owing a driver nothing released."""+ ctx = make_copilot_ctx(browser_session_id="pbs_turn")+ attached = MagicMock()+ monkeypatch.setattr(run_execution, "resolve_persistent_browser_state", AsyncMock(return_value=attached))++ await run_execution._observe_authored_locators(+ ctx,+ run_session_id="pbs_turn",+ failed_block_code="page.locator('#pay').click()",+ )++ assert list(ctx.attached_browser_drivers) == ["pbs_turn"]+ assert ctx.attached_browser_drivers["pbs_turn"].browser_state is attached+++async def test_a_build_test_run_on_a_separate_session_records_that_session_too(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = make_copilot_ctx(browser_session_id="pbs_turn")+ attached = MagicMock()+ monkeypatch.setattr(run_execution, "resolve_persistent_browser_state", AsyncMock(return_value=attached))++ await run_execution._observe_authored_locators(+ ctx,+ run_session_id="pbs_minted",+ failed_block_code="page.locator('#pay').click()",+ )++ assert ctx.attached_browser_drivers["pbs_minted"].browser_state is attached+++def test_every_copilot_resolve_of_a_cached_browser_state_records_what_it_attached() -> None:+ """The turn-exit release can only retire generations the turn recorded, so a resolve that+ reaches the pod's cache without a recording beside it strands its driver until the session dies."""+ offenders: list[str] = []+ for path in sorted(_COPILOT_PACKAGE.rglob("*.py")):+ tree = ast.parse(path.read_text(), filename=str(path))+ for node in ast.walk(tree):+ if not isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):+ continue+ names = [_called_name(call) for call in _calls_in_own_scope(node)]+ if "resolve_persistent_browser_state" in names and "record_attached_browser_driver" not in names:+ offenders.append(f"{path.name}:{node.lineno} {node.name}")+ assert offenders == [], "Copilot resolves that never record the driver they attached:\n" + "\n".join(offenders)+++async def test_a_turn_that_attached_two_sessions_releases_both(monkeypatch: pytest.MonkeyPatch) -> None:+ """Recording only the newest attach would leave the first session's driver cached for the rest+ of its lifetime — the exact pileup this release exists to stop."""+ first, second = MagicMock(), MagicMock()+ manager = _release_manager()+ states = {"pbs_first": first, "pbs_second": second}+ manager.get_browser_state = AsyncMock(side_effect=lambda session_id, *a, **k: states[session_id])++ async def _attach_a_second_session(ctx: runtime.AgentContext) -> None:+ ctx.browser_session_id = "pbs_second"+ await runtime.resolve_browser_state_for_context(ctx, session_id="pbs_second")++ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ session_id="pbs_first",+ browser_state=first,+ on_attached=_attach_a_second_session,+ )++ released = [call.args[0] for call in manager.evict_cached_browser_state.await_args_list]+ assert sorted(released) == ["pbs_first", "pbs_second"]+++async def test_a_second_session_does_not_strand_the_first_sessions_attach_count(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A count left behind by an unreleased session reads as a live sibling turn forever, so every+ later turn on that session would skip its own release."""+ first, second = MagicMock(), MagicMock()+ manager = _release_manager()+ states = {"pbs_first": first, "pbs_second": second}+ manager.get_browser_state = AsyncMock(side_effect=lambda session_id, *a, **k: states[session_id])++ async def _attach_a_second_session(ctx: runtime.AgentContext) -> None:+ ctx.browser_session_id = "pbs_second"+ await runtime.resolve_browser_state_for_context(ctx, session_id="pbs_second")++ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ session_id="pbs_first",+ browser_state=first,+ on_attached=_attach_a_second_session,+ )+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}++ later = _release_manager()+ later.get_browser_state = AsyncMock(return_value=first)+ await run_turn_to_exit(monkeypatch, manager=later, exit_path="normal", session_id="pbs_first", browser_state=first)++ later.evict_cached_browser_state.assert_awaited_once()+++async def test_the_last_turn_out_retires_the_generation_the_pod_now_caches(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A sibling turn that attached a replacement generation and exited first leaves this turn+ holding a superseded state, and evicting that one would cache the live driver for good."""+ superseded, replacement = MagicMock(), MagicMock()+ manager = _release_manager()++ await run_concurrent_turns_on_one_session(+ monkeypatch, manager=manager, browser_states=(superseded, replacement), exit_order=(1, 0)+ )++ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_turn", "org-1", expected=replacement, detach_remote_driver=True, only_if_unleased=True+ )+++async def test_a_resolve_abandoned_by_a_cancel_releases_the_driver_it_landed_on(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The lookup is shielded, so a cancelled turn leaves it running and it caches a driver the+ turn's finalizer never saw recorded."""+ attached = MagicMock()+ resolving, evicted = asyncio.Event(), asyncio.Event()++ async def _slow_resolve(**_kwargs: object) -> MagicMock:+ resolving.set()+ await asyncio.sleep(0.05)+ return attached++ async def _evict(*_args: object, **_kwargs: object) -> bool:+ evicted.set()+ return True++ manager = _release_manager(evict=AsyncMock(side_effect=_evict))+ turn = asyncio.ensure_future(+ run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=attached,+ get_browser_state=AsyncMock(side_effect=_slow_resolve),+ )+ )+ await resolving.wait()+ turn.cancel()+ await turn++ await asyncio.wait_for(evicted.wait(), timeout=2)+ manager.evict_cached_browser_state.assert_awaited_once_with(+ "pbs_turn", "org-1", expected=attached, detach_remote_driver=True, only_if_unleased=True+ )+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}++[email protected]("lookup_already_in_flight", [False, True])+async def test_a_turn_attaching_while_the_last_release_is_in_flight_ends_on_a_live_generation(+ monkeypatch: pytest.MonkeyPatch, lookup_already_in_flight: bool+) -> None:+ """A lookup that answers with the generation an evict is retiring hands the new turn a driver+ whose next operation is refused as session_ending, which closes the user's session."""+ retiring, reconnected = MagicMock(name="retiring"), MagicMock(name="reconnected")+ manager = _release_manager()++ await run_turn_attaching_during_release(+ monkeypatch,+ manager=manager,+ browser_states=(retiring, reconnected),+ lookup_already_in_flight=lookup_already_in_flight,+ )++ evicted = [call.kwargs["expected"] for call in manager.evict_cached_browser_state.await_args_list]+ assert evicted == [retiring, reconnected]+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}+ assert runtime._DRIVER_RELEASES_IN_FLIGHT == {}+++async def test_a_cancel_mid_cleanup_still_hands_back_every_session_the_turn_attached(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Releasing one session at a time lets the cancel that lands on the first one skip the rest,+ stranding their drivers for the life of the pod."""+ evicting, both_detached = asyncio.Event(), asyncio.Event()+ detached: list[str] = []++ async def _slow_evict(session_id: str, *_args: object, **_kwargs: object) -> bool:+ evicting.set()+ await asyncio.sleep(0.05)+ detached.append(session_id)+ if len(detached) == 2:+ both_detached.set()+ return True++ async def _attach_a_second_session(ctx: runtime.AgentContext) -> None:+ await runtime.resolve_browser_state_for_context(ctx, session_id="pbs_second")++ _result, raised = await run_turn_cancelled_during_cleanup(+ monkeypatch,+ manager=_release_manager(evict=AsyncMock(side_effect=_slow_evict)),+ browser_state=MagicMock(),+ evicting=evicting,+ on_attached=_attach_a_second_session,+ )++ assert isinstance(raised, asyncio.CancelledError)+ await asyncio.wait_for(both_detached.wait(), timeout=2)+ assert sorted(detached) == ["pbs_second", "pbs_turn"]+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}+++async def test_a_release_that_outlives_its_wait_still_holds_off_the_next_attach(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The manager's own detach bound is longer than the turn's wait, so a lookup admitted after the+ wait gives up but before the evict pops the entry would be handed the retiring generation."""+ retiring, reconnected = MagicMock(name="retiring"), MagicMock(name="reconnected")+ evict_may_finish, evicted = asyncio.Event(), asyncio.Event()+ monkeypatch.setattr(runtime, "_SESSION_CLEANUP_TIMEOUT_SECONDS", 0.05)++ async def _slow_evict(*_args: object, **_kwargs: object) -> bool:+ if not evicted.is_set():+ await evict_may_finish.wait()+ evicted.set()+ return True++ async def _current_generation(**_kwargs: object) -> MagicMock:+ return reconnected if evicted.is_set() else retiring++ manager = _release_manager(evict=AsyncMock(side_effect=_slow_evict))+ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=retiring,+ get_browser_state=AsyncMock(side_effect=_current_generation),+ )+ assert "pbs_turn" in runtime._DRIVER_RELEASES_IN_FLIGHT++ second = asyncio.ensure_future(+ run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="normal",+ browser_state=reconnected,+ get_browser_state=AsyncMock(side_effect=_current_generation),+ )+ )+ await asyncio.sleep(0.05)+ assert not second.done()+ evict_may_finish.set()+ await asyncio.wait_for(second, 5)++ evicted_generations = [call.kwargs["expected"] for call in manager.evict_cached_browser_state.await_args_list]+ assert evicted_generations == [retiring, reconnected]+ assert runtime._DRIVER_RELEASES_IN_FLIGHT == {}+++async def test_a_manager_that_rejects_the_release_call_outright_neither_masks_the_turn_nor_blocks_the_next(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A synchronous raise (a manager without the newer keyword) happens before any evict task+ exists; it must be logged like any other failed release and must never leave a marker that+ every later resolve of the session would wait on forever."""+ manager = _release_manager()+ manager.evict_cached_browser_state = MagicMock(side_effect=TypeError("unexpected keyword argument"))++ with capture_logs() as logs:+ result, _ = await run_turn_to_exit(monkeypatch, manager=manager, exit_path="normal", browser_state=MagicMock())++ assert result is not None+ assert result.turn_outcome.terminal_reason == _TURN_EXIT_TERMINAL_REASONS["normal"]+ assert [log["error_type"] for log in logs if log["event"] == "Failed to release browser driver"] == ["TypeError"]+ assert runtime._DRIVER_RELEASES_IN_FLIGHT == {}++ later = _release_manager()+ await asyncio.wait_for(+ run_turn_to_exit(monkeypatch, manager=later, exit_path="normal", browser_state=MagicMock()), 5+ )+ later.evict_cached_browser_state.assert_awaited_once()+++async def test_a_cancel_landing_on_the_finalizers_own_await_still_hands_back_the_ledger(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A release created inside the awaited gather is cancelled before its first line when the+ cancel lands there, so the attach count never comes down and every later turn on the session+ skips its own release."""+ from skyvern.forge.sdk.copilot import agent as copilot_agent++ manager = _release_manager()+ real_finalize = copilot_agent.finalize_outcome_verification_trace++ def _finalize_then_cancel(*args: object, **kwargs: object) -> None:+ real_finalize(*args, **kwargs)+ task = asyncio.current_task()+ assert task is not None+ task.cancel()++ monkeypatch.setattr(copilot_agent, "finalize_outcome_verification_trace", _finalize_then_cancel)++ _, raised = await run_turn_to_exit(monkeypatch, manager=manager, exit_path="normal", browser_state=MagicMock())+ for _ in range(3):+ await asyncio.sleep(0)++ assert isinstance(raised, asyncio.CancelledError)+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}+ manager.evict_cached_browser_state.assert_awaited_once()+++async def test_a_release_on_another_session_does_not_reissue_an_overlapping_lookup(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """On a busy pod, steady turn exits on other sessions would otherwise re-issue every slow+ attach in flight and leave it without a bound."""+ other_released = asyncio.Event()+ lookups = 0++ async def _slow_lookup(**_kwargs: object) -> MagicMock:+ nonlocal lookups+ lookups += 1+ await asyncio.wait_for(other_released.wait(), 5)+ return MagicMock(name="pbs_slow generation")++ slow_manager = _release_manager()+ slow_manager.get_browser_state = AsyncMock(side_effect=_slow_lookup)+ mock_app = MagicMock()+ mock_app.PERSISTENT_SESSIONS_MANAGER = slow_manager+ monkeypatch.setattr(runtime, "app", mock_app)++ slow = asyncio.ensure_future(+ runtime.resolve_persistent_browser_state(session_id="pbs_slow", organization_id="org-1")+ )+ await asyncio.sleep(0)+ other = runtime.AttachedBrowserDriver("pbs_other", MagicMock())+ runtime._hold_attached_browser_driver("pbs_other", other.browser_state, new_holder=True)+ await runtime.release_browser_driver_quietly("org-1", other)+ other_released.set()++ assert await asyncio.wait_for(slow, 5) is not None+ assert lookups == 1++[email protected]("unwind_seconds", [0.02, 2.0], ids=["unwinds_within_the_bound", "outlives_the_bound"])+async def test_a_release_refused_for_the_turns_own_unwinding_operation_waits_it_out(+ monkeypatch: pytest.MonkeyPatch, unwind_seconds: float+) -> None:+ """A cancelled turn's tool task can still be inside its admitted operation when the finalizer+ runs. Taking the manager's refusal as done would leave the driver cached for the session's life,+ and an unwind slower than the turn's cleanup bound must delay the release, not the turn."""+ monkeypatch.setattr(runtime, "_SESSION_CLEANUP_TIMEOUT_SECONDS", 0.05)+ admitted: set[asyncio.Task[object]] = set()+ let_tool_finish = asyncio.Event()+ tool_entered = asyncio.Event()+ attached = MagicMock()+ attached.browser_context = _FakeBrowserContext()++ @asynccontextmanager+ async def _operation(_session_id: str, browser_state: Any) -> AsyncIterator[BrowserOperation]:+ task = asyncio.current_task()+ assert task is not None+ admitted.add(task)+ try:+ yield BrowserOperation(browser_state, BrowserRetirement())+ finally:+ admitted.discard(task)++ async def _evict_only_if_unleased(*_args: object, **_kwargs: object) -> bool:+ return not admitted++ manager = _release_manager(evict=AsyncMock(side_effect=_evict_only_if_unleased))+ manager.browser_operation = _operation+ monkeypatch.setattr(runtime, "get_skyvern", lambda: MagicMock())+ monkeypatch.setattr(runtime, "SkyvernBrowser", lambda *_a, **_kw: MagicMock(workflow_run_id=None))+ monkeypatch.setattr(runtime, "set_api_key_override", lambda _key: object())+ monkeypatch.setattr(runtime, "reset_api_key_override", lambda _token: None)+ monkeypatch.setattr(runtime, "register_copilot_session", MagicMock())+ monkeypatch.setattr(runtime, "unregister_copilot_session", MagicMock())++ async def _tool_call(ctx: runtime.AgentContext) -> None:+ async with mcp_browser_context(ctx):+ tool_entered.set()+ await let_tool_finish.wait()++ tool: asyncio.Task[None] | None = None++ async def _start_tool(ctx: runtime.AgentContext) -> None:+ nonlocal tool+ tool = asyncio.ensure_future(_tool_call(ctx))+ await asyncio.wait_for(tool_entered.wait(), 5)+ asyncio.get_running_loop().call_later(unwind_seconds, let_tool_finish.set)++ refused_while_busy: list[bool] = []+ real_evict = manager.evict_cached_browser_state++ async def _evict_recording_busy(*args: object, **kwargs: object) -> bool:+ refused_while_busy.append(bool(admitted))+ return await real_evict(*args, **kwargs)++ manager.evict_cached_browser_state = AsyncMock(side_effect=_evict_recording_busy)++ with capture_logs() as logs:+ result, _ = await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="cancel",+ browser_state=attached,+ on_attached=_start_tool,+ )+ assert tool is not None+ turn_exited_first = not tool.done()+ await tool+ for _ in range(5):+ await asyncio.sleep(0)++ assert refused_while_busy == [False], "the release evicted while the tool was still admitted"+ if unwind_seconds > 0.05:+ assert turn_exited_first, "the turn's exit waited on the tool past the cleanup bound"++ assert result is not None and result.turn_outcome.terminal_reason == "cancel"+ assert runtime._ATTACHED_TURNS_PER_SESSION == {}+ released = [log["had_cached_driver"] for log in logs if log["event"] == "copilot_browser_driver_released"]+ assert released == [True]+++async def test_a_wedged_operation_on_one_session_does_not_hold_another_sessions_release(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Waiting on a turn-wide operation set would let a stuck tool on session A strand session B's+ driver for the pod's life."""+ monkeypatch.setattr(runtime, "_SESSION_CLEANUP_TIMEOUT_SECONDS", 0.05)+ wedged = asyncio.Event()+ tool_entered = asyncio.Event()+ first, second = MagicMock(name="first"), MagicMock(name="second")+ for state in (first, second):+ state.browser_context = _FakeBrowserContext()+ states = {"pbs_first": first, "pbs_second": second}++ @asynccontextmanager+ async def _operation(_session_id: str, browser_state: Any) -> AsyncIterator[BrowserOperation]:+ yield BrowserOperation(browser_state, BrowserRetirement())++ manager = _release_manager()+ manager.browser_operation = _operation+ manager.get_browser_state = AsyncMock(side_effect=lambda session_id, *a, **k: states[session_id])+ monkeypatch.setattr(runtime, "get_skyvern", lambda: MagicMock())+ monkeypatch.setattr(runtime, "SkyvernBrowser", lambda *_a, **_kw: MagicMock(workflow_run_id=None))+ monkeypatch.setattr(runtime, "set_api_key_override", lambda _key: object())+ monkeypatch.setattr(runtime, "reset_api_key_override", lambda _token: None)+ monkeypatch.setattr(runtime, "register_copilot_session", MagicMock())+ monkeypatch.setattr(runtime, "unregister_copilot_session", MagicMock())++ async def _wedged_tool_on_first(ctx: runtime.AgentContext) -> None:+ async with mcp_browser_context(ctx):+ tool_entered.set()+ await wedged.wait()++ tool: asyncio.Task[None] | None = None++ async def _attach_second_and_wedge_first(ctx: runtime.AgentContext) -> None:+ nonlocal tool+ tool = asyncio.ensure_future(_wedged_tool_on_first(ctx))+ await asyncio.wait_for(tool_entered.wait(), 5)+ ctx.browser_session_id = "pbs_second"+ await runtime.resolve_browser_state_for_context(ctx, session_id="pbs_second")++ await run_turn_to_exit(+ monkeypatch,+ manager=manager,+ exit_path="cancel",+ session_id="pbs_first",+ browser_state=first,+ on_attached=_attach_second_and_wedge_first,+ )+ for _ in range(5):+ await asyncio.sleep(0)++ released = [call.args[0] for call in manager.evict_cached_browser_state.await_args_list]+ assert released == ["pbs_second"], "the idle session waited on the other session's stuck tool"++ wedged.set()+ assert tool is not None+ await tool+ for _ in range(5):+ await asyncio.sleep(0)+ released = [call.args[0] for call in manager.evict_cached_browser_state.await_args_list]+ assert sorted(released) == ["pbs_first", "pbs_second"]diff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.pyindex 2889b035b..cd09c9fec 100644--- a/tests/unit/test_copilot_watchdog.py+++ b/tests/unit/test_copilot_watchdog.py@@ -281,7 +281,10 @@ async def test_fallback_page_info_uses_persistent_session_state_without_sdk_recomonkeypatch.setattr(forge_app, "PERSISTENT_SESSIONS_MANAGER", session_manager)ctx = SimpleNamespace(- organization_id="o_test", browser_session_id="pbs_copilot", turn_origin=TurnOrigin.interactive+ organization_id="o_test",+ browser_session_id="pbs_copilot",+ turn_origin=TurnOrigin.interactive,+ attached_browser_drivers={},)current_url, page_title = await _fallback_page_info(ctx)@@ -315,7 +318,10 @@ async def test_fallback_page_info_bounds_a_title_that_never_resolves_and_keeps_tmonkeypatch.setattr(_shared, "_DISCOVERY_PER_CALL_TIMEOUT_SECONDS", 0.05)ctx = SimpleNamespace(- organization_id="o_test", browser_session_id="pbs_copilot", turn_origin=TurnOrigin.interactive+ organization_id="o_test",+ browser_session_id="pbs_copilot",+ turn_origin=TurnOrigin.interactive,+ attached_browser_drivers={},)current_url, page_title = await asyncio.wait_for(_fallback_page_info(ctx), timeout=5)diff --git a/tests/unit/test_default_persistent_sessions_manager_evict.py b/tests/unit/test_default_persistent_sessions_manager_evict.pyindex e6e8ccd78..9c047162c 100644--- a/tests/unit/test_default_persistent_sessions_manager_evict.py+++ b/tests/unit/test_default_persistent_sessions_manager_evict.py@@ -149,3 +149,64 @@ async def test_cache_transition_retires_the_active_generation(assert "pbs_local" not in manager._browser_sessionselse:assert manager._browser_sessions["pbs_local"].browser_state is fresh_state+++async def test_evict_reports_whether_a_live_entry_was_dropped(+ manager: DefaultPersistentSessionsManager,+) -> None:+ browser_state = MagicMock()+ browser_state.detach_remote_driver = AsyncMock()+ manager._browser_sessions["pbs_local"] = BrowserSession(browser_state=browser_state)++ assert (+ await manager.evict_cached_browser_state(+ "pbs_local", "org_local", expected=browser_state, detach_remote_driver=True+ )+ is True+ )+ assert await manager.evict_cached_browser_state("pbs_local", "org_local", detach_remote_driver=True) is False++ manager._browser_sessions["pbs_local"] = BrowserSession(browser_state=browser_state)++ assert (+ await manager.evict_cached_browser_state(+ "pbs_local", "org_local", expected=MagicMock(), detach_remote_driver=True+ )+ is False+ )+ assert "pbs_local" in manager._browser_sessions+++async def test_idle_only_evict_leaves_a_generation_a_concurrent_operation_is_driving(+ manager: DefaultPersistentSessionsManager,+) -> None:+ browser_state = MagicMock()+ browser_state.detach_remote_driver = AsyncMock()+ manager._browser_sessions["pbs_local"] = BrowserSession(browser_state=browser_state)+ entered = asyncio.Event()+ release = asyncio.Event()++ async def _hold() -> str:+ async with manager.browser_operation("pbs_local", browser_state) as operation:+ if isinstance(operation, BrowserOperationRejected):+ return "rejected"+ entered.set()+ await release.wait()+ return "completed"++ holder = asyncio.ensure_future(_hold())+ await entered.wait()++ assert (+ await manager.evict_cached_browser_state(+ "pbs_local", "org_local", expected=browser_state, detach_remote_driver=True, only_if_unleased=True+ )+ is False+ )+ release.set()++ assert await holder == "completed"+ assert manager._browser_sessions["pbs_local"].browser_state is browser_state+ browser_state.detach_remote_driver.assert_not_awaited()