Skip to content

Automate browser based workflows with AI

fix(SKY-9803): inject tab context into extract-action prompt for safe CLOSE_PAGE (#6074)

LawyZheng2d77f97066c0
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 1a691bb78..38c9434e6 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -299,6 +299,35 @@ def _schedule_summary_shadow_check_for_hit(
)
+async def _build_open_tabs_context(
+ browser_state: BrowserState,
+ working_page: Page | None,
+) -> str | None:
+ if working_page is None:
+ return None
+ pages = await browser_state.list_valid_pages()
+ if len(pages) <= 1:
+ return None
+ lines: list[str] = []
+ for i, p in enumerate(pages):
+ marker = " [current]" if p == working_page else ""
+ url = p.url
+ try:
+ title = await asyncio.wait_for(p.title(), timeout=1.0)
+ except Exception:
+ LOG.debug("tab_title_fetch_failed", url=url)
+ title = ""
+ if len(url) > 120:
+ url = url[:117] + "..."
+ if len(title) > 80:
+ title = title[:77] + "..."
+ entry = f"Tab {i}{marker}: {url}"
+ if title:
+ entry += f" ({title})"
+ lines.append(entry)
+ return "\n".join(lines)
+
+
def _build_totp_timeout_reasoning(task: Task) -> str:
# Mirror poll_otp_value's URL-then-identifier precedence so we only report the
# source that was actually queried. URL goes through strip_query_params to keep
@@ -3245,19 +3274,19 @@ class ForgeAgent:
@staticmethod
def _build_extract_action_cache_variant(
verification_code_check: bool,
- has_magic_link_page: bool,
+ show_close_page_action: bool,
complete_criterion: str | None,
) -> str:
"""
Build a short-but-unique cache variant identifier so extract-action prompts that
- differ meaningfully (OTP, magic link flows, complete criteria) do not reuse the
- same Vertex cache object.
+ differ meaningfully (OTP, close-page availability, complete criteria) do not reuse
+ the same Vertex cache object.
"""
variant_parts: list[str] = []
if verification_code_check:
variant_parts.append("vc")
- if has_magic_link_page:
- variant_parts.append("ml")
+ if show_close_page_action:
+ variant_parts.append("cp")
if complete_criterion:
normalized = " ".join(complete_criterion.split())
digest = hashlib.sha256(normalized.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
@@ -3527,6 +3556,9 @@ class ForgeAgent:
else:
elements_for_prompt = scraped_page.build_element_tree(element_tree_format)
+ open_tabs_context = await _build_open_tabs_context(browser_state, page)
+ show_close_page_action = open_tabs_context is not None
+
# Format-then-clear so a render failure can't drop the signal permanently;
# gate on extract-action template since other task types don't render it.
recent_dialog_messages_str = (
@@ -3550,12 +3582,13 @@ class ForgeAgent:
"verification_code_check": verification_code_check,
"complete_criterion": task.complete_criterion.strip() if task.complete_criterion else None,
"terminate_criterion": task.terminate_criterion.strip() if task.terminate_criterion else None,
- "has_magic_link_page": context.has_magic_link_page(task.task_id),
+ "show_close_page_action": show_close_page_action,
+ "open_tabs_context": open_tabs_context,
"recent_dialog_messages_str": recent_dialog_messages_str,
}
cache_variant = self._build_extract_action_cache_variant(
verification_code_check=verification_code_check,
- has_magic_link_page=context.has_magic_link_page(task.task_id),
+ show_close_page_action=show_close_page_action,
complete_criterion=task.complete_criterion.strip() if task.complete_criterion else None,
)
static_prompt = prompt_engine.load_prompt(f"{template}-static", **prompt_kwargs)
@@ -3641,7 +3674,8 @@ class ForgeAgent:
verification_code_check=verification_code_check,
complete_criterion=task.complete_criterion.strip() if task.complete_criterion else None,
terminate_criterion=task.terminate_criterion.strip() if task.terminate_criterion else None,
- has_magic_link_page=context.has_magic_link_page(task.task_id),
+ show_close_page_action=show_close_page_action,
+ open_tabs_context=open_tabs_context,
recent_dialog_messages_str=recent_dialog_messages_str,
# SKY-9718 Layer 1: planner non-cached fallback. Keep Skyvern IDs
# (default html_need_skyvern_attrs=True) — the planner emits
diff --git a/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2 b/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2
index 28cd8a825..b8c4a8cc2 100644
--- a/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2
+++ b/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2
@@ -34,6 +34,12 @@ User details:
{{ navigation_payload_str }}
```
+{% if open_tabs_context %}
+Open browser tabs (CLOSE_PAGE always closes the tab marked [current] — other tabs are shown for context only):
+```
+{{ open_tabs_context }}
+```
+{% endif %}
Clickable elements from `{{ current_url }}`:
```
{{ elements }}
diff --git a/skyvern/forge/prompts/skyvern/extract-action-static.j2 b/skyvern/forge/prompts/skyvern/extract-action-static.j2
index 094091fca..2b2a7aa7d 100644
--- a/skyvern/forge/prompts/skyvern/extract-action-static.j2
+++ b/skyvern/forge/prompts/skyvern/extract-action-static.j2
@@ -18,7 +18,7 @@ Reply in JSON format with the following keys:
"user_detail_query": str, // Think of this value as a Jeopardy question and the intention behind the action. Ask the user for the details you need for executing this action. IMPORTANT: This question must be user information agnostic and must NOT contain specific user data (like names, IDs, specific values, etc.). Ask what information is needed generically. Ask the question even if the details are disclosed in user goal or user details. If it's a text field, ask for the text. If it's a file upload, ask for the file. If it's a dropdown, ask for the relevant information. If you are clicking on something specific, ask about what the intention is behind the click and what to click on. If you're downloading a file and you have multiple options, ask the user which one to download. Examples are: "What product ID should I input into the search bar?", "What file should I upload?", "What is the previous insurance provider of the user?", "Which invoice should I download?", "Does the user have any pets?", "Which member should I take action on?". NEVER include specific user data in this question - keep it generic so it can be answered with different user contexts.
"user_detail_answer": str, // The answer to the `user_detail_query`. The source of this answer can be user goal or user details. This answer CAN contain specific user data.
"confidence_float": float, // The confidence of the action. Pick a number between 0.0 and 1.0. 0.0 means no confidence, 1.0 means full confidence
- "action_type": str, // It's a string enum: "CLICK", "HOVER", "INPUT_TEXT", "UPLOAD_FILE", "SELECT_OPTION", "WAIT", "SOLVE_CAPTCHA", "COMPLETE", "TERMINATE", "KEYPRESS", "SCROLL"{{', "CLOSE_PAGE"' if has_magic_link_page else ""}}. "CLICK" is an element you'd like to click. "HOVER" is used to move the mouse over an element without clicking, particularly when revealing hover-only menus or buttons before clicking, or when the UI hints that a control (like a CTA button) only appears after hovering a card, tile, or model name. "INPUT_TEXT" is an element you'd like to input text into. "UPLOAD_FILE" is an element you'd like to upload a file into. "SELECT_OPTION" is an element you'd like to select an option from. "WAIT" action should be used if there are no actions to take and there is some indication on screen that waiting could yield more actions. "WAIT" should not be used if there are actions to take. "SOLVE_CAPTCHA" should be used if there's a captcha to solve on the screen. "COMPLETE" is used when the {{"complete criterion has been met" if complete_criterion else "user goal has been achieved"}} AND if there's any data extraction goal, you should be able to get data from the page. Never return a COMPLETE action unless the {{ "complete criterion is met" if complete_criterion else "user goal is achieved" }}. "TERMINATE" is used to terminate the whole task with a failure when it doesn't seem like the user goal can be achieved. Do not use "TERMINATE" if waiting could lead the user towards the goal. Only return "TERMINATE" if you are on a page where the user goal cannot be achieved. All other actions are ignored when "TERMINATE" is returned. "KEYPRESS" is used to press a keyboard key when no clickable button or element achieves the same result. Only use KEYPRESS when pressing a key is the sole way to proceed (e.g., pressing Enter to submit a search with no search button, or Escape to close a modal with no close button). KEYPRESS does not require an element id. Requires the "key" field. "SCROLL" is used to scroll within a specific scrollable container on the page (not the page itself). Only use SCROLL when a required action is blocked because the target element is hidden, disabled, or unreachable until the container is scrolled (e.g., an "Agree" button that only becomes enabled after scrolling to the bottom of a terms and conditions box). Do not use SCROLL for general page navigation. Provide the element id of an interactable element within or near the scrollable container. Requires the "direction" field. SCROLL does not require a "text", "option", or "file_url" field.{{' "CLOSE_PAGE" is used to close the current page when the page instructs you to close it or return to the original page, OR when it is impossible to achieve the user goal on the current page.' if has_magic_link_page else ''}}
+ "action_type": str, // It's a string enum: "CLICK", "HOVER", "INPUT_TEXT", "UPLOAD_FILE", "SELECT_OPTION", "WAIT", "SOLVE_CAPTCHA", "COMPLETE", "TERMINATE", "KEYPRESS", "SCROLL"{{', "CLOSE_PAGE"' if show_close_page_action else ""}}. "CLICK" is an element you'd like to click. "HOVER" is used to move the mouse over an element without clicking, particularly when revealing hover-only menus or buttons before clicking, or when the UI hints that a control (like a CTA button) only appears after hovering a card, tile, or model name. "INPUT_TEXT" is an element you'd like to input text into. "UPLOAD_FILE" is an element you'd like to upload a file into. "SELECT_OPTION" is an element you'd like to select an option from. "WAIT" action should be used if there are no actions to take and there is some indication on screen that waiting could yield more actions. "WAIT" should not be used if there are actions to take. "SOLVE_CAPTCHA" should be used if there's a captcha to solve on the screen. "COMPLETE" is used when the {{"complete criterion has been met" if complete_criterion else "user goal has been achieved"}} AND if there's any data extraction goal, you should be able to get data from the page. Never return a COMPLETE action unless the {{ "complete criterion is met" if complete_criterion else "user goal is achieved" }}. "TERMINATE" is used to terminate the whole task with a failure when it doesn't seem like the user goal can be achieved. Do not use "TERMINATE" if waiting could lead the user towards the goal. Only return "TERMINATE" if you are on a page where the user goal cannot be achieved. All other actions are ignored when "TERMINATE" is returned. "KEYPRESS" is used to press a keyboard key when no clickable button or element achieves the same result. Only use KEYPRESS when pressing a key is the sole way to proceed (e.g., pressing Enter to submit a search with no search button, or Escape to close a modal with no close button). KEYPRESS does not require an element id. Requires the "key" field. "SCROLL" is used to scroll within a specific scrollable container on the page (not the page itself). Only use SCROLL when a required action is blocked because the target element is hidden, disabled, or unreachable until the container is scrolled (e.g., an "Agree" button that only becomes enabled after scrolling to the bottom of a terms and conditions box). Do not use SCROLL for general page navigation. Provide the element id of an interactable element within or near the scrollable container. Requires the "direction" field. SCROLL does not require a "text", "option", or "file_url" field.{{' "CLOSE_PAGE" is used to close the current tab and return to a previous tab. Use it when the page instructs you to close it or return to the original page, or when the user goal explicitly requires closing this tab. Do not use CLOSE_PAGE simply because the goal cannot be achieved — use TERMINATE for that.' if show_close_page_action else ''}}
"id": str, // The id of the element to take action on. The id has to be one from the elements list. For target-less actions (SOLVE_CAPTCHA, WAIT, COMPLETE, TERMINATE, KEYPRESS), set this to null.
"captcha_type": str, // The type of captcha for SOLVE_CAPTCHA action only. null if not SOLVE_CAPTCHA action. It's a string enum: "TEXT_CAPTCHA", "RECAPTCHA", "HCAPTCHA", "MTCAPTCHA", "FUNCAPTCHA", "CLOUDFLARE", "OTHER".
"text": str, // Text for INPUT_TEXT action only
diff --git a/skyvern/forge/prompts/skyvern/extract-action.j2 b/skyvern/forge/prompts/skyvern/extract-action.j2
index f2dca46d9..20c21578f 100644
--- a/skyvern/forge/prompts/skyvern/extract-action.j2
+++ b/skyvern/forge/prompts/skyvern/extract-action.j2
@@ -18,7 +18,7 @@ Reply in JSON format with the following keys:
"user_detail_query": str, // Think of this value as a Jeopardy question and the intention behind the action. Ask the user for the details you need for executing this action. IMPORTANT: This question must be user information agnostic and must NOT contain specific user data (like names, IDs, specific values, etc.). Ask what information is needed generically. Ask the question even if the details are disclosed in user goal or user details. If it's a text field, ask for the text. If it's a file upload, ask for the file. If it's a dropdown, ask for the relevant information. If you are clicking on something specific, ask about what the intention is behind the click and what to click on. If you're downloading a file and you have multiple options, ask the user which one to download. Examples are: "What product ID should I input into the search bar?", "What file should I upload?", "What is the previous insurance provider of the user?", "Which invoice should I download?", "Does the user have any pets?", "Which member should I take action on?". NEVER include specific user data in this question - keep it generic so it can be answered with different user contexts.
"user_detail_answer": str, // The answer to the `user_detail_query`. The source of this answer can be user goal or user details. This answer CAN contain specific user data.
"confidence_float": float, // The confidence of the action. Pick a number between 0.0 and 1.0. 0.0 means no confidence, 1.0 means full confidence
- "action_type": str, // It's a string enum: "CLICK", "HOVER", "INPUT_TEXT", "UPLOAD_FILE", "SELECT_OPTION", "WAIT", "SOLVE_CAPTCHA", "COMPLETE", "TERMINATE", "KEYPRESS", "SCROLL"{{', "CLOSE_PAGE"' if has_magic_link_page else ""}}. "CLICK" is an element you'd like to click. "HOVER" is used to move the mouse over an element without clicking, particularly when revealing hover-only menus or buttons before clicking, or when the UI hints that a control (like a CTA button) only appears after hovering a card, tile, or model name. "INPUT_TEXT" is an element you'd like to input text into. "UPLOAD_FILE" is an element you'd like to upload a file into. "SELECT_OPTION" is an element you'd like to select an option from. "WAIT" action should be used if there are no actions to take and there is some indication on screen that waiting could yield more actions. "WAIT" should not be used if there are actions to take. "SOLVE_CAPTCHA" should be used if there's a captcha to solve on the screen. "COMPLETE" is used when the {{"complete criterion has been met" if complete_criterion else "user goal has been achieved"}} AND if there's any data extraction goal, you should be able to get data from the page. Never return a COMPLETE action unless the {{ "complete criterion is met" if complete_criterion else "user goal is achieved" }}. "TERMINATE" is used to terminate the whole task with a failure when it doesn't seem like the user goal can be achieved. Do not use "TERMINATE" if waiting could lead the user towards the goal. Only return "TERMINATE" if you are on a page where the user goal cannot be achieved. All other actions are ignored when "TERMINATE" is returned. "KEYPRESS" is used to press a keyboard key when no clickable button or element achieves the same result. Only use KEYPRESS when pressing a key is the sole way to proceed (e.g., pressing Enter to submit a search with no search button, or Escape to close a modal with no close button). KEYPRESS does not require an element id. Requires the "key" field. "SCROLL" is used to scroll within a specific scrollable container on the page (not the page itself). Only use SCROLL when a required action is blocked because the target element is hidden, disabled, or unreachable until the container is scrolled (e.g., an "Agree" button that only becomes enabled after scrolling to the bottom of a terms and conditions box). Do not use SCROLL for general page navigation. Provide the element id of an interactable element within or near the scrollable container. Requires the "direction" field. SCROLL does not require a "text", "option", or "file_url" field.{{' "CLOSE_PAGE" is used to close the current page when the page instructs you to close it or return to the original page, OR when it is impossible to achieve the user goal on the current page.' if has_magic_link_page else ''}}
+ "action_type": str, // It's a string enum: "CLICK", "HOVER", "INPUT_TEXT", "UPLOAD_FILE", "SELECT_OPTION", "WAIT", "SOLVE_CAPTCHA", "COMPLETE", "TERMINATE", "KEYPRESS", "SCROLL"{{', "CLOSE_PAGE"' if show_close_page_action else ""}}. "CLICK" is an element you'd like to click. "HOVER" is used to move the mouse over an element without clicking, particularly when revealing hover-only menus or buttons before clicking, or when the UI hints that a control (like a CTA button) only appears after hovering a card, tile, or model name. "INPUT_TEXT" is an element you'd like to input text into. "UPLOAD_FILE" is an element you'd like to upload a file into. "SELECT_OPTION" is an element you'd like to select an option from. "WAIT" action should be used if there are no actions to take and there is some indication on screen that waiting could yield more actions. "WAIT" should not be used if there are actions to take. "SOLVE_CAPTCHA" should be used if there's a captcha to solve on the screen. "COMPLETE" is used when the {{"complete criterion has been met" if complete_criterion else "user goal has been achieved"}} AND if there's any data extraction goal, you should be able to get data from the page. Never return a COMPLETE action unless the {{ "complete criterion is met" if complete_criterion else "user goal is achieved" }}. "TERMINATE" is used to terminate the whole task with a failure when it doesn't seem like the user goal can be achieved. Do not use "TERMINATE" if waiting could lead the user towards the goal. Only return "TERMINATE" if you are on a page where the user goal cannot be achieved. All other actions are ignored when "TERMINATE" is returned. "KEYPRESS" is used to press a keyboard key when no clickable button or element achieves the same result. Only use KEYPRESS when pressing a key is the sole way to proceed (e.g., pressing Enter to submit a search with no search button, or Escape to close a modal with no close button). KEYPRESS does not require an element id. Requires the "key" field. "SCROLL" is used to scroll within a specific scrollable container on the page (not the page itself). Only use SCROLL when a required action is blocked because the target element is hidden, disabled, or unreachable until the container is scrolled (e.g., an "Agree" button that only becomes enabled after scrolling to the bottom of a terms and conditions box). Do not use SCROLL for general page navigation. Provide the element id of an interactable element within or near the scrollable container. Requires the "direction" field. SCROLL does not require a "text", "option", or "file_url" field.{{' "CLOSE_PAGE" is used to close the current tab and return to a previous tab. Use it when the page instructs you to close it or return to the original page, or when the user goal explicitly requires closing this tab. Do not use CLOSE_PAGE simply because the goal cannot be achieved — use TERMINATE for that.' if show_close_page_action else ''}}
"id": str, // The id of the element to take action on. The id has to be one from the elements list. For target-less actions (SOLVE_CAPTCHA, WAIT, COMPLETE, TERMINATE, KEYPRESS), set this to null.
"captcha_type": str, // The type of captcha for SOLVE_CAPTCHA action only. null if not SOLVE_CAPTCHA action. It's a string enum: "TEXT_CAPTCHA", "RECAPTCHA", "HCAPTCHA", "MTCAPTCHA", "FUNCAPTCHA", "CLOUDFLARE", "OTHER".
"text": str, // Text for INPUT_TEXT action only
@@ -90,6 +90,12 @@ User details:
{{ navigation_payload_str }}
```
+{% if open_tabs_context %}
+Open browser tabs (CLOSE_PAGE always closes the tab marked [current] — other tabs are shown for context only):
+```
+{{ open_tabs_context }}
+```
+{% endif %}
Clickable elements from `{{ current_url }}`:
```
{{ elements }}
diff --git a/tests/unit/test_extract_action_dialog_messages_render.py b/tests/unit/test_extract_action_dialog_messages_render.py
index f4ee38177..89b551c13 100644
--- a/tests/unit/test_extract_action_dialog_messages_render.py
+++ b/tests/unit/test_extract_action_dialog_messages_render.py
@@ -18,7 +18,8 @@ _BASE_KWARGS: dict[str, Any] = {
"verification_code_check": False,
"complete_criterion": None,
"terminate_criterion": None,
- "has_magic_link_page": False,
+ "show_close_page_action": False,
+ "open_tabs_context": None,
"elements": "<html></html>",
}
diff --git a/tests/unit/test_extract_action_open_tabs_context.py b/tests/unit/test_extract_action_open_tabs_context.py
new file mode 100644
index 000000000..057730f7e
--- /dev/null
+++ b/tests/unit/test_extract_action_open_tabs_context.py
@@ -0,0 +1,230 @@
+"""Tests for the open-tabs context section and CLOSE_PAGE gate in extract-action prompts."""
+
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.forge.agent import ForgeAgent, _build_open_tabs_context
+from skyvern.forge.prompts import prompt_engine
+
+_BASE_KWARGS: dict[str, Any] = {
+ "navigation_goal": "close the stuck tab and continue",
+ "navigation_payload_str": "{}",
+ "starting_url": "https://example.test/start",
+ "current_url": "https://example.test/form",
+ "data_extraction_goal": None,
+ "action_history": "[]",
+ "error_code_mapping_str": None,
+ "local_datetime": "2026-05-14T00:00:00Z",
+ "verification_code_check": False,
+ "complete_criterion": None,
+ "terminate_criterion": None,
+ "recent_dialog_messages_str": None,
+ "elements": "<html></html>",
+}
+
+
+class TestClosePageGate:
+ @pytest.mark.parametrize("template", ["extract-action", "extract-action-static"])
+ def test_close_page_shown_when_enabled(self, template: str) -> None:
+ rendered = prompt_engine.load_prompt(
+ template,
+ show_close_page_action=True,
+ open_tabs_context="Tab 0: https://a.test\nTab 1 [current]: https://b.test",
+ **_BASE_KWARGS,
+ )
+ assert '"CLOSE_PAGE"' in rendered
+ assert "close the current tab" in rendered.lower()
+
+ @pytest.mark.parametrize("template", ["extract-action", "extract-action-static"])
+ def test_no_close_page_without_tab_context(self, template: str) -> None:
+ """Magic-link-only scenario: CLOSE_PAGE should NOT appear without tab context.
+ Magic-link auto-close is handled by the post-step fallback, not by the prompt."""
+ rendered = prompt_engine.load_prompt(
+ template,
+ show_close_page_action=False,
+ open_tabs_context=None,
+ **_BASE_KWARGS,
+ )
+ assert '"CLOSE_PAGE"' not in rendered
+
+ @pytest.mark.parametrize("template", ["extract-action", "extract-action-static"])
+ def test_no_close_page_when_disabled(self, template: str) -> None:
+ rendered = prompt_engine.load_prompt(
+ template,
+ show_close_page_action=False,
+ open_tabs_context=None,
+ **_BASE_KWARGS,
+ )
+ assert '"CLOSE_PAGE"' not in rendered
+
+
+class TestOpenTabsContextSection:
+ @pytest.mark.parametrize("template", ["extract-action", "extract-action-dynamic"])
+ def test_renders_tab_listing_when_context_present(self, template: str) -> None:
+ tab_ctx = "Tab 0: https://main.test (Main Page)\nTab 1 [current]: https://pdf.test/viewer (PDF Viewer)"
+ rendered = prompt_engine.load_prompt(
+ template,
+ show_close_page_action=True,
+ open_tabs_context=tab_ctx,
+ **_BASE_KWARGS,
+ )
+ assert "Open browser tabs" in rendered
+ assert "other tabs are shown for context only" in rendered
+ assert "[current]" in rendered
+ assert "https://main.test" in rendered
+ assert "https://pdf.test/viewer" in rendered
+
+ @pytest.mark.parametrize("template", ["extract-action", "extract-action-dynamic"])
+ def test_omits_tab_listing_when_no_context(self, template: str) -> None:
+ rendered = prompt_engine.load_prompt(
+ template,
+ show_close_page_action=False,
+ open_tabs_context=None,
+ **_BASE_KWARGS,
+ )
+ assert "Open browser tabs" not in rendered
+
+ def test_static_template_omits_tab_listing(self) -> None:
+ rendered = prompt_engine.load_prompt(
+ "extract-action-static",
+ show_close_page_action=True,
+ open_tabs_context="Tab 0: https://a.test\nTab 1 [current]: https://b.test",
+ **_BASE_KWARGS,
+ )
+ assert "Open browser tabs" not in rendered
+
+
+class TestCacheVariant:
+ def test_cp_tag_present_when_close_page_enabled(self) -> None:
+ result = ForgeAgent._build_extract_action_cache_variant(
+ verification_code_check=False,
+ show_close_page_action=True,
+ complete_criterion=None,
+ )
+ assert "cp" in result
+
+ def test_cp_tag_absent_when_close_page_disabled(self) -> None:
+ result = ForgeAgent._build_extract_action_cache_variant(
+ verification_code_check=False,
+ show_close_page_action=False,
+ complete_criterion=None,
+ )
+ assert "cp" not in result
+
+ def test_std_when_no_flags(self) -> None:
+ result = ForgeAgent._build_extract_action_cache_variant(
+ verification_code_check=False,
+ show_close_page_action=False,
+ complete_criterion=None,
+ )
+ assert result == "std"
+
+ def test_vc_and_cp_combined(self) -> None:
+ result = ForgeAgent._build_extract_action_cache_variant(
+ verification_code_check=True,
+ show_close_page_action=True,
+ complete_criterion=None,
+ )
+ assert "vc" in result
+ assert "cp" in result
+
+
+class TestBuildOpenTabsContext:
+ @pytest.mark.asyncio
+ async def test_returns_none_when_working_page_is_none(self) -> None:
+ browser_state = MagicMock()
+ result = await _build_open_tabs_context(browser_state, None)
+ assert result is None
+ browser_state.list_valid_pages.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_returns_none_for_single_tab(self) -> None:
+ page = MagicMock()
+ page.url = "https://example.test"
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[page])
+ result = await _build_open_tabs_context(browser_state, page)
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_returns_formatted_string_for_multiple_tabs(self) -> None:
+ page0 = MagicMock()
+ page0.url = "https://example.test/main"
+ page0.title = AsyncMock(return_value="Main Page")
+
+ page1 = MagicMock()
+ page1.url = "https://example.test/viewer"
+ page1.title = AsyncMock(return_value="PDF Viewer")
+
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
+
+ result = await _build_open_tabs_context(browser_state, page1)
+ assert result is not None
+ assert "Tab 0: https://example.test/main (Main Page)" in result
+ assert "Tab 1 [current]: https://example.test/viewer (PDF Viewer)" in result
+
+ @pytest.mark.asyncio
+ async def test_handles_title_failure_gracefully(self) -> None:
+ page0 = MagicMock()
+ page0.url = "https://example.test/main"
+ page0.title = AsyncMock(side_effect=Exception("page crashed"))
+
+ page1 = MagicMock()
+ page1.url = "https://example.test/viewer"
+ page1.title = AsyncMock(return_value="Viewer")
+
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
+
+ result = await _build_open_tabs_context(browser_state, page1)
+ assert result is not None
+ assert "Tab 0: https://example.test/main" in result
+ assert "(Main Page)" not in result
+ assert "Tab 1 [current]: https://example.test/viewer (Viewer)" in result
+
+ @pytest.mark.asyncio
+ async def test_truncates_long_urls(self) -> None:
+ long_url = "https://example.test/" + "a" * 200
+ page0 = MagicMock()
+ page0.url = long_url
+ page0.title = AsyncMock(return_value="")
+
+ page1 = MagicMock()
+ page1.url = "https://short.test"
+ page1.title = AsyncMock(return_value="")
+
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
+
+ result = await _build_open_tabs_context(browser_state, page1)
+ assert result is not None
+ assert "..." in result
+ for line in result.splitlines():
+ if "Tab 0" in line:
+ url_part = line.split(": ", 1)[1]
+ assert url_part.endswith("...")
+ assert len(url_part) <= 120
+
+ @pytest.mark.asyncio
+ async def test_truncates_long_titles(self) -> None:
+ page0 = MagicMock()
+ page0.url = "https://example.test"
+ page0.title = AsyncMock(return_value="A" * 200)
+
+ page1 = MagicMock()
+ page1.url = "https://short.test"
+ page1.title = AsyncMock(return_value="Short")
+
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
+
+ result = await _build_open_tabs_context(browser_state, page1)
+ assert result is not None
+ assert "..." in result
+ for line in result.splitlines():
+ if "Tab 0" in line:
+ title_part = line.split("(", 1)[1].rstrip(")")
+ assert len(title_part) <= 80
diff --git a/tests/unit/test_extract_actions_ceiling.py b/tests/unit/test_extract_actions_ceiling.py
index bc75b7a0f..a49fc36fb 100644
--- a/tests/unit/test_extract_actions_ceiling.py
+++ b/tests/unit/test_extract_actions_ceiling.py
@@ -34,7 +34,8 @@ def test_extract_action_ceiling_drops_action_history_on_overshoot() -> None:
verification_code_check=False,
complete_criterion=None,
terminate_criterion=None,
- has_magic_link_page=False,
+ show_close_page_action=False,
+ open_tabs_context=None,
)
assert count_tokens(rendered) <= PROMPT_HARD_CEILING_TOKENS
@@ -61,7 +62,8 @@ def test_extract_action_small_prompt_passes_through() -> None:
verification_code_check=False,
complete_criterion=None,
terminate_criterion=None,
- has_magic_link_page=False,
+ show_close_page_action=False,
+ open_tabs_context=None,
)
assert "small history" in rendered