Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Merge branch 'main' into fuckaround/dom-processing-tree
Gregor Žunič177d5bcb7ec2
diff --git a/.github/workflows/eval.yaml b/.github/workflows/eval.yamlindex f1b673334..0ce5a61e2 100644--- a/.github/workflows/eval.yaml+++ b/.github/workflows/eval.yaml@@ -7,7 +7,9 @@ on:jobs:run_evaluation:- runs-on: ubuntu-latest+ runs-on:+ group: eval+ labels: eval-2-core-500timeout-minutes: 360env:IN_DOCKER: 'true'@@ -104,6 +106,13 @@ jobs:ps aux | wc -lecho "================================="+ - name: Construct GitHub Workflow URL+ id: github_url+ run: |+ GITHUB_WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"+ echo "GITHUB_WORKFLOW_URL=$GITHUB_WORKFLOW_URL" >> $GITHUB_OUTPUT+ echo "::notice title=Workflow URL::Workflow URL: $GITHUB_WORKFLOW_URL"+- name: Construct eval commandid: eval_commandrun: |@@ -196,6 +205,7 @@ jobs:[[ "${{ github.event.client_payload.script_args.no_vision }}" == "true" ]] && CMD_ARGS+=("--no-vision")[[ "$HEADLESS" == "true" ]] && CMD_ARGS+=("--headless")[[ "${{ github.event.client_payload.script_args.use_serp }}" == "true" ]] && CMD_ARGS+=("--use-serp")+ [[ "${{ github.event.client_payload.script_args.use_anchor }}" == "true" ]] && CMD_ARGS+=("--use-anchor")[[ "${{ github.event.client_payload.script_args.enable_memory }}" == "true" ]] && CMD_ARGS+=("--enable-memory")[[ "${{ github.event.client_payload.script_args.validate_output }}" == "true" ]] && CMD_ARGS+=("--validate-output")[[ "${{ github.event.client_payload.script_args.include_result }}" == "true" ]] && CMD_ARGS+=("--include-result")@@ -215,6 +225,9 @@ jobs:[[ -n "$TASK_TEXT" ]] && CMD_ARGS+=("--task-text" "$TASK_TEXT")[[ -n "$TASK_WEBSITE" ]] && CMD_ARGS+=("--task-website" "$TASK_WEBSITE")+ # Add GitHub workflow URL+ [[ -n "${{ steps.github_url.outputs.GITHUB_WORKFLOW_URL }}" ]] && CMD_ARGS+=("--github-workflow-url" "${{ steps.github_url.outputs.GITHUB_WORKFLOW_URL }}")+# Convert array to command string with proper escapingprintf -v CMD_STRING '%q ' "${CMD_ARGS[@]}"diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 32c541d97..b48d1aff1 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -4,8 +4,7 @@ import jsonimport loggingfrom browser_use.agent.message_manager.views import (- MessageMetadata,- SupportedMessageTypes,+ HistoryItem,)from browser_use.agent.prompts import AgentMessagePromptfrom browser_use.agent.views import (@@ -106,6 +105,7 @@ class MessageManager:include_attributes: list[str] | None = None,message_context: str | None = None,sensitive_data: dict[str, str | dict[str, str]] | None = None,+ max_history_items: int | None = None,):self.task = taskself.state = state@@ -114,6 +114,9 @@ class MessageManager:self.sensitive_data_description = ''self.available_file_paths = available_file_pathsself.use_thinking = use_thinking+ self.max_history_items = max_history_items++ assert max_history_items is None or max_history_items > 5, 'max_history_items must be None or greater than 5'# Store settings as direct attributes instead of in a settings objectself.include_attributes = include_attributes or []@@ -124,16 +127,45 @@ class MessageManager:if len(self.state.history.messages) == 0:self._init_messages()+ @property+ def agent_history_description(self) -> str:+ """Build agent history description from list of items, respecting max_history_items limit"""+ if self.max_history_items is None:+ # Include all items+ return '\n'.join(item.to_string() for item in self.state.agent_history_items)++ total_items = len(self.state.agent_history_items)++ # If we have fewer items than the limit, just return all items+ if total_items <= self.max_history_items:+ return '\n'.join(item.to_string() for item in self.state.agent_history_items)++ # We have more items than the limit, so we need to omit some+ omitted_count = total_items - self.max_history_items++ # Show first item + omitted message + most recent (max_history_items - 1) items+ # The omitted message doesn't count against the limit, only real history items do+ recent_items_count = self.max_history_items - 1 # -1 for first item++ items_to_include = [+ self.state.agent_history_items[0].to_string(), # Keep first item (initialization)+ f'<sys>[... {omitted_count} previous steps omitted...]</sys>',+ ]+ # Add most recent items+ items_to_include.extend([item.to_string() for item in self.state.agent_history_items[-recent_items_count:]])++ return '\n'.join(items_to_include)+def _init_messages(self) -> None:"""Initialize the message history with system message, context, task, and other initial messages"""- self._add_message_with_type(self.system_prompt, message_type='init')+ self._add_message_with_type(self.system_prompt)placeholder_message = UserMessage(content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.',cache=True,)# placeholder_message = HumanMessage(content='Example output:')- self._add_message_with_type(placeholder_message, message_type='init')+ self._add_message_with_type(placeholder_message)# Create base example contentexample_content = {@@ -173,18 +205,18 @@ After writing todo.md, I can also initialize a github.md file to accumulate theThe file system actions do not change the browser state, so I can also click on the bytedance/UI-TARS-desktop (index [4]) to start collecting information."""example_tool_call_1 = AssistantMessage(content=json.dumps(example_content), cache=True)- self._add_message_with_type(example_tool_call_1, message_type='init')+ self._add_message_with_type(example_tool_call_1)self._add_message_with_type(UserMessage(content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',cache=True,),- message_type='init',)def add_new_task(self, new_task: str) -> None:self.task = new_task- self.state.agent_history_description += f'\n<s>User updated <user_request> to: {new_task}</s>\n'+ task_update_item = HistoryItem(system_message=f'User updated <user_request> to: {new_task}')+ self.state.agent_history_items.append(task_update_item)def _update_agent_history_description(self,@@ -196,7 +228,7 @@ The file system actions do not change the browser state, so I can also click onif result is None:result = []- step_number = step_info.step_number if step_info else 'unknown'+ step_number = step_info.step_number if step_info else Noneself.state.read_state_description = ''@@ -220,23 +252,23 @@ The file system actions do not change the browser state, so I can also click onif action_results:action_results = f'Action Results:\n{action_results}'- action_results = action_results.strip('\n')+ action_results = action_results.strip('\n') if action_results else None- # Handle case where model_output is None (e.g., parsing failed)+ # Build the history itemif model_output is None:- if isinstance(step_number, int) and step_number > 0:- self.state.agent_history_description += f"""<step_{step_number}>-Agent failed to output in the right format.-</step_{step_number}>-"""+ # Only add error history item if we have a valid step number+ if step_number is not None and step_number > 0:+ history_item = HistoryItem(step_number=step_number, error='Agent failed to output in the right format.')+ self.state.agent_history_items.append(history_item)else:- self.state.agent_history_description += f"""<step_{step_number}>-Evaluation of Previous Step: {model_output.current_state.evaluation_previous_goal}-Memory: {model_output.current_state.memory}-Next Goal: {model_output.current_state.next_goal}-{action_results}-</step_{step_number}>-"""+ history_item = HistoryItem(+ step_number=step_number,+ evaluation_previous_goal=model_output.current_state.evaluation_previous_goal,+ memory=model_output.current_state.memory,+ next_goal=model_output.current_state.next_goal,+ action_results=action_results,+ )+ self.state.agent_history_items.append(history_item)def _get_sensitive_data_description(self, current_page_url) -> str:sensitive_data = self.sensitive_data@@ -284,7 +316,7 @@ Next Goal: {model_output.current_state.next_goal}state_message = AgentMessagePrompt(browser_state_summary=browser_state_summary,file_system=self.file_system,- agent_history_description=self.state.agent_history_description,+ agent_history_description=self.agent_history_description,read_state_description=self.state.read_state_description,task=self.task,include_attributes=self.include_attributes,@@ -346,16 +378,15 @@ Next Goal: {model_output.current_state.next_goal}# Log message history for debugginglogger.debug(self._log_history_lines())- self.last_input_messages = [m.message for m in self.state.history.messages]+ self.last_input_messages = list(self.state.history.messages)return self.last_input_messagesdef _add_message_with_type(self,message: BaseMessage,position: int | None = None,- message_type: SupportedMessageTypes | None = None,) -> None:- """Add message with token count metadata+ """Add message to historyposition: None for last, -1 for second last, etc."""@@ -363,8 +394,7 @@ Next Goal: {model_output.current_state.next_goal}if self.sensitive_data:message = self._filter_sensitive_data(message)- metadata = MessageMetadata(message_type=message_type)- self.state.history.add_message(message, metadata, position)+ self.state.history.add_message(message, position)@time_execution_sync('--filter_sensitive_data')def _filter_sensitive_data(self, message: BaseMessage) -> BaseMessage:diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex 9e605fa34..351a938f2 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import TYPE_CHECKING, Literal+from typing import TYPE_CHECKINGfrom pydantic import BaseModel, ConfigDict, Field@@ -13,43 +13,74 @@ if TYPE_CHECKING:pass-SupportedMessageTypes = Literal['init', 'memory']+class HistoryItem(BaseModel):+ """Represents a single agent history item with its data and string representation"""+ step_number: int | None = None+ evaluation_previous_goal: str | None = None+ memory: str | None = None+ next_goal: str | None = None+ action_results: str | None = None+ error: str | None = None+ system_message: str | None = None-class MessageMetadata(BaseModel):- """Metadata for a message"""+ model_config = ConfigDict(arbitrary_types_allowed=True)- message_type: SupportedMessageTypes | None = None+ def model_post_init(self, __context) -> None:+ """Validate that error and system_message are not both provided"""+ if self.error is not None and self.system_message is not None:+ raise ValueError('Cannot have both error and system_message at the same time')++ def to_string(self) -> str:+ """Get string representation of the history item"""+ step_str = f'step_{self.step_number}' if self.step_number is not None else 'step_unknown'++ if self.error:+ return f"""<{step_str}>+{self.error}+</{step_str}>"""+ elif self.system_message:+ return f"""<sys>+{self.system_message}+</sys>"""+ else:+ content_parts = [+ f'Evaluation of Previous Step: {self.evaluation_previous_goal}',+ f'Memory: {self.memory}',+ f'Next Goal: {self.next_goal}',+ ]+ if self.action_results:+ content_parts.append(self.action_results)-class ManagedMessage(BaseModel):- """A message with its metadata"""+ content = '\n'.join(content_parts)- message: BaseMessage- metadata: MessageMetadata = Field(default_factory=MessageMetadata)+ return f"""<{step_str}>+{content}+</{step_str}>"""class MessageHistory(BaseModel):- """History of messages with metadata"""+ """History of messages"""- messages: list[ManagedMessage] = Field(default_factory=list)+ messages: list[BaseMessage] = Field(default_factory=list)model_config = ConfigDict(arbitrary_types_allowed=True)- def add_message(self, message: BaseMessage, metadata: MessageMetadata, position: int | None = None) -> None:- """Add message with metadata to history"""+ def add_message(self, message: BaseMessage, position: int | None = None) -> None:+ """Add message to history"""if position is None:- self.messages.append(ManagedMessage(message=message, metadata=metadata))+ self.messages.append(message)else:- self.messages.insert(position, ManagedMessage(message=message, metadata=metadata))+ self.messages.insert(position, message)def get_messages(self) -> list[BaseMessage]:"""Get all messages"""- return [m.message for m in self.messages]+ return self.messagesdef remove_last_state_message(self) -> None:"""Remove last state message from history"""- if len(self.messages) > 2 and isinstance(self.messages[-1].message, UserMessage):+ if len(self.messages) > 2 and isinstance(self.messages[-1], UserMessage):self.messages.pop()@@ -58,7 +89,9 @@ class MessageManagerState(BaseModel):history: MessageHistory = Field(default_factory=MessageHistory)tool_id: int = 1- agent_history_description: str = '<s>Agent initialized</s>\n'+ agent_history_items: list[HistoryItem] = Field(+ default_factory=lambda: [HistoryItem(step_number=0, system_message='Agent initialized')]+ )read_state_description: str = ''model_config = ConfigDict(arbitrary_types_allowed=True)diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 745589652..c9513fdc7 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -156,6 +156,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):include_attributes: list[str] = DEFAULT_INCLUDE_ATTRIBUTES,max_actions_per_step: int = 10,use_thinking: bool = True,+ max_history_items: int = 40,page_extraction_llm: BaseChatModel | None = None,planner_llm: BaseChatModel | None = None,planner_interval: int = 1, # Run planner every N steps@@ -222,12 +223,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):available_file_paths=available_file_paths,include_attributes=include_attributes,max_actions_per_step=max_actions_per_step,+ use_thinking=use_thinking,+ max_history_items=max_history_items,page_extraction_llm=page_extraction_llm,planner_llm=planner_llm,planner_interval=planner_interval,is_planner_reasoning=is_planner_reasoning,extend_planner_system_message=extend_planner_system_message,- use_thinking=use_thinking,calculate_cost=calculate_cost,)@@ -305,6 +307,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):include_attributes=self.settings.include_attributes,message_context=self.settings.message_context,sensitive_data=sensitive_data,+ max_history_items=self.settings.max_history_items,)if isinstance(browser, BrowserSession):diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.mdindex c63dfd44a..411fca56f 100644--- a/browser_use/agent/system_prompt.md+++ b/browser_use/agent/system_prompt.md@@ -34,7 +34,7 @@ Next Goal: Your goal for this stepAction Results: Your actions and their results</step_{{step_number}}>-and system messages wrapped in <s> tag.+and system messages wrapped in <sys> tag.</agent_history><user_request>@@ -61,7 +61,7 @@ Examples:Note that:- Only elements with numeric indexes in [] are interactive- (stacked) indentation (with \t) is important and means that the element is a (html) child of the element above (with a lower index)-- Elements with \* are new elements that were added after the previous step (if url has not changed)+- Elements tagged with `*[` are the new clickable elements that appeared on the website since the last step - if url has not changed.- Pure text elements without [] are not interactive.</browser_state>@@ -90,16 +90,13 @@ Strictly follow these rules while using the browser and navigating the web:<file_system>- You have access to a persistent file system which you can use to track progress, store results, and manage long tasks.-- Your file system is initialized with two files:- 1. `todo.md`: Use this to keep a checklist for known subtasks. Update it to mark completed items and track what remains. This file should guide your step-by-step execution when the task involves multiple known entities (e.g., a list of links or items to visit). The contents of this file will be also visible in your state. ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.- 2. `results.md`: Use this to accumulate extracted or generated results for the user. Append each new finding clearly and avoid duplication. This file serves as your output log.-- You can read, write, and append to files.+- Your file system is initialized with a `todo.md`: Use this to keep a checklist for known subtasks. Update it to mark completed items and track what remains. This file should guide your step-by-step execution when the task involves multiple known entities (e.g., a list of links or items to visit). ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.- Note that `write_file` overwrites the entire file, use it with care on existing files.- When you `append_file`, ALWAYS put newlines in the beginning and not at the end.-- If the file is too large, you are only given a preview of your file. Use read_file to see the full content if necessary.-- Always use the file system as the source of truth. Do not rely on memory alone for tracking task state.-- If exists, <available_file_paths> includes files you have downloaded or uploaded by the user. You DON'T HAVE write access to these files. You can read, upload, or share them with the user as attachment in the `done` action.-- DO NOT use the file system if the task is really short!+- If the file is too large, you are only given a preview of your file. Use `read_file` to see the full content if necessary.+- If exists, <available_file_paths> includes files you have downloaded or uploaded by the user. You can only read or upload these files but you don't have write access.+- If the task is really long, initialize a `results.md` file to accumulate your results.+- DO NOT use the file system if the task is less than 5 steps!</file_system><task_completion_rules>diff --git a/browser_use/agent/system_prompt_no_thinking.md b/browser_use/agent/system_prompt_no_thinking.mdindex 95f4fc2c4..dee039363 100644--- a/browser_use/agent/system_prompt_no_thinking.md+++ b/browser_use/agent/system_prompt_no_thinking.md@@ -34,7 +34,7 @@ Next Goal: Your goal for this stepAction Results: Your actions and their results</step_{{step_number}}>-and system messages wrapped in <s> tag.+and system messages wrapped in <sys> tag.</agent_history><user_request>@@ -56,12 +56,12 @@ Interactive Elements: All interactive elements will be provided in format as [inExamples:[33]<div>User form</div>-\t*[35]*<button aria-label='Submit form'>Submit</button>+\t*[35]<button aria-label='Submit form'>Submit</button>Note that:- Only elements with numeric indexes in [] are interactive- (stacked) indentation (with \t) is important and means that the element is a (html) child of the element above (with a lower index)-- Elements with \* are new elements that were added after the previous step (if url has not changed)+- Elements tagged with `*[` are the new clickable elements that appeared on the website since the last step - if url has not changed.- Pure text elements without [] are not interactive.</browser_state>@@ -90,16 +90,13 @@ Strictly follow these rules while using the browser and navigating the web:<file_system>- You have access to a persistent file system which you can use to track progress, store results, and manage long tasks.-- Your file system is initialized with two files:- 1. `todo.md`: Use this to keep a checklist for known subtasks. Update it to mark completed items and track what remains. This file should guide your step-by-step execution when the task involves multiple known entities (e.g., a list of links or items to visit). The contents of this file will be also visible in your state. ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.- 2. `results.md`: Use this to accumulate extracted or generated results for the user. Append each new finding clearly and avoid duplication. This file serves as your output log.-- You can read, write, and append to files.+- Your file system is initialized with a `todo.md`: Use this to keep a checklist for known subtasks. Update it to mark completed items and track what remains. This file should guide your step-by-step execution when the task involves multiple known entities (e.g., a list of links or items to visit). ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.- Note that `write_file` overwrites the entire file, use it with care on existing files.- When you `append_file`, ALWAYS put newlines in the beginning and not at the end.-- If the file is too large, you are only given a preview of your file. Use read_file to see the full content if necessary.-- Always use the file system as the source of truth. Do not rely on memory alone for tracking task state.+- If the file is too large, you are only given a preview of your file. Use `read_file` to see the full content if necessary.- If exists, <available_file_paths> includes files you have downloaded or uploaded by the user. You can only read or upload these files but you don't have write access.-- DO NOT use the file system if the task is really short!+- If the task is really long, initialize a `results.md` file to accumulate your results.+- DO NOT use the file system if the task is less than 5 steps!</file_system><task_completion_rules>diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex c29482110..6b717d5c1 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -54,6 +54,7 @@ class AgentSettings(BaseModel):]max_actions_per_step: int = 10use_thinking: bool = True+ max_history_items: int = 40page_extraction_llm: BaseChatModel | None = Noneplanner_llm: BaseChatModel | None = Nonediff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 783a0afe1..fa4cfceab 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -25,7 +25,7 @@ os.environ['PW_TEST_SCREENSHOT_NO_FONTS_READY'] = '1' # https://github.com/micrimport anyioimport psutil-from playwright._impl._api_structures import FloatRect, ViewportSize+from playwright._impl._api_structures import ViewportSizefrom pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validatorfrom uuid_extensions import uuid7str@@ -248,12 +248,12 @@ class BrowserSession(BaseModel):return self._loggerdef __repr__(self) -> str:- is_copy = '©' if self._original_browser_session else '1️⃣ '- return f'BrowserSession🆂 {self.id[-4:]}{is_copy}{str(id(self))[-2:]} ({self._connection_str}, profile={self.browser_profile})'+ is_copy = '©' if self._original_browser_session else '#'+ return f'BrowserSession🆂 {self.id[-4:]} {is_copy}{str(id(self))[-2:]} ({self._connection_str}, profile={self.browser_profile})'def __str__(self) -> str:- is_copy = '©' if self._original_browser_session else '1️⃣ '- return f'BrowserSession🆂 {self.id[-4:]}{is_copy}{str(id(self))[-2:]} 🅟 {str(id(self.agent_current_page))[-2:]}'+ is_copy = '©' if self._original_browser_session else '#'+ return f'BrowserSession🆂 {self.id[-4:]} {is_copy}{str(id(self))[-2:]} 🅟 {str(id(self.agent_current_page))[-2:]}'# better to force people to get it from the right object, "only one way to do it" is better python# def __getattr__(self, key: str) -> Any:@@ -725,7 +725,7 @@ class BrowserSession(BaseModel):full_page=False,# scale='css',timeout=self.browser_profile.default_timeout or 30000,- clip=FloatRect(**clip) if clip else None,+ # clip=FloatRect(**clip) if clip else None,animations='allow',caret='initial',)@@ -2714,27 +2714,28 @@ class BrowserSession(BaseModel):# This prevents timeouts on very long pages# 1. Get current viewport and page dimensions including scroll position- dimensions = await page.evaluate("""() => {- return {- width: window.innerWidth,- height: window.innerHeight,- pageHeight: document.documentElement.scrollHeight,- devicePixelRatio: window.devicePixelRatio || 1,- scrollX: window.pageXOffset || document.documentElement.scrollLeft || 0,- scrollY: window.pageYOffset || document.documentElement.scrollTop || 0- };- }""")+ # dimensions = await page.evaluate("""() => {+ # return {+ # width: window.innerWidth,+ # height: window.innerHeight,+ # pageWidth: document.documentElement.scrollWidth,+ # pageHeight: document.documentElement.scrollHeight,+ # devicePixelRatio: window.devicePixelRatio || 1,+ # scrollX: window.pageXOffset || document.documentElement.scrollLeft || 0,+ # scrollY: window.pageYOffset || document.documentElement.scrollTop || 0+ # };+ # }""")++ # When full_page=False, screenshot captures the current viewport+ # The clip parameter uses viewport coordinates (0,0 is top-left of viewport)+ # We just need to ensure the clip dimensions don't exceed our maximums+ # clip_width = min(dimensions['width'], MAX_SCREENSHOT_WIDTH)+ # clip_height = min(dimensions['height'], MAX_SCREENSHOT_HEIGHT)# Take screenshot using our retry-decorated method- return await self._take_screenshot_hybrid(- page,- clip={- 'x': dimensions['scrollX'],- 'y': dimensions['scrollY'],- 'width': min(dimensions['width'], MAX_SCREENSHOT_WIDTH),- 'height': min(dimensions['height'], MAX_SCREENSHOT_HEIGHT),- },- )+ # Don't pass clip parameter - let Playwright capture the full viewport+ # It will automatically handle cases where viewport extends beyond page content+ return await self._take_screenshot_hybrid(page)except Exception as e:self.logger.error(f'❌ Failed to take screenshot after retries: {type(e).__name__}: {e}')raisediff --git a/browser_use/cli.py b/browser_use/cli.pyindex 975ea8f25..17d5199bc 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -855,8 +855,8 @@ class BrowserUseApp(App):# Extract original task(s)original_tasks = []for msg in message_history:- if hasattr(msg, 'message') and hasattr(msg.message, 'content'):- content = msg.message.content+ if hasattr(msg, 'content'):+ content = msg.contentif isinstance(content, str) and 'Your ultimate task is:' in content:task_text = content.split('"""')[1].strip()original_tasks.append(task_text)diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 782e8ae62..919b61b60 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -331,10 +331,12 @@ class Controller(Generic[Context]):@self.registry.action("""Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.Only use this for extracting info from a single product/article page, not for entire listings or search results pages.+Set extract_links=True ONLY if your query requires extracting links/URLs from the page.""",)async def extract_structured_data(query: str,+ extract_links: bool,page: Page,page_extraction_llm: BaseChatModel,file_system: FileSystem,@@ -344,13 +346,8 @@ Only use this for extracting info from a single product/article page, not for enimport markdownifystrip = []- include_links = False- lower_query = query.lower()- url_keywords = ['url', 'links']- if any(keyword in lower_query for keyword in url_keywords):- include_links = True- if not include_links:+ if not extract_links:strip = ['a', 'img']# Run markdownify in a thread pool to avoid blocking the event loopdiff --git a/browser_use/controller/views.py b/browser_use/controller/views.pyindex fff18926a..50c4796ad 100644--- a/browser_use/controller/views.py+++ b/browser_use/controller/views.py@@ -15,13 +15,11 @@ class GoToUrlAction(BaseModel):class ClickElementAction(BaseModel):index: int- xpath: str | None = Noneclass InputTextAction(BaseModel):index: inttext: str- xpath: str | None = Noneclass DoneAction(BaseModel):diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.pyindex c4a97e18a..eb823e9fd 100644--- a/browser_use/filesystem/file_system.py+++ b/browser_use/filesystem/file_system.py@@ -124,7 +124,7 @@ class FileSystem:self.files = {}if create_default_files:- self.default_files = ['results.md', 'todo.md']+ self.default_files = ['todo.md']self._create_default_files()self.extracted_content_count = 0diff --git a/browser_use/llm/openai/chat.py b/browser_use/llm/openai/chat.pyindex fb4f83083..2b49ea20f 100644--- a/browser_use/llm/openai/chat.py+++ b/browser_use/llm/openai/chat.py@@ -6,6 +6,7 @@ import httpxfrom openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitErrorfrom openai.types.chat.chat_completion import ChatCompletionfrom openai.types.shared.chat_model import ChatModel+from openai.types.shared_params.reasoning_effort import ReasoningEffortfrom openai.types.shared_params.response_format_json_schema import JSONSchema, ResponseFormatJSONSchemafrom pydantic import BaseModel@@ -18,6 +19,8 @@ from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsageT = TypeVar('T', bound=BaseModel)+ReasoningModels: list[ChatModel | str] = ['o4-mini', 'o3', 'o3-mini', 'o1', 'o1-pro', 'o3-pro']+@dataclassclass ChatOpenAI(BaseChatModel):@@ -33,6 +36,7 @@ class ChatOpenAI(BaseChatModel):# Model paramstemperature: float | None = None+ reasoning_effort: ReasoningEffort = 'low'# Client initialization parametersapi_key: str | None = None@@ -132,10 +136,19 @@ class ChatOpenAI(BaseChatModel):openai_messages = OpenAIMessageSerializer.serialize_messages(messages)try:+ reasoning_effort_dict: dict = {}+ if self.model in ReasoningModels:+ reasoning_effort_dict = {+ 'reasoning_effort': self.reasoning_effort,+ }+if output_format is None:# Return string responseresponse = await self.get_client().chat.completions.create(- model=self.model, messages=openai_messages, temperature=self.temperature+ model=self.model,+ messages=openai_messages,+ temperature=self.temperature,+ **reasoning_effort_dict,)usage = self._get_usage(response)@@ -157,6 +170,7 @@ class ChatOpenAI(BaseChatModel):messages=openai_messages,temperature=self.temperature,response_format=ResponseFormatJSONSchema(json_schema=response_format, type='json_schema'),+ **reasoning_effort_dict,)if response.choices[0].message.content is None:diff --git a/docs/customize/agent-settings.mdx b/docs/customize/agent-settings.mdxindex b7d50b97a..ff25c4e3e 100644--- a/docs/customize/agent-settings.mdx+++ b/docs/customize/agent-settings.mdx@@ -161,8 +161,8 @@ Specify the action as a dictionary where the key is the action name and the valu```pythoninitial_actions = [- {'go_to_url': {'url': 'https://www.google.com', 'new_tab': true}},- {'go_to_url': {'url': 'https://en.wikipedia.org/wiki/Randomness', 'new_tab': true}},+ {'go_to_url': {'url': 'https://www.google.com', 'new_tab': True}},+ {'go_to_url': {'url': 'https://en.wikipedia.org/wiki/Randomness', 'new_tab': True}},{'scroll_down': {'amount': 1000}},]agent = Agent(diff --git a/eval/judge_system.py b/eval/judge_system.pyindex 64cf78ced..3072b0723 100644--- a/eval/judge_system.py+++ b/eval/judge_system.py@@ -29,40 +29,34 @@ logger = logging.getLogger(__name__)class ErrorCategory(Enum):# Access & Authentication- CAPTCHA_CHALLENGE = 'captcha_challenge'- LOGIN_REQUIRED = 'login_required'+ CAPTCHA = 'captcha'+ LOGIN_FAILED = 'login_failed'++ # LLMRATE_LIMITED = 'rate_limited'+ LLM_CALL_ERROR = 'llm_call_error'- # Agent Behavior Issues+ # Planning / contextINFINITE_LOOP = 'infinite_loop'- CONTEXT_LOSS = 'missing_user_data'+ WRONG_OUTPUT_FORMAT = 'wrong_output_format'- # Browser & Technical- ELEMENT_NOT_FOUND = 'element_not_found'- CLICK_FAILURE = 'click_failure'- LOAD_TIMEOUT = 'load_timeout'- JAVASCRIPT_ERROR = 'javascript_error'- MAX_STEPS_REACHED = 'max_steps_reached'+ # Browser+ WAIT_TOO_SHORT = 'wait_too_short'+ BROWSER_CRASHES = 'browser_crashes'+ ELEMENT_INTERACTION_ERROR = 'element_interaction_error'+ IFRAME_ISSUES = 'iframe_issues'- CONTENT_PARSING_ERROR = 'content_parsing_error'+ # Tools+ TOOL_FAILED = 'tool_failed'- # Enhanced Detection Categories- NAVIGATION_CONFUSION = 'navigation_confusion'- FORM_FILLING_ERROR = 'form_filling_error'- IFRAME_ISSUES = 'iframe_issues'- BROWSER_CRASHES = 'browser_crashes'+ # Task+ PARTIAL_OUTPUT = 'partial_output'IMPOSSIBLE_TASK = 'impossible_task'- # Browser-Use Specific Categories- INVALID_ELEMENT_INDEX = 'invalid_element_index' # Using non-existent [index] values+ # File SystemFILE_SYSTEM_MISUSE = 'file_system_misuse' # Not saving results or tracking progress-EXTRACT_DATA_MISUSE = 'extract_data_misuse' # Wrong usage of extract_structured_data- # Output & Task Completion Issues- PARTIAL_OUTPUT = 'partial_output'- WRONG_OUTPUT_FORMAT = 'wrong_output_format'-class TaskCategory(Enum):EXTRACTION = 'extraction'@@ -298,7 +292,7 @@ The browser-use agent operates in iterative loops receiving structured input:**CRITICAL: BROWSER STATE CONTAINS READABLE TEXT**- The DOM is converted to text with indexed interactive elements: [index]<type>text content</type>- Agent sees the browser_state of the current viewport at every step without needing extract_structured_data-- extract_structured_data gets the markdown of the entire page and not just the visible part+- extract_structured_data gets the markdown of the entire page and not just the visible part, it then parses it to structured data based on a query and saves it to a markdown file and shows it into the read state- Instead of extract_structured_data the agent can also scroll to get more information in the browser_state- The browser_state is the ground truth, but can be improved if information is missing- The agent can also read information directly from the input screenshot@@ -359,6 +353,20 @@ The browser-use agent operates in iterative loops receiving structured input:**ERROR CATEGORIES TO IDENTIFY:**{error_categories_text}+- Notes for the error categories:+- Use the main error - e.g. if we cant login and thats why we dont have an output we should use the login_failed error category+- The error category list is sequential - so check if an error before is matching better and use that instead+- captcha includes traditional captchas, Cloudflare challenges, and any other anti-bot protection systems that block task completion+- partial_output means we collected some part of the output but some is missing+- tool_failed means a tool like scrolling or file interaction failed or can be improved because functionality which would be helpful was missing - mention that in the improvement tips+- infinite_loop means the agent is stuck in a loop and not making progress+- wrong_output_format means the output is not in the requested format+- element_interaction_error means that our extraction of the DOM is not correct. E.g. we missed to detect a crucial button and the agent does not see it with a [index]. This can be verified if you look how we highlight elements in the screenshot.+- iframe_issues means we dont parse elements in the iframe correctly. E.g. we missed to detect a crucial button and the agent does not see it with a [index].+- impossible_task means the task is impossible to complete because the said is down or information is missing+- file_system_misuse means using read_file/write_file for short tasks when direct output would be appropriate. NOTE: extract_structured_data automatically saves to files as part of its core functionality - this is NOT file system misuse and expected behavior.++**Improvement Tips (Actionable Developer Guidance):**Format: "Error Category: Specific improvement suggestion"Examples:diff --git a/eval/service.py b/eval/service.pyindex aec66bf36..586b38a70 100644--- a/eval/service.py+++ b/eval/service.py@@ -535,6 +535,7 @@ class TaskResult:task: Anymax_steps: intlaminar_link: str | None = None+ github_workflow_url: str | None = Nonecompleted_stages: set[Stage] = field(default_factory=set)stage_data: dict[Stage, Any] = field(default_factory=dict)errors: list = field(default_factory=list)@@ -576,6 +577,7 @@ class TaskResult:'critical_error': self.critical_error,'server_save_failed': self.server_save_failed,'laminarTaskLink': self.laminar_link,+ 'githubWorkflowUrl': self.github_workflow_url,}# Add task execution data if available@@ -684,6 +686,11 @@ SUPPORTED_MODELS = {'model_name': 'claude-3-5-sonnet-20241022','api_key_env': 'ANTHROPIC_API_KEY',},+ 'claude-3.5-haiku-latest': {+ 'provider': 'anthropic',+ 'model_name': 'claude-3-5-haiku-latest',+ 'api_key_env': 'ANTHROPIC_API_KEY',+ },'claude-3.7-sonnet-exp': {'provider': 'anthropic','model_name': 'claude-3-7-sonnet-20250219',@@ -716,8 +723,8 @@ SUPPORTED_MODELS = {'gemini-1.5-flash': {'provider': 'google', 'model_name': 'gemini-1.5-flash-latest', 'api_key_env': 'GEMINI_API_KEY'},'gemini-2.0-flash-lite': {'provider': 'google', 'model_name': 'gemini-2.0-flash-lite', 'api_key_env': 'GEMINI_API_KEY'},'gemini-2.0-flash': {'provider': 'google', 'model_name': 'gemini-2.0-flash', 'api_key_env': 'GEMINI_API_KEY'},- 'gemini-2.5-pro': {'provider': 'google', 'model_name': 'gemini-2.5-pro-preview-03-25', 'api_key_env': 'GEMINI_API_KEY'},- 'gemini-2.5-flash': {'provider': 'google', 'model_name': 'gemini-2.5-flash-latest', 'api_key_env': 'GEMINI_API_KEY'},+ 'gemini-2.5-pro': {'provider': 'google', 'model_name': 'gemini-2.5-pro', 'api_key_env': 'GEMINI_API_KEY'},+ 'gemini-2.5-flash': {'provider': 'google', 'model_name': 'gemini-2.5-flash', 'api_key_env': 'GEMINI_API_KEY'},'gemini-2.5-pro-preview-05-06': {'provider': 'google','model_name': 'gemini-2.5-pro-preview-05-06',@@ -731,6 +738,7 @@ SUPPORTED_MODELS = {# OpenAI'gpt-4.1': {'provider': 'openai', 'model_name': 'gpt-4.1-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},'gpt-4.1-mini': {'provider': 'openai', 'model_name': 'gpt-4.1-mini-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},+ 'gpt-o3': {'provider': 'openai', 'model_name': 'o3-2025-04-16', 'api_key_env': 'OPENAI_API_KEY'},'gpt-4.1-nano': {'provider': 'openai', 'model_name': 'gpt-4.1-nano-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},'gpt-4o': {'provider': 'openai', 'model_name': 'gpt-4o', 'api_key_env': 'OPENAI_API_KEY'},'gpt-4o-mini': {'provider': 'openai', 'model_name': 'gpt-4o-mini', 'api_key_env': 'OPENAI_API_KEY'},@@ -881,7 +889,7 @@ def get_llm(model_name: str):case 'openai':kwargs = {'model': config['model_name'], 'temperature': 0.0}# Must set temperatue=1 if model is gpt-o4-mini- if model_name == 'gpt-o4-mini':+ if model_name in ['gpt-o4-mini', 'gpt-o3']:kwargs['temperature'] = 1if api_key:kwargs['api_key'] = api_key@@ -1246,8 +1254,9 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3try:# Run comprehensive judge evaluation- comprehensive_result = await evaluate_task_with_comprehensive_judge(- task_folder=task_folder, model=model, max_images=10+ comprehensive_result = await asyncio.wait_for(+ evaluate_task_with_comprehensive_judge(task_folder=task_folder, model=model, max_images=10),+ timeout=180, # 3 minutes max for evaluation)if comprehensive_result.get('error'):@@ -1580,6 +1589,7 @@ async def run_task_with_semaphore(headless: bool,use_vision: bool,semaphore_runs: asyncio.Semaphore, # Pass semaphore as argument+ github_workflow_url: str | None = None,use_serp: bool = False,enable_memory: bool = False,memory_interval: int = 10,@@ -1651,7 +1661,9 @@ async def run_task_with_semaphore(logger.debug(f'Task {task.task_id}: No Laminar run ID available, skipping datapoint creation')# Initialize task result and basic setup- task_result = TaskResult(task.task_id, run_id, task.confirmed_task, task, max_steps_per_task, laminar_task_link)+ task_result = TaskResult(+ task.task_id, run_id, task.confirmed_task, task, max_steps_per_task, laminar_task_link, github_workflow_url+ )task_folder = Path(f'saved_trajectories/{task.task_id}')@@ -1845,7 +1857,13 @@ async def run_task_with_semaphore(# Create minimal task result for server reportingtry:task_result = TaskResult(- task.task_id, run_id, task.confirmed_task, task, max_steps_per_task, laminar_task_link+ task.task_id,+ run_id,+ task.confirmed_task,+ task,+ max_steps_per_task,+ laminar_task_link,+ github_workflow_url,)task_result.mark_critical_error(f'Initialization failed: {str(init_error)}')except Exception as result_error:@@ -1906,6 +1924,7 @@ async def run_multiple_tasks(convex_url: str,secret_key: str,eval_model: BaseChatModel,+ github_workflow_url: str | None = None,max_parallel_runs: int = 3,max_steps_per_task: int = 25,start_index: int = 0,@@ -1990,6 +2009,7 @@ async def run_multiple_tasks(headless=headless,use_vision=use_vision,semaphore_runs=semaphore_runs, # Pass the semaphore+ github_workflow_url=github_workflow_url,use_serp=use_serp,enable_memory=enable_memory,memory_interval=memory_interval,@@ -2252,6 +2272,7 @@ async def run_evaluation_pipeline(convex_url: str,secret_key: str,eval_model: BaseChatModel,+ github_workflow_url: str | None = None,max_parallel_runs: int = 3,max_steps_per_task: int = 25,start_index: int = 0,@@ -2304,6 +2325,7 @@ async def run_evaluation_pipeline(convex_url=convex_url,secret_key=secret_key,eval_model=eval_model,+ github_workflow_url=github_workflow_url,max_parallel_runs=max_parallel_runs,max_steps_per_task=max_steps_per_task,start_index=start_index,@@ -2385,6 +2407,8 @@ if __name__ == '__main__':)parser.add_argument('--use-mind2web-judge', action='store_true', help='Use original judge')parser.add_argument('--no-thinking', action='store_true', help='Disable thinking in agent system prompt')+ parser.add_argument('--use-anchor', action='store_true', help='Use anchor to navigate to the page')+ parser.add_argument('--github-workflow-url', type=str, default=None, help='GitHub workflow URL for tracking')# Single task mode argumentsparser.add_argument('--task-text', type=str, default=None, help='Task description for single task mode')@@ -2612,6 +2636,7 @@ if __name__ == '__main__':convex_url=convex_url,secret_key=secret_key,eval_model=eval_model,+ github_workflow_url=args.github_workflow_url,max_parallel_runs=parallel_runs,max_steps_per_task=args.max_steps,start_index=start_index,diff --git a/examples/features/sensitive_data.py b/examples/features/sensitive_data.pyindex 33206cc7b..76184a457 100644--- a/examples/features/sensitive_data.py+++ b/examples/features/sensitive_data.py@@ -12,9 +12,16 @@ from browser_use import Agentfrom browser_use.browser import BrowserProfilefrom browser_use.llm import ChatOpenAI+try:+ from lmnr import Laminar++ Laminar.initialize(project_api_key=os.getenv('LMNR_PROJECT_API_KEY'))+except Exception as e:+ print(f'Error initializing Laminar: {e}')+# Initialize the modelllm = ChatOpenAI(- model='gpt-4o',+ model='gpt-4.1',temperature=0.0,)# Simple case: the model will see x_name and x_password, but never the actual values.@@ -35,7 +42,7 @@ sensitive_data: dict[str, str | dict[str, str]] = {'https://*.google.com': {'g_email': '[email protected]', 'g_pass': 'google_password'},}# Update task to use one of the credentials above-task = 'Go to example.com and login with company_username and company_password'+task = 'Go to google.com and put the login information in the search bar.'# Always set allowed_domains when using sensitive_data for securityfrom browser_use.browser.session import BrowserSessiondiff --git a/pyproject.toml b/pyproject.tomlindex f990f3056..ba63f8640 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -17,7 +17,6 @@ dependencies = ["google-api-core>=2.25.0","httpx>=0.28.1","markdownify==1.1.0",- "mem0ai>=0.1.106","patchright>=1.52.5","playwright>=1.52.0","portalocker>=2.7.0,<3.0.0",diff --git a/tests/ci/test_browser_session_screenshots.py b/tests/ci/test_browser_session_screenshots.pyindex b1c15c8c9..e07fdda8f 100644--- a/tests/ci/test_browser_session_screenshots.py+++ b/tests/ci/test_browser_session_screenshots.py@@ -2,6 +2,7 @@Test that screenshots work correctly in headless browser mode."""+import asyncioimport base64from browser_use.browser import BrowserProfile, BrowserSession@@ -193,7 +194,7 @@ class TestHeadlessScreenshots:# Take screenshots from all sessions at the same timeprint('Taking screenshots from all 10 sessions simultaneously...')- screenshot_tasks = [session.take_screenshot(full_page=True) for session in browser_sessions]+ screenshot_tasks = [session.take_screenshot() for session in browser_sessions]screenshots = await asyncio.gather(*screenshot_tasks)# Verify all screenshots are valid@@ -221,9 +222,7 @@ class TestHeadlessScreenshots:# Also test taking regular (viewport) screenshots in parallelprint('Taking viewport screenshots from all sessions simultaneously...')- viewport_screenshots = await asyncio.gather(- *[session.take_screenshot(full_page=False) for session in browser_sessions]- )+ viewport_screenshots = await asyncio.gather(*[session.take_screenshot() for session in browser_sessions])# Verify viewport screenshotsfor i, screenshot in enumerate(viewport_screenshots):@@ -244,3 +243,69 @@ class TestHeadlessScreenshots:for i, result in enumerate(results):if isinstance(result, Exception):print(f'Warning: Session {i} kill raised exception: {type(result).__name__}: {result}')++ async def test_screenshot_at_bottom_of_page(self, httpserver):+ """Test screenshot capture when scrolled to bottom of page (regression test for clipping issue)"""+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=False,+ )+ )++ try:+ await browser_session.start()++ # Create a page with scrollable content+ httpserver.expect_request('/scrollable').respond_with_data(+ """<html>+ <head><title>Scrollable Page Test</title></head>+ <body style="margin: 0; padding: 0;">+ <div style="height: 3000px; background: linear-gradient(to bottom, red, yellow, green, blue);">+ <div style="position: absolute; top: 0; left: 10px; font-size: 24px;">Top of page</div>+ <div style="position: absolute; top: 50%; left: 10px; font-size: 24px;">Middle of page</div>+ <div style="position: absolute; bottom: 10px; left: 10px; font-size: 24px;">Bottom of page</div>+ </div>+ </body>+ </html>""",+ content_type='text/html',+ )++ # Navigate to test page+ await browser_session.navigate(httpserver.url_for('/scrollable'))+ page = browser_session.agent_current_page+ assert page is not None++ # Test 1: Screenshot at top of page (should work)+ screenshot_top = await browser_session.take_screenshot()+ assert screenshot_top is not None+ assert len(base64.b64decode(screenshot_top)) > 5000++ # Test 2: Screenshot at middle of page+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight / 2)')+ await asyncio.sleep(0.1) # Wait for scroll+ screenshot_middle = await browser_session.take_screenshot()+ assert screenshot_middle is not None+ assert len(base64.b64decode(screenshot_middle)) > 5000++ # Test 3: Screenshot at bottom of page (this was failing with clipping error)+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight)')+ await asyncio.sleep(0.1) # Wait for scroll++ # This should not raise "Clipped area is either empty or outside the resulting image" error+ screenshot_bottom = await browser_session.take_screenshot()+ assert screenshot_bottom is not None+ assert len(base64.b64decode(screenshot_bottom)) > 5000++ # Test 4: Screenshot when scrolled beyond page bottom (edge case)+ await page.evaluate('window.scrollTo(0, document.body.scrollHeight + 1000)')+ await asyncio.sleep(0.1)+ screenshot_beyond = await browser_session.take_screenshot()+ assert screenshot_beyond is not None+ assert len(base64.b64decode(screenshot_beyond)) > 5000++ print('✅ All screenshot positions tested successfully!')++ finally:+ await browser_session.stop()diff --git a/tests/ci/test_filesystem.py b/tests/ci/test_filesystem.pyindex 5f9a9b017..b005c432d 100644--- a/tests/ci/test_filesystem.py+++ b/tests/ci/test_filesystem.py@@ -138,14 +138,11 @@ class TestFileSystem:assert fs.data_dir.name == DEFAULT_FILE_SYSTEM_PATH# Check default files are created- assert 'results.md' in fs.filesassert 'todo.md' in fs.files- assert len(fs.files) == 2+ assert len(fs.files) == 1# Check files exist on disk- results_path = fs.data_dir / 'results.md'todo_path = fs.data_dir / 'todo.md'- assert results_path.exists()assert todo_path.exists()def test_filesystem_without_default_files(self, empty_filesystem):@@ -199,12 +196,6 @@ class TestFileSystem:"""Test getting files from the filesystem."""fs = temp_filesystem- # Get existing file- results_file = fs.get_file('results.md')- assert results_file is not None- assert isinstance(results_file, MarkdownFile)- assert results_file.name == 'results'-# Get non-existent filenon_existent = fs.get_file('nonexistent.md')assert non_existent is None@@ -218,16 +209,15 @@ class TestFileSystem:fs = temp_filesystemfiles = fs.list_files()- assert 'results.md' in filesassert 'todo.md' in files- assert len(files) == 2+ assert len(files) == 1def test_display_file(self, temp_filesystem):"""Test displaying file content."""fs = temp_filesystem# Display existing file- content = fs.display_file('results.md')+ content = fs.display_file('todo.md')assert content == '' # Default files are empty# Display non-existent file@@ -243,8 +233,8 @@ class TestFileSystem:fs = temp_filesystem# Read existing empty file- result = fs.read_file('results.md')- expected = 'Read from file results.md.\n<content>\n\n</content>'+ result = fs.read_file('todo.md')+ expected = 'Read from file todo.md.\n<content>\n\n</content>'assert result == expected# Read non-existent file@@ -326,17 +316,6 @@ class TestFileSystem:assert content1 == 'First extracted content'assert content2 == 'Second extracted content'- async def test_describe_empty_files(self, temp_filesystem):- """Test describing filesystem with empty files."""- fs = temp_filesystem-- description = fs.describe()-- # Should contain results.md but not todo.md (excluded from description)- assert 'results.md' in description- assert 'todo.md' not in description- assert '[empty file]' in description-async def test_describe_with_content(self, temp_filesystem):"""Test describing filesystem with files containing content."""fs = temp_filesystem@@ -392,15 +371,8 @@ class TestFileSystem:assert isinstance(state, FileSystemState)assert state.base_dir == str(fs.base_dir)assert state.extracted_content_count == 0- assert 'results.md' in state.filesassert 'todo.md' in state.files- # Check file data structure- results_data = state.files['results.md']- assert results_data['type'] == 'MarkdownFile'- assert 'data' in results_data- assert results_data['data']['name'] == 'results'-async def test_from_state(self, temp_filesystem):"""Test restoring filesystem from state."""fs = temp_filesystem@@ -503,7 +475,6 @@ class TestFileSystemEdgeCases:# Custom file should be gone, default files should existassert not custom_file.exists()- assert (fs2.data_dir / 'results.md').exists()assert (fs2.data_dir / 'todo.md').exists()fs2.nuke()