Skip to content

Automate browser based workflows with AI

fix(SKY-11235): honor "keep exactly N tabs" in task_v2 (curate over-opened tabs + planner tab visibility) (#6838)

Trevor Cheung4f5b65ae3585
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 0dd1bf721..793699b87 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -162,7 +162,7 @@ from skyvern.webeye.actions.parse_actions import (
from skyvern.webeye.actions.responses import ActionResult, ActionSuccess
from skyvern.webeye.browser_state import BrowserState
from skyvern.webeye.scraper.scraped_page import ElementTreeFormat, ScrapedPage
-from skyvern.webeye.utils.page import SkyvernFrame
+from skyvern.webeye.utils.page import SkyvernFrame, build_open_tabs_context
LOG = structlog.get_logger()
@@ -336,35 +336,6 @@ async def _cancel_pending_prefetch_task(task: asyncio.Task | None) -> None:
await task
-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
@@ -3849,7 +3820,7 @@ 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)
+ open_tabs_context = await build_open_tabs_context(browser_state, page)
show_close_page_action = open_tabs_context is not None
# NEW_TAB/SWITCH_TAB are gated behind a flag (default off) so single-tab tasks are
# unaffected. SWITCH_TAB additionally requires >= 2 open tabs, like CLOSE_PAGE.
diff --git a/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2 b/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2
index 12136d26c..5b341e308 100644
--- a/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2
+++ b/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2
@@ -35,7 +35,7 @@ User details:
```
{% if open_tabs_context %}
-Open browser tabs ({% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active, and CLOSE_PAGE closes the tab marked [current]{% else %}CLOSE_PAGE always closes the tab marked [current] — other tabs are shown for context only{% endif %}):
+Open browser tabs ({% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active; CLOSE_PAGE closes the tab marked [current], or set its "tab_index" to close a specific tab{% else %}CLOSE_PAGE closes the tab marked [current] by default, or set its "tab_index" to the number of a specific tab to close that one{% endif %}):
```
{{ open_tabs_context }}
```
diff --git a/skyvern/forge/prompts/skyvern/extract-action-static.j2 b/skyvern/forge/prompts/skyvern/extract-action-static.j2
index 6ea7958bc..57363acb2 100644
--- a/skyvern/forge/prompts/skyvern/extract-action-static.j2
+++ b/skyvern/forge/prompts/skyvern/extract-action-static.j2
@@ -21,7 +21,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"{{', "GOTO_URL", "RELOAD_PAGE"' if enable_new_planner_actions else ""}}{{', "EXTRACT_INFORMATION"' if enable_new_planner_actions and data_extraction_goal else ""}}{{', "NEW_TAB"' if show_new_tab_action else ""}}{{', "SWITCH_TAB"' if show_switch_tab_action else ""}}{{', "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 visible captcha to solve on the screen. Captcha tokens expire quickly (~2 minutes), so fill all form fields first, then SOLVE_CAPTCHA immediately before the final submit or protected click — do not place SOLVE_CAPTCHA before a long form-fill sequence. "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.{% if enable_new_planner_actions %} "GOTO_URL" is used to navigate the current tab directly to a fully-qualified http/https URL. Only use GOTO_URL when the user goal requires direct navigation and the exact target URL comes from the user goal, the user details, the page content, or the action history. Do not use GOTO_URL to follow a normal link on the page when a clickable element is available — use CLICK on that element instead. Never invent, guess, or construct website-specific URLs or query parameters that are not explicitly available to you. If the URL of the page you're on right now already matches the target URL (ignoring a trailing slash), do not use GOTO_URL to reload the page. Element ids from the current page become invalid after navigation, so GOTO_URL must be the only action or the last action in the array. GOTO_URL is target-less and requires the "url" field. "RELOAD_PAGE" reloads the current page. Only use RELOAD_PAGE when the page itself is in a broken or stale state that a refresh would fix — content failed to load, a spinner or loading state is stuck, the DOM looks empty or only partially rendered, or the page shows a transient error. Do not use RELOAD_PAGE for normal navigation, and do not use it to retry an action that simply didn't achieve the goal — only when the page itself appears broken. RELOAD_PAGE is target-less and takes no extra fields.{% endif %}{{' "EXTRACT_INFORMATION" is used to extract the information described in the user data extraction goal from the current page. Only use EXTRACT_INFORMATION when the current page already contains the data requested in the data extraction goal and the page state is ready for extraction (fully loaded, filters applied, correct tab or section visible). Extraction runs against the current page state, so never place EXTRACT_INFORMATION after page-changing actions in the same array. If the user goal is also achieved, return COMPLETE right after EXTRACT_INFORMATION in the same array. EXTRACT_INFORMATION is target-less.' if enable_new_planner_actions and data_extraction_goal else ''}}{{' "NEW_TAB" opens a new browser tab at a given URL and makes it the active tab, keeping existing tabs open. Use it to open a page in a separate tab while keeping the current tab open (for example, to compare two pages). NEW_TAB requires the "url" field set to a fully-qualified http/https URL. Do not use NEW_TAB to follow a normal link on the page when a clickable element is available. NEW_TAB does not require an element id.' if show_new_tab_action else ''}}{{' "SWITCH_TAB" makes another already-open tab the active tab so you can see and act on it. SWITCH_TAB requires the "tab_index" field set to the number shown for the target tab in the open browser tabs list. Use it to return to an earlier tab without closing the current one. SWITCH_TAB does not require an element id.' if show_switch_tab_action else ''}}{{' "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 ''}}
+ "action_type": str, // It's a string enum: "CLICK", "HOVER", "INPUT_TEXT", "UPLOAD_FILE", "SELECT_OPTION", "WAIT", "SOLVE_CAPTCHA", "COMPLETE", "TERMINATE", "KEYPRESS", "SCROLL"{{', "GOTO_URL", "RELOAD_PAGE"' if enable_new_planner_actions else ""}}{{', "EXTRACT_INFORMATION"' if enable_new_planner_actions and data_extraction_goal else ""}}{{', "NEW_TAB"' if show_new_tab_action else ""}}{{', "SWITCH_TAB"' if show_switch_tab_action else ""}}{{', "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 visible captcha to solve on the screen. Captcha tokens expire quickly (~2 minutes), so fill all form fields first, then SOLVE_CAPTCHA immediately before the final submit or protected click — do not place SOLVE_CAPTCHA before a long form-fill sequence. "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.{% if enable_new_planner_actions %} "GOTO_URL" is used to navigate the current tab directly to a fully-qualified http/https URL. Only use GOTO_URL when the user goal requires direct navigation and the exact target URL comes from the user goal, the user details, the page content, or the action history. Do not use GOTO_URL to follow a normal link on the page when a clickable element is available — use CLICK on that element instead. Never invent, guess, or construct website-specific URLs or query parameters that are not explicitly available to you. If the URL of the page you're on right now already matches the target URL (ignoring a trailing slash), do not use GOTO_URL to reload the page. Element ids from the current page become invalid after navigation, so GOTO_URL must be the only action or the last action in the array. GOTO_URL is target-less and requires the "url" field. "RELOAD_PAGE" reloads the current page. Only use RELOAD_PAGE when the page itself is in a broken or stale state that a refresh would fix — content failed to load, a spinner or loading state is stuck, the DOM looks empty or only partially rendered, or the page shows a transient error. Do not use RELOAD_PAGE for normal navigation, and do not use it to retry an action that simply didn't achieve the goal — only when the page itself appears broken. RELOAD_PAGE is target-less and takes no extra fields.{% endif %}{{' "EXTRACT_INFORMATION" is used to extract the information described in the user data extraction goal from the current page. Only use EXTRACT_INFORMATION when the current page already contains the data requested in the data extraction goal and the page state is ready for extraction (fully loaded, filters applied, correct tab or section visible). Extraction runs against the current page state, so never place EXTRACT_INFORMATION after page-changing actions in the same array. If the user goal is also achieved, return COMPLETE right after EXTRACT_INFORMATION in the same array. EXTRACT_INFORMATION is target-less.' if enable_new_planner_actions and data_extraction_goal else ''}}{{' "NEW_TAB" opens a new browser tab at a given URL and makes it the active tab, keeping existing tabs open. Use it to open a page in a separate tab while keeping the current tab open (for example, to compare two pages). NEW_TAB requires the "url" field set to a fully-qualified http/https URL. Do not use NEW_TAB to follow a normal link on the page when a clickable element is available. NEW_TAB does not require an element id.' if show_new_tab_action else ''}}{{' "SWITCH_TAB" makes another already-open tab the active tab so you can see and act on it. SWITCH_TAB requires the "tab_index" field set to the number shown for the target tab in the open browser tabs list. Use it to return to an earlier tab without closing the current one. SWITCH_TAB does not require an element id.' if show_switch_tab_action else ''}}{{' "CLOSE_PAGE" closes a browser tab. By default it closes the current tab (the one marked [current]); to close a different open tab instead, set "tab_index" to that tab number from the open browser tabs list. Use it when the page instructs you to close it or return to a previous tab, or when the user goal limits how many tabs may stay open — then close the extra tabs so only the requested set remains open. 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{{', GOTO_URL, RELOAD_PAGE' if enable_new_planner_actions else ''}}{{', EXTRACT_INFORMATION' if enable_new_planner_actions and data_extraction_goal else ''}}), 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
@@ -31,7 +31,7 @@ Reply in JSON format with the following keys:
{% if enable_new_planner_actions and show_new_tab_action %} "url": str, // The fully-qualified http/https URL. For GOTO_URL, navigate the current tab to this URL; for NEW_TAB, open this URL in a new tab. null if not a navigation action.
{% elif enable_new_planner_actions %} "url": str, // The fully-qualified http/https URL to navigate to for GOTO_URL action only. null if not GOTO_URL action.
{% elif show_new_tab_action %} "url": str, // The fully-qualified http/https URL to open for NEW_TAB action only (required for NEW_TAB). null if not NEW_TAB action.
-{% endif %}{% if show_switch_tab_action %} "tab_index": int, // The tab number to switch to for SWITCH_TAB action only, taken from the open browser tabs list (required for SWITCH_TAB). null if not SWITCH_TAB action.
+{% endif %}{% if show_switch_tab_action or show_close_page_action %} "tab_index": int, // For SWITCH_TAB, the tab number to switch to (required). For CLOSE_PAGE, the tab number to close instead of the current tab (optional — omit or null to close the current tab). The number is taken from the open browser tabs list. null when neither applies.
{% endif %} "file_url": str, // The url of the file to upload if applicable. This field must be present for UPLOAD_FILE but can also be present for CLICK only if the click is to upload the file. It should be null otherwise.
"double_click": bool, // For CLICK action only. True only when the element requires a double-click to activate (e.g., opening a file in a file manager, entering edit mode in a spreadsheet cell, or expanding a tree node). Defaults to false for normal clicks. Do not use double-click for regular buttons, links, form elements, clickable grid rows, icons, or dashboard cards.
"download": bool, // Can only be true for CLICK or SELECT_OPTION actions. If true, the browser will trigger a download by clicking the element. If false, the browser will click the element without triggering a download.
diff --git a/skyvern/forge/prompts/skyvern/extract-action.j2 b/skyvern/forge/prompts/skyvern/extract-action.j2
index 525fd6794..9addcfbd8 100644
--- a/skyvern/forge/prompts/skyvern/extract-action.j2
+++ b/skyvern/forge/prompts/skyvern/extract-action.j2
@@ -21,7 +21,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"{{', "GOTO_URL", "RELOAD_PAGE"' if enable_new_planner_actions else ""}}{{', "EXTRACT_INFORMATION"' if enable_new_planner_actions and data_extraction_goal else ""}}{{', "NEW_TAB"' if show_new_tab_action else ""}}{{', "SWITCH_TAB"' if show_switch_tab_action else ""}}{{', "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 visible captcha to solve on the screen. Captcha tokens expire quickly (~2 minutes), so fill all form fields first, then SOLVE_CAPTCHA immediately before the final submit or protected click — do not place SOLVE_CAPTCHA before a long form-fill sequence. "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.{% if enable_new_planner_actions %} "GOTO_URL" is used to navigate the current tab directly to a fully-qualified http/https URL. Only use GOTO_URL when the user goal requires direct navigation and the exact target URL comes from the user goal, the user details, the page content, or the action history. Do not use GOTO_URL to follow a normal link on the page when a clickable element is available — use CLICK on that element instead. Never invent, guess, or construct website-specific URLs or query parameters that are not explicitly available to you. If the URL of the page you're on right now already matches the target URL (ignoring a trailing slash), do not use GOTO_URL to reload the page. Element ids from the current page become invalid after navigation, so GOTO_URL must be the only action or the last action in the array. GOTO_URL is target-less and requires the "url" field. "RELOAD_PAGE" reloads the current page. Only use RELOAD_PAGE when the page itself is in a broken or stale state that a refresh would fix — content failed to load, a spinner or loading state is stuck, the DOM looks empty or only partially rendered, or the page shows a transient error. Do not use RELOAD_PAGE for normal navigation, and do not use it to retry an action that simply didn't achieve the goal — only when the page itself appears broken. RELOAD_PAGE is target-less and takes no extra fields.{% endif %}{{' "EXTRACT_INFORMATION" is used to extract the information described in the user data extraction goal from the current page. Only use EXTRACT_INFORMATION when the current page already contains the data requested in the data extraction goal and the page state is ready for extraction (fully loaded, filters applied, correct tab or section visible). Extraction runs against the current page state, so never place EXTRACT_INFORMATION after page-changing actions in the same array. If the user goal is also achieved, return COMPLETE right after EXTRACT_INFORMATION in the same array. EXTRACT_INFORMATION is target-less.' if enable_new_planner_actions and data_extraction_goal else ''}}{{' "NEW_TAB" opens a new browser tab at a given URL and makes it the active tab, keeping existing tabs open. Use it to open a page in a separate tab while keeping the current tab open (for example, to compare two pages). NEW_TAB requires the "url" field set to a fully-qualified http/https URL. Do not use NEW_TAB to follow a normal link on the page when a clickable element is available. NEW_TAB does not require an element id.' if show_new_tab_action else ''}}{{' "SWITCH_TAB" makes another already-open tab the active tab so you can see and act on it. SWITCH_TAB requires the "tab_index" field set to the number shown for the target tab in the open browser tabs list. Use it to return to an earlier tab without closing the current one. SWITCH_TAB does not require an element id.' if show_switch_tab_action else ''}}{{' "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 ''}}
+ "action_type": str, // It's a string enum: "CLICK", "HOVER", "INPUT_TEXT", "UPLOAD_FILE", "SELECT_OPTION", "WAIT", "SOLVE_CAPTCHA", "COMPLETE", "TERMINATE", "KEYPRESS", "SCROLL"{{', "GOTO_URL", "RELOAD_PAGE"' if enable_new_planner_actions else ""}}{{', "EXTRACT_INFORMATION"' if enable_new_planner_actions and data_extraction_goal else ""}}{{', "NEW_TAB"' if show_new_tab_action else ""}}{{', "SWITCH_TAB"' if show_switch_tab_action else ""}}{{', "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 visible captcha to solve on the screen. Captcha tokens expire quickly (~2 minutes), so fill all form fields first, then SOLVE_CAPTCHA immediately before the final submit or protected click — do not place SOLVE_CAPTCHA before a long form-fill sequence. "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.{% if enable_new_planner_actions %} "GOTO_URL" is used to navigate the current tab directly to a fully-qualified http/https URL. Only use GOTO_URL when the user goal requires direct navigation and the exact target URL comes from the user goal, the user details, the page content, or the action history. Do not use GOTO_URL to follow a normal link on the page when a clickable element is available — use CLICK on that element instead. Never invent, guess, or construct website-specific URLs or query parameters that are not explicitly available to you. If the URL of the page you're on right now already matches the target URL (ignoring a trailing slash), do not use GOTO_URL to reload the page. Element ids from the current page become invalid after navigation, so GOTO_URL must be the only action or the last action in the array. GOTO_URL is target-less and requires the "url" field. "RELOAD_PAGE" reloads the current page. Only use RELOAD_PAGE when the page itself is in a broken or stale state that a refresh would fix — content failed to load, a spinner or loading state is stuck, the DOM looks empty or only partially rendered, or the page shows a transient error. Do not use RELOAD_PAGE for normal navigation, and do not use it to retry an action that simply didn't achieve the goal — only when the page itself appears broken. RELOAD_PAGE is target-less and takes no extra fields.{% endif %}{{' "EXTRACT_INFORMATION" is used to extract the information described in the user data extraction goal from the current page. Only use EXTRACT_INFORMATION when the current page already contains the data requested in the data extraction goal and the page state is ready for extraction (fully loaded, filters applied, correct tab or section visible). Extraction runs against the current page state, so never place EXTRACT_INFORMATION after page-changing actions in the same array. If the user goal is also achieved, return COMPLETE right after EXTRACT_INFORMATION in the same array. EXTRACT_INFORMATION is target-less.' if enable_new_planner_actions and data_extraction_goal else ''}}{{' "NEW_TAB" opens a new browser tab at a given URL and makes it the active tab, keeping existing tabs open. Use it to open a page in a separate tab while keeping the current tab open (for example, to compare two pages). NEW_TAB requires the "url" field set to a fully-qualified http/https URL. Do not use NEW_TAB to follow a normal link on the page when a clickable element is available. NEW_TAB does not require an element id.' if show_new_tab_action else ''}}{{' "SWITCH_TAB" makes another already-open tab the active tab so you can see and act on it. SWITCH_TAB requires the "tab_index" field set to the number shown for the target tab in the open browser tabs list. Use it to return to an earlier tab without closing the current one. SWITCH_TAB does not require an element id.' if show_switch_tab_action else ''}}{{' "CLOSE_PAGE" closes a browser tab. By default it closes the current tab (the one marked [current]); to close a different open tab instead, set "tab_index" to that tab number from the open browser tabs list. Use it when the page instructs you to close it or return to a previous tab, or when the user goal limits how many tabs may stay open — then close the extra tabs so only the requested set remains open. 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{{', GOTO_URL, RELOAD_PAGE' if enable_new_planner_actions else ''}}{{', EXTRACT_INFORMATION' if enable_new_planner_actions and data_extraction_goal else ''}}), 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
@@ -31,7 +31,7 @@ Reply in JSON format with the following keys:
{% if enable_new_planner_actions and show_new_tab_action %} "url": str, // The fully-qualified http/https URL. For GOTO_URL, navigate the current tab to this URL; for NEW_TAB, open this URL in a new tab. null if not a navigation action.
{% elif enable_new_planner_actions %} "url": str, // The fully-qualified http/https URL to navigate to for GOTO_URL action only. null if not GOTO_URL action.
{% elif show_new_tab_action %} "url": str, // The fully-qualified http/https URL to open for NEW_TAB action only (required for NEW_TAB). null if not NEW_TAB action.
-{% endif %}{% if show_switch_tab_action %} "tab_index": int, // The tab number to switch to for SWITCH_TAB action only, taken from the open browser tabs list (required for SWITCH_TAB). null if not SWITCH_TAB action.
+{% endif %}{% if show_switch_tab_action or show_close_page_action %} "tab_index": int, // For SWITCH_TAB, the tab number to switch to (required). For CLOSE_PAGE, the tab number to close instead of the current tab (optional — omit or null to close the current tab). The number is taken from the open browser tabs list. null when neither applies.
{% endif %} "file_url": str, // The url of the file to upload if applicable. This field must be present for UPLOAD_FILE but can also be present for CLICK only if the click is to upload the file. It should be null otherwise.
"double_click": bool, // For CLICK action only. True only when the element requires a double-click to activate (e.g., opening a file in a file manager, entering edit mode in a spreadsheet cell, or expanding a tree node). Defaults to false for normal clicks. Do not use double-click for regular buttons, links, form elements, clickable grid rows, icons, or dashboard cards.
"download": bool, // Can only be true for CLICK or SELECT_OPTION actions. If true, the browser will trigger a download by clicking the element. If false, the browser will click the element without triggering a download.
@@ -102,7 +102,7 @@ User details:
```
{% if open_tabs_context %}
-Open browser tabs ({% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active, and CLOSE_PAGE closes the tab marked [current]{% else %}CLOSE_PAGE always closes the tab marked [current] — other tabs are shown for context only{% endif %}):
+Open browser tabs ({% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active; CLOSE_PAGE closes the tab marked [current], or set its "tab_index" to close a specific tab{% else %}CLOSE_PAGE closes the tab marked [current] by default, or set its "tab_index" to the number of a specific tab to close that one{% endif %}):
```
{{ open_tabs_context }}
```
diff --git a/skyvern/forge/prompts/skyvern/task_v2.j2 b/skyvern/forge/prompts/skyvern/task_v2.j2
index 7f6d38341..5c548ad15 100644
--- a/skyvern/forge/prompts/skyvern/task_v2.j2
+++ b/skyvern/forge/prompts/skyvern/task_v2.j2
@@ -48,6 +48,10 @@ CRITICAL - The agent's own final answer is composed at completion, not by a task
- Once the underlying DATA each required part needs has been captured by extract tasks, set user_goal_achieved to true. Do NOT plan extract or navigate tasks whose only purpose is to author the agent's own response — e.g. "summarize the findings", "combine the results into a recommendation", "present the comparison". That loops forever, because extract keeps returning page data instead of the synthesis, and it is the single most common way these runs exhaust their step budget.
- Exception — required on-page actions still count: entering content INTO a web page the goal asks you to fill (a form, document, or post), and completing terminal actions the goal requires (submit, confirm, place order, send), are real navigate tasks and must still be done. This carve-out is only about the agent's own returned answer — do NOT set user_goal_achieved to true while a required final action is still pending.
+CRITICAL - Honor explicit count, selection, and kept-open-tab constraints in the goal:
+- When the goal fixes an exact count or a specific selection (e.g. "exactly N", "the N best/strongest", "top N", a required mix like "at least one X and one Y", or one specifically described item), matching that count and mix is a required subgoal. Do NOT set user_goal_achieved to true while the captured result is a superset, the wrong count, or missing a required category.
+- When the goal limits how many browser tabs should stay open, compare that limit against the live "Open browser tabs" list shown below. If more tabs are open than allowed, plan a navigate task to close the extra tabs down to exactly the requested set and mix (keeping the strongest/required ones). Closing tabs is a real browser action, so this is a valid navigate task — it is NOT the forbidden "only authors the answer" kind of task described above. Judge the count from the open-tabs list, not from how many tabs you intended to open — sub-tasks may have opened more. If you have already attempted a close-tabs task and the open tabs still do not match, do not keep retrying it — set user_goal_achieved to true and finish with the best result.
+
MAKE SURE YOU OUTPUT VALID JSON. No text before or after JSON, no trailing commas, no comments (//), no unnecessary quotes, etc.
Reply in JSON format with the following keys:
@@ -74,6 +78,13 @@ Reply in JSON format with the following keys:
}
The URL of the page you're on right now is `{{ current_url }}`.
+{% if open_tabs_context %}
+
+Open browser tabs right now (the live set of tabs the agent has open; the tab marked [current] is the page shown above). Sub-tasks may have opened more tabs than planned, so when the goal limits how many tabs may stay open, treat this list — not the number you intended to open — as the true open-tab state:
+```
+{{ open_tabs_context }}
+```
+{% endif %}
Clickable elements from the page:
```
diff --git a/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2 b/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2
index 581d5c0e5..9d086decd 100644
--- a/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2
+++ b/skyvern/forge/prompts/skyvern/task_v2_check_completion.j2
@@ -38,6 +38,8 @@ CRITICAL - Do not declare success on a partially-complete multi-part goal:
- Many goals have multiple required parts/legs (e.g. "find X AND find Y AND find Z"). The goal is achieved ONLY when ALL required parts are done.
- If your own analysis (task_history_information, thoughts, or required_subgoals) identifies ANY required part as missing, unmet, or not yet found, you MUST set user_goal_achieved to false so the agent attempts the missing part next.
- Setting user_goal_achieved to false here does NOT fail the task — it lets the agent keep working on the missing part. Only set should_terminate to true if a required part is genuinely IMPOSSIBLE per the termination rules above; in that case give a termination_reason.
+- A goal that fixes an exact count, selection, or required mix (e.g. "exactly N", "the N best/strongest", "top N", "at least one X and one Y", or one specifically described item) is NOT satisfied by the wrong count or a set missing a required category — keep user_goal_achieved false until the captured result covers the requested count and mix.
+- If the goal limits how many browser tabs may stay open (e.g. "keep exactly N tabs open"), compare that limit against the live "Open browser tabs" list below (count the actual tabs, not how many the agent meant to open). If more tabs are open than allowed, set user_goal_achieved to false so the agent can close the extra tabs next — UNLESS the task history already shows a tab-closing/curation attempt, in which case do NOT keep blocking on the open-tab count; decide user_goal_achieved from whether the rest of the goal is satisfied so the run can finish with its result.
User goal:
```
@@ -48,6 +50,13 @@ Task history (the earliest task is the first in the list and the latest is the l
```
{{ task_history }}
```
+{% if open_tabs_context %}
+
+Open browser tabs right now (the live set of tabs the agent has open; the tab marked [current] is the page in the screenshot). Use this list — not the number the agent intended to open — to judge any "keep N tabs open" constraint:
+```
+{{ open_tabs_context }}
+```
+{% endif %}
Current datetime, ISO format:
```
diff --git a/skyvern/forge/prompts/skyvern/task_v2_summary.j2 b/skyvern/forge/prompts/skyvern/task_v2_summary.j2
index 62e2b4e92..589e909b1 100644
--- a/skyvern/forge/prompts/skyvern/task_v2_summary.j2
+++ b/skyvern/forge/prompts/skyvern/task_v2_summary.j2
@@ -3,7 +3,7 @@ Given the user goal, the latest screenshot of the page, and the mini tasks compl
If the user goal asks for a summary, comparison, recommendation, brief, decision, or other written deliverable, the "description" field MUST be that deliverable, stated in full: give the actual answer with its specific items, values, and reasoning, synthesized across the entire task history. Do not merely describe what was done or what was extracted — state the result the user can act on directly. Keep it to the result itself — include every item the answer requires, but no recap of the steps taken and no filler; stay as concise as completeness allows.
-Match the output structure the goal explicitly asks for: if it names sections, headings, or questions to address, include each one as its own labeled part — do not merge, drop, or renumber them; if it asks for an exact number of items, rows, or options, return that many when the gathered data supports it (never pad, repeat, or invent entries to reach a count); if it asks for a recommendation or decision, state the actual choice, not just the options.
+Match the output structure the goal explicitly asks for: if it names sections, headings, or questions to address, include each one as its own labeled part — do not merge, drop, or renumber them; if it fixes an exact count or selection (e.g. "exactly N", "the N best/strongest", "top N", or one specifically described item), return exactly that many when the gathered data supports it — never pad, repeat, or invent entries to reach a count, and never return a superset: when more were gathered, select the best-matching items and drop the rest; if it requires a specific mix (e.g. "at least one X and one Y"), include each required category; if it asks for a recommendation or decision, state the actual choice, not just the options.
{% if is_partial %}Some required parts may be missing because the run stopped early. Produce the deliverable for every part you have data for, and for any part still missing or unverified, include it with an explicit note that it could not be completed — never silently omit a requested section, item, or row.
{% endif %}
Reply in JSON format with the following keys:
diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.py
index 06910ed4c..e66ab9975 100644
--- a/skyvern/services/task_v2_service.py
+++ b/skyvern/services/task_v2_service.py
@@ -79,7 +79,7 @@ from skyvern.utils.strings import generate_random_string
from skyvern.webeye.actions.actions import ActionType
from skyvern.webeye.browser_state import BrowserState
from skyvern.webeye.scraper.scraped_page import ScrapedPage
-from skyvern.webeye.utils.page import SkyvernFrame
+from skyvern.webeye.utils.page import SkyvernFrame, build_open_tabs_context
LOG = structlog.get_logger()
DEFAULT_WORKFLOW_TITLE = "New Workflow"
@@ -851,6 +851,11 @@ async def run_task_v2_helper(
continue
current_url = current_url if current_url else str(await SkyvernFrame.get_url(frame=page) if page else url)
+ try:
+ open_tabs_context = await build_open_tabs_context(browser_state, page)
+ except Exception:
+ LOG.warning("Failed to build open-tabs context for the planner", exc_info=True)
+ open_tabs_context = None
task_v2_prompt = load_prompt_with_elements(
scraped_page,
prompt_engine,
@@ -858,6 +863,7 @@ async def run_task_v2_helper(
current_url=current_url,
user_goal=user_prompt,
task_history=task_history,
+ open_tabs_context=open_tabs_context,
local_datetime=datetime.now(context.tz_info).isoformat(),
)
thought = await app.DATABASE.observer.create_thought(
@@ -1117,6 +1123,7 @@ async def run_task_v2_helper(
if block_result.success is True:
completion_screenshots: list[bytes] = []
completion_scraped_page: ScrapedPage | None = None
+ completion_open_tabs_context: str | None = None
try:
browser_state = await app.BROWSER_MANAGER.get_or_create_for_workflow_run(
workflow_run=workflow_run,
@@ -1131,13 +1138,21 @@ async def run_task_v2_helper(
)
completion_screenshots = completion_scraped_page.screenshots
except Exception:
- LOG.warning("Failed to scrape the website for task v2 completion check")
+ LOG.warning("Failed to scrape the website for task v2 completion check", exc_info=True)
+ if completion_scraped_page is not None:
+ try:
+ completion_open_tabs_context = await build_open_tabs_context(
+ browser_state, await browser_state.get_working_page()
+ )
+ except Exception:
+ LOG.warning("Failed to build open-tabs context for completion check", exc_info=True)
# validate completion only happens at the last iteration
task_v2_completion_prompt = prompt_engine.load_prompt(
"task_v2_check_completion",
user_goal=user_prompt,
task_history=task_history,
+ open_tabs_context=completion_open_tabs_context,
local_datetime=datetime.now(context.tz_info).isoformat(),
)
thought = await app.DATABASE.observer.create_thought(
diff --git a/skyvern/webeye/actions/actions.py b/skyvern/webeye/actions/actions.py
index f70a90d84..41383a9a8 100644
--- a/skyvern/webeye/actions/actions.py
+++ b/skyvern/webeye/actions/actions.py
@@ -257,9 +257,10 @@ class ReloadPageAction(Action):
action_type: ActionType = ActionType.RELOAD_PAGE
-# TODO: right now, it's only enabled when there's magic link during login
class ClosePageAction(Action):
action_type: ActionType = ActionType.CLOSE_PAGE
+ # When set, close the open tab at this index in the open-tabs list instead of the current tab.
+ tab_index: int | None = None
class NewTabAction(Action):
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index bb8fa2273..69ec43306 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -3444,8 +3444,26 @@ async def handle_close_page_action(
task: Task,
step: Step,
) -> list[ActionResult]:
- await page.close(reason=action.reasoning)
- return [ActionSuccess()]
+ target_page = page
+ if action.tab_index is not None:
+ browser_state = app.BROWSER_MANAGER.get_for_task(task.task_id, workflow_run_id=task.workflow_run_id)
+ if browser_state is None:
+ return [ActionFailure(Exception("No browser state found for the task"), stop_execution_on_failure=False)]
+ pages = await browser_state.list_valid_pages()
+ if action.tab_index < 0 or action.tab_index >= len(pages):
+ return [
+ ActionFailure(
+ Exception(f"CLOSE_PAGE tab_index {action.tab_index} is out of range (0-{len(pages) - 1})"),
+ stop_execution_on_failure=False,
+ )
+ ]
+ target_page = pages[action.tab_index]
+ await target_page.close(reason=action.reasoning)
+ # Closing a tab shifts the remaining tab indices; stop the batch so the next step re-scrapes
+ # and re-indexes the open tabs before any further close/switch action runs against stale indices.
+ result = ActionSuccess()
+ result.skip_remaining_actions = True
+ return [result]
@traced(name="skyvern.agent.action.new_tab")
diff --git a/skyvern/webeye/actions/parse_actions.py b/skyvern/webeye/actions/parse_actions.py
index 7268da164..bf061f93a 100644
--- a/skyvern/webeye/actions/parse_actions.py
+++ b/skyvern/webeye/actions/parse_actions.py
@@ -260,7 +260,18 @@ def parse_action(
return ScrollAction(**base_action_dict, scroll_x=scroll_x, scroll_y=scroll_y)
if action_type == ActionType.CLOSE_PAGE:
- return ClosePageAction(**base_action_dict)
+ raw_index = action.get("tab_index")
+ if raw_index is None:
+ return ClosePageAction(**base_action_dict)
+ try:
+ tab_index = int(raw_index)
+ except (TypeError, ValueError):
+ LOG.warning(
+ "CLOSE_PAGE action returned with a non-integer tab_index, closing the current tab instead",
+ raw_action=action,
+ )
+ return ClosePageAction(**base_action_dict)
+ return ClosePageAction(**base_action_dict, tab_index=tab_index)
if action_type == ActionType.EXTRACT:
# EXTRACT is a global page action, not element-targeted
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index 224134dec..5f4ace3e4 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -5,7 +5,7 @@ import json
import time
from enum import StrEnum
from io import BytesIO
-from typing import Any
+from typing import TYPE_CHECKING, Any
import structlog
from opentelemetry import trace as otel_trace
@@ -21,9 +21,48 @@ from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.trace import apply_context_attrs, traced
from skyvern.webeye.main_world_eval import evaluate_in_main_world, get_main_world_prefix
+if TYPE_CHECKING:
+ from skyvern.webeye.browser_state import BrowserState
+
LOG = structlog.get_logger()
+async def _safe_tab_title(page: Page) -> str:
+ try:
+ return await asyncio.wait_for(page.title(), timeout=1.0)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ LOG.debug("tab_title_fetch_failed", url=page.url)
+ return ""
+
+
+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
+ # Fetch titles concurrently so a few slow tabs don't add N×timeout latency to every iteration.
+ titles = await asyncio.gather(*(_safe_tab_title(p) for p in pages))
+ lines: list[str] = []
+ for i, (p, title) in enumerate(zip(pages, titles)):
+ marker = " [current]" if p == working_page else ""
+ url = p.url
+ 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 load_js_script() -> str:
# TODO: Handle file location better. This is a hacky way to find the file location.
path = f"{SKYVERN_DIR}/webeye/scraper/domUtils.js"
diff --git a/tests/unit/test_actions.py b/tests/unit/test_actions.py
index 7234499f5..7e01dde0a 100644
--- a/tests/unit/test_actions.py
+++ b/tests/unit/test_actions.py
@@ -20,6 +20,7 @@ from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import (
Action,
ClickAction,
+ ClosePageAction,
ExtractAction,
GotoUrlAction,
InputTextAction,
@@ -359,6 +360,33 @@ def test_parse_keypress_invalid_key_returns_null_action() -> None:
assert isinstance(action, NullAction)
+def test_parse_close_page_with_tab_index() -> None:
+ action = parse_action(
+ action={"action_type": "CLOSE_PAGE", "tab_index": 3, "reasoning": "drop the extra tab"},
+ scraped_page=_mock_scraped_page(),
+ )
+ assert isinstance(action, ClosePageAction)
+ assert action.tab_index == 3
+
+
+def test_parse_close_page_without_tab_index_defaults_to_current() -> None:
+ action = parse_action(
+ action={"action_type": "CLOSE_PAGE", "reasoning": "close current"},
+ scraped_page=_mock_scraped_page(),
+ )
+ assert isinstance(action, ClosePageAction)
+ assert action.tab_index is None
+
+
+def test_parse_close_page_non_integer_tab_index_falls_back_to_current() -> None:
+ action = parse_action(
+ action={"action_type": "CLOSE_PAGE", "tab_index": "not-a-number", "reasoning": "bad index"},
+ scraped_page=_mock_scraped_page(),
+ )
+ assert isinstance(action, ClosePageAction)
+ assert action.tab_index is None
+
+
def test_parse_keypress_backward_compat_press_enter() -> None:
action = parse_action(
action={"action_type": "PRESS_ENTER", "key": "Enter", "reasoning": "test"},
diff --git a/tests/unit/test_extract_action_open_tabs_context.py b/tests/unit/test_extract_action_open_tabs_context.py
index 473f23eee..53a4d9c88 100644
--- a/tests/unit/test_extract_action_open_tabs_context.py
+++ b/tests/unit/test_extract_action_open_tabs_context.py
@@ -5,8 +5,9 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
-from skyvern.forge.agent import ForgeAgent, _build_open_tabs_context
+from skyvern.forge.agent import ForgeAgent
from skyvern.forge.prompts import prompt_engine
+from skyvern.webeye.utils.page import build_open_tabs_context
_BASE_KWARGS: dict[str, Any] = {
"navigation_goal": "close the stuck tab and continue",
@@ -35,7 +36,9 @@ class TestClosePageGate:
**_BASE_KWARGS,
)
assert '"CLOSE_PAGE"' in rendered
- assert "close the current tab" in rendered.lower()
+ assert "closes the current tab" in rendered.lower()
+ # close-by-index is documented even when SWITCH_TAB is unavailable
+ assert "tab_index" in rendered
@pytest.mark.parametrize("template", ["extract-action", "extract-action-static"])
def test_no_close_page_without_tab_context(self, template: str) -> None:
@@ -71,7 +74,7 @@ class TestOpenTabsContextSection:
**_BASE_KWARGS,
)
assert "Open browser tabs" in rendered
- assert "other tabs are shown for context only" in rendered
+ assert "tab_index" in rendered
assert "[current]" in rendered
assert "https://main.test" in rendered
assert "https://pdf.test/viewer" in rendered
@@ -183,7 +186,7 @@ class TestNewTabSwitchTabGate:
**_BASE_KWARGS,
)
assert "use SWITCH_TAB" in switch_on
- assert "context only" not in switch_on
+ assert "by default" not in switch_on
switch_off = prompt_engine.load_prompt(
"extract-action-dynamic",
@@ -194,7 +197,7 @@ class TestNewTabSwitchTabGate:
**_BASE_KWARGS,
)
assert "use SWITCH_TAB" not in switch_off
- assert "context only" in switch_off
+ assert "by default" in switch_off
class TestTabCacheVariant:
@@ -222,7 +225,7 @@ 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)
+ result = await build_open_tabs_context(browser_state, None)
assert result is None
browser_state.list_valid_pages.assert_not_called()
@@ -232,7 +235,7 @@ class TestBuildOpenTabsContext:
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)
+ result = await build_open_tabs_context(browser_state, page)
assert result is None
@pytest.mark.asyncio
@@ -248,7 +251,7 @@ class TestBuildOpenTabsContext:
browser_state = MagicMock()
browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
- result = await _build_open_tabs_context(browser_state, 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
@@ -266,7 +269,7 @@ class TestBuildOpenTabsContext:
browser_state = MagicMock()
browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
- result = await _build_open_tabs_context(browser_state, 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
@@ -286,7 +289,7 @@ class TestBuildOpenTabsContext:
browser_state = MagicMock()
browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
- result = await _build_open_tabs_context(browser_state, page1)
+ result = await build_open_tabs_context(browser_state, page1)
assert result is not None
assert "..." in result
for line in result.splitlines():
@@ -308,7 +311,7 @@ class TestBuildOpenTabsContext:
browser_state = MagicMock()
browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1])
- result = await _build_open_tabs_context(browser_state, page1)
+ result = await build_open_tabs_context(browser_state, page1)
assert result is not None
assert "..." in result
for line in result.splitlines():
diff --git a/tests/unit/test_tab_action_handlers.py b/tests/unit/test_tab_action_handlers.py
index aa5328dfd..1b6185542 100644
--- a/tests/unit/test_tab_action_handlers.py
+++ b/tests/unit/test_tab_action_handlers.py
@@ -1,11 +1,15 @@
-"""Tests for the NEW_TAB / SWITCH_TAB action handlers."""
+"""Tests for the NEW_TAB / SWITCH_TAB / CLOSE_PAGE action handlers."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.webeye.actions import actions
-from skyvern.webeye.actions.handler import handle_new_tab_action, handle_switch_tab_action
+from skyvern.webeye.actions.handler import (
+ handle_close_page_action,
+ handle_new_tab_action,
+ handle_switch_tab_action,
+)
from skyvern.webeye.actions.responses import ActionFailure, ActionSuccess
@@ -94,3 +98,72 @@ async def test_switch_tab_out_of_range_fails_without_stopping_step() -> None:
assert isinstance(result[0], ActionFailure)
assert result[0].stop_execution_on_failure is False
browser_state.set_active_page.assert_not_awaited()
+
+
+async def test_close_page_without_index_closes_current_and_stops_batch() -> None:
+ current_page = MagicMock()
+ current_page.close = AsyncMock()
+
+ result = await handle_close_page_action(actions.ClosePageAction(), current_page, MagicMock(), _task(), MagicMock())
+
+ assert isinstance(result[0], ActionSuccess)
+ assert result[0].skip_remaining_actions is True
+ current_page.close.assert_awaited_once()
+
+
+async def test_close_page_with_index_closes_target_tab_not_current() -> None:
+ current_page = MagicMock()
+ current_page.close = AsyncMock()
+ page0, page1, page2 = MagicMock(), MagicMock(), MagicMock()
+ page2.close = AsyncMock()
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[page0, page1, page2])
+
+ with patch("skyvern.webeye.actions.handler.app", _mock_app(browser_state)):
+ result = await handle_close_page_action(
+ actions.ClosePageAction(tab_index=2), current_page, MagicMock(), _task(), MagicMock()
+ )
+
+ assert isinstance(result[0], ActionSuccess)
+ assert result[0].skip_remaining_actions is True
+ page2.close.assert_awaited_once()
+ current_page.close.assert_not_awaited()
+
+
+async def test_close_page_with_index_can_close_the_current_tab() -> None:
+ # tab_index may point at the current tab itself; closing it must still succeed and stop the
+ # batch so the next step re-scrapes against whatever page becomes active.
+ current_page = MagicMock()
+ current_page.close = AsyncMock()
+ other_page = MagicMock()
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[current_page, other_page])
+
+ with patch("skyvern.webeye.actions.handler.app", _mock_app(browser_state)):
+ result = await handle_close_page_action(
+ actions.ClosePageAction(tab_index=0), current_page, MagicMock(), _task(), MagicMock()
+ )
+
+ assert isinstance(result[0], ActionSuccess)
+ assert result[0].skip_remaining_actions is True
+ current_page.close.assert_awaited_once()
+
+
+async def test_close_page_out_of_range_fails_without_stopping_step() -> None:
+ current_page = MagicMock()
+ current_page.close = AsyncMock()
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=[MagicMock()])
+
+ with patch("skyvern.webeye.actions.handler.app", _mock_app(browser_state)):
+ result = await handle_close_page_action(
+ actions.ClosePageAction(tab_index=9), current_page, MagicMock(), _task(), MagicMock()
+ )
+
+ assert isinstance(result[0], ActionFailure)
+ assert result[0].stop_execution_on_failure is False
+ current_page.close.assert_not_awaited()
diff --git a/tests/unit/test_task_v2_open_tabs_context.py b/tests/unit/test_task_v2_open_tabs_context.py
new file mode 100644
index 000000000..8639f56b2
--- /dev/null
+++ b/tests/unit/test_task_v2_open_tabs_context.py
@@ -0,0 +1,97 @@
+"""The task_v2 planner and completion-gate prompts must surface the live open-tab set.
+
+The planner and completion gate receive open_tabs_context (previously only per-step action
+selection did), so a "keep exactly N tabs" goal is judged from the actual open-tab count rather
+than the number the agent intended to open. These tests pin that the live tab list reaches both
+prompts and that the curate-down guidance references it.
+"""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.forge.prompts import prompt_engine
+from skyvern.webeye.utils.page import build_open_tabs_context
+
+# More tabs (8) than the goal allows (5): the over-open the planner must notice and curate.
+_EIGHT_TABS = "\n".join(
+ f"Tab {i}{' [current]' if i == 0 else ''}: https://golf{i}.test/course (Course {i})" for i in range(8)
+)
+_GOAL = "Research reputable sources and keep exactly 5 golf course candidate tabs open."
+
+
+class TestTaskV2PlannerOpenTabs:
+ def _render(self, open_tabs_context: str | None) -> str:
+ return prompt_engine.load_prompt(
+ "task_v2",
+ current_url="https://golf0.test/course",
+ elements="<html></html>",
+ user_goal=_GOAL,
+ task_history="[]",
+ open_tabs_context=open_tabs_context,
+ local_datetime="2026-06-24T00:00:00Z",
+ )
+
+ def test_planner_sees_full_tab_list_when_present(self) -> None:
+ rendered = self._render(_EIGHT_TABS)
+ assert "Open browser tabs right now" in rendered
+ assert "[current]" in rendered
+ # Every actually-open tab is listed — including the ones beyond the goal's count of 5.
+ assert "Tab 7" in rendered and "Course 7" in rendered
+ # The planner is told to trust the live list, not its intended count.
+ assert "true open-tab state" in rendered
+
+ def test_planner_curate_rule_references_the_list(self) -> None:
+ rendered = self._render(_EIGHT_TABS)
+ assert "close the extra tabs down to exactly" in rendered
+ assert 'live "Open browser tabs" list' in rendered
+
+ def test_planner_block_absent_without_tab_context(self) -> None:
+ rendered = self._render(None)
+ assert "Open browser tabs right now" not in rendered
+ # The standing count/selection rule is unconditional and must remain.
+ assert "Honor explicit count" in rendered
+
+
+class TestTaskV2CompletionGateOpenTabs:
+ def _render(self, open_tabs_context: str | None) -> str:
+ return prompt_engine.load_prompt(
+ "task_v2_check_completion",
+ user_goal=_GOAL,
+ task_history="[]",
+ open_tabs_context=open_tabs_context,
+ local_datetime="2026-06-24T00:00:00Z",
+ )
+
+ def test_completion_gate_sees_full_tab_list_when_present(self) -> None:
+ rendered = self._render(_EIGHT_TABS)
+ assert "Open browser tabs right now" in rendered
+ assert "Tab 7" in rendered and "Course 7" in rendered
+ assert "compare that limit against the live" in rendered
+
+ def test_completion_gate_block_absent_without_tab_context(self) -> None:
+ rendered = self._render(None)
+ assert "Open browser tabs right now" not in rendered
+ # The standing keep-N-tabs rule is unconditional and must remain.
+ assert "keep exactly N tabs open" in rendered
+
+
+class TestPlannerCountIsActualNotIntended:
+ """The helper reports the real number of open tabs — the signal the planner was missing."""
+
+ @pytest.mark.asyncio
+ async def test_eight_open_tabs_yield_eight_listed(self) -> None:
+ pages = []
+ for i in range(8):
+ p = MagicMock()
+ p.url = f"https://golf{i}.test/course"
+ p.title = AsyncMock(return_value=f"Course {i}")
+ pages.append(p)
+ browser_state = MagicMock()
+ browser_state.list_valid_pages = AsyncMock(return_value=pages)
+
+ result = await build_open_tabs_context(browser_state, pages[0])
+ assert result is not None
+ assert result.count("Tab ") == 8
+ assert "Tab 7: https://golf7.test/course (Course 7)" in result
+ assert "Tab 0 [current]:" in result