Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

mr cloudrunner

mertunsallfa60e747d991
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 576546428..7f49a8ebc 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -3,8 +3,6 @@ from __future__ import annotations
import json
import logging
-from pydantic import BaseModel
-
from browser_use.agent.message_manager.views import (
MessageMetadata,
SupportedMessageTypes,
@@ -96,14 +94,6 @@ def _log_format_message_line(message: BaseMessage, content: str, is_last_message
# ========== End of Logging Helper Functions ==========
-class MessageManagerSettings(BaseModel):
- include_attributes: list[str] = []
- message_context: str | None = None
- # Support both old format {key: value} and new format {domain: {key: value}}
- sensitive_data: dict[str, str | dict[str, str]] | None = None
- available_file_paths: list[str] | None = None
-
-
class MessageManager:
def __init__(
self,
@@ -111,20 +101,25 @@ class MessageManager:
system_message: SystemMessage,
file_system: FileSystem,
available_file_paths: list[str] | None = None,
- settings: MessageManagerSettings = MessageManagerSettings(),
state: MessageManagerState = MessageManagerState(),
use_thinking: bool = True,
+ include_attributes: list[str] | None = None,
+ message_context: str | None = None,
+ sensitive_data: dict[str, str | dict[str, str]] | None = None,
):
self.task = task
- self.settings = settings
self.state = state
self.system_prompt = system_message
self.file_system = file_system
- self.agent_history_description = '<s>Agent initialized</s>\n'
- self.read_state_description = ''
self.sensitive_data_description = ''
self.available_file_paths = available_file_paths
self.use_thinking = use_thinking
+
+ # Store settings as direct attributes instead of in a settings object
+ self.include_attributes = include_attributes or []
+ self.message_context = message_context
+ self.sensitive_data = sensitive_data
+
# Only initialize messages if state is empty
if len(self.state.history.messages) == 0:
self._init_messages()
@@ -185,52 +180,9 @@ The file system actions do not change the browser state, so I can also click on
message_type='init',
)
- placeholder_message = UserMessage(content='<example_2>Example thinking and tool call 2:')
- # self._add_message_with_tokens(placeholder_message, message_type='init')
-
- # TODO: add this back
- # example_tool_call_2 = AssistantMessage(
- # content=json.dumps(
- # {
- # 'name': 'AgentOutput',
- # 'args': {
- # 'current_state': {
- # 'thinking': """I
- # **Understanding the Current State:**
- # I am currently on Apple's main homepage, having successfully clicked on an 'Apple' link in the previous step. The page has loaded and I can see the typical Apple website layout with navigation elements. I can see an interactive element at index [4] that is labeled 'iPhone', which indicates this is a navigation link to Apple's iPhone product section.
-
- # **Evaluating the Previous Action:**
- # The click on the 'Apple' link was successful and brought me to Apple's homepage as expected. The page loaded properly and I can see the navigation structure including the iPhone link. This confirms that the previous navigation action worked correctly and I'm now in the right place to continue with the iPhone-related task.
-
- # **Tracking and Planning with todo.md:**
- # Based on the context, this seems to be part of a larger task involving Apple products. I should be prepared to update my todo.md file if there are multiple iPhone models or other Apple products to investigate. The current goal is to access the iPhone section to see what product information is available.
-
- # **Writing Intermediate Results:**
- # Once I reach the iPhone page, I'll need to extract information about different iPhone models, their specifications, prices, or other details. I should accumulate all findings in results.md in a structured format as I collect the information.
-
- # **Preparing what goes into my memory:**
- # I need to capture that I'm in the process of navigating to the iPhone section and preparing to collect product information.
-
- # **Planning my next action:**
- # My next action is to click on the iPhone link at index [4] to navigate to Apple's iPhone product page. This will give me access to the iPhone lineup and allow me to gather the requested information.
- # """,
- # 'evaluation_previous_goal': 'Clicked Apple link and reached the homepage. Verdict: Success',
- # 'memory': 'On Apple homepage with iPhone link at index [4].',
- # 'next_goal': 'Click iPhone link.',
- # },
- # 'action': [{'click_element_by_index': {'index': 4}}],
- # },
- # 'id': str(self.state.tool_id),
- # 'type': 'tool_call',
- # },
- # ),
- # )
- # self._add_message_with_tokens(example_tool_call_2, message_type='init')
- # self.add_tool_message(content='Clicked on index [4]. </example_2>', message_type='init')
-
def add_new_task(self, new_task: str) -> None:
self.task = new_task
- self.agent_history_description += f'\n<system>User updated USER REQUEST to: {new_task}</system>\n'
+ self.state.agent_history_description += f'\n<system>User updated USER REQUEST to: {new_task}</system>\n'
def _update_agent_history_description(
self,
@@ -244,13 +196,13 @@ The file system actions do not change the browser state, so I can also click on
result = []
step_number = step_info.step_number if step_info else 'unknown'
- self.read_state_description = ''
+ self.state.read_state_description = ''
action_results = ''
result_len = len(result)
for idx, action_result in enumerate(result):
if action_result.include_extracted_content_only_once and action_result.extracted_content:
- self.read_state_description += action_result.extracted_content + '\n'
+ self.state.read_state_description += action_result.extracted_content + '\n'
logger.debug(f'Added extracted_content to read_state_description: {action_result.extracted_content}')
if action_result.long_term_memory:
@@ -271,12 +223,12 @@ The file system actions do not change the browser state, so I can also click on
# Handle case where model_output is None (e.g., parsing failed)
if model_output is None:
if isinstance(step_number, int) and step_number > 0:
- self.agent_history_description += f"""<step_{step_number}>
+ self.state.agent_history_description += f"""<step_{step_number}>
Agent failed to output in the right format.
</step_{step_number}>
"""
else:
- self.agent_history_description += f"""<step_{step_number}>
+ 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}
@@ -285,7 +237,7 @@ Next Goal: {model_output.current_state.next_goal}
"""
def _get_sensitive_data_description(self, current_page_url) -> str:
- sensitive_data = self.settings.sensitive_data
+ sensitive_data = self.sensitive_data
if not sensitive_data:
return ''
@@ -330,10 +282,10 @@ 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.agent_history_description,
- read_state_description=self.read_state_description,
+ agent_history_description=self.state.agent_history_description,
+ read_state_description=self.state.read_state_description,
task=self.task,
- include_attributes=self.settings.include_attributes,
+ include_attributes=self.include_attributes,
step_info=step_info,
page_filtered_actions=page_filtered_actions,
sensitive_data=self.sensitive_data_description,
@@ -406,7 +358,7 @@ Next Goal: {model_output.current_state.next_goal}
"""
# filter out sensitive data from the message
- if self.settings.sensitive_data:
+ if self.sensitive_data:
message = self._filter_sensitive_data(message)
metadata = MessageMetadata(message_type=message_type)
@@ -417,14 +369,14 @@ Next Goal: {model_output.current_state.next_goal}
"""Filter out sensitive data from the message"""
def replace_sensitive(value: str) -> str:
- if not self.settings.sensitive_data:
+ if not self.sensitive_data:
return value
# Collect all sensitive values, immediately converting old format to new format
sensitive_values: dict[str, str] = {}
# Process all sensitive data entries
- for key_or_domain, content in self.settings.sensitive_data.items():
+ for key_or_domain, content in self.sensitive_data.items():
if isinstance(content, dict):
# Already in new format: {domain: {key: value}}
for key, val in content.items():
diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.py
index cac4124c3..9e605fa34 100644
--- a/browser_use/agent/message_manager/views.py
+++ b/browser_use/agent/message_manager/views.py
@@ -58,5 +58,7 @@ class MessageManagerState(BaseModel):
history: MessageHistory = Field(default_factory=MessageHistory)
tool_id: int = 1
+ agent_history_description: str = '<s>Agent initialized</s>\n'
+ read_state_description: str = ''
model_config = ConfigDict(arbitrary_types_allowed=True)
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 7940ec25a..58b2b1c34 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -36,7 +36,6 @@ from browser_use.agent.gif import create_history_gif
from browser_use.agent.memory import Memory, MemoryConfig
from browser_use.agent.message_manager.service import (
MessageManager,
- MessageManagerSettings,
)
from browser_use.agent.message_manager.utils import (
save_conversation,
@@ -295,15 +294,13 @@ class Agent(Generic[Context]):
use_thinking=self.settings.use_thinking,
).get_system_message(),
file_system=self.file_system,
- settings=MessageManagerSettings(
- include_attributes=self.settings.include_attributes,
- message_context=self.settings.message_context,
- sensitive_data=sensitive_data,
- available_file_paths=self.settings.available_file_paths,
- ),
available_file_paths=self.settings.available_file_paths,
state=self.state.message_manager_state,
use_thinking=self.settings.use_thinking,
+ # Settings that were previously in MessageManagerSettings
+ include_attributes=self.settings.include_attributes,
+ message_context=self.settings.message_context,
+ sensitive_data=sensitive_data,
)
# TODO: FIX MEMORY
@@ -502,7 +499,6 @@ class Agent(Generic[Context]):
if new_files:
self.settings.available_file_paths = list(current_files | new_files)
# Update message manager with new file paths
- self._message_manager.settings.available_file_paths = self.settings.available_file_paths
self._message_manager.available_file_paths = self.settings.available_file_paths
self.logger.info(
@@ -514,24 +510,50 @@ class Agent(Generic[Context]):
self.logger.info(f'πŸ“ No new downloads detected (tracking {len(current_files)} files)')
def _set_file_system(self, file_system_path: str | None = None) -> None:
- # Initialize file system
- if file_system_path:
- self.file_system = FileSystem(file_system_path)
- self.file_system_path = file_system_path
- else:
- # create a temporary file system using agent ID
- base_tmp = tempfile.gettempdir() # e.g., /tmp on Unix
- self.file_system_path = os.path.join(base_tmp, f'browser_use_agent_{self.id}')
- self.file_system = FileSystem(self.file_system_path)
+ # Check for conflicting parameters
+ if self.state.file_system_state and file_system_path:
+ raise ValueError(
+ 'Cannot provide both file_system_state (from agent state) and file_system_path. '
+ 'Either restore from existing state or create new file system at specified path, not both.'
+ )
- logger.info(f'πŸ’Ύ File system path: {self.file_system_path}')
+ # Check if we should restore from existing state first
+ if self.state.file_system_state:
+ try:
+ # Restore file system from state
+ self.file_system = FileSystem.from_state(self.state.file_system_state)
+ self.file_system_path = str(self.file_system.base_dir.parent)
+ logger.info(f'πŸ’Ύ File system restored from state: {self.file_system_path}')
+ return
+ except Exception as e:
+ logger.warning(f'πŸ’Ύ Failed to restore file system from state: {e}. Creating new file system.')
+ # Fall through to create new file system
+
+ # Initialize new file system
+ try:
+ if file_system_path:
+ self.file_system = FileSystem(file_system_path)
+ self.file_system_path = file_system_path
+ else:
+ # create a temporary file system using agent ID
+ base_tmp = tempfile.gettempdir() # e.g., /tmp on Unix
+ self.file_system_path = os.path.join(base_tmp, f'browser_use_agent_{self.id}')
+ self.file_system = FileSystem(self.file_system_path)
+ except Exception as e:
+ logger.error(f'πŸ’Ύ Failed to initialize file system: {e}.')
+ raise e
- # TODO: move this logic to special registries -> we have methods to combine controllers
+ # Save file system state to agent state
+ self.state.file_system_state = self.file_system.get_state()
+
+ logger.info(f'πŸ’Ύ File system path: {self.file_system_path}')
# if file system is set, add actions to the controller
- @self.controller.registry.action('Write content to file_name in file system, use only .md or .txt extensions.')
+ @self.controller.registry.action('Write content to file_name in file system.')
async def write_file(file_name: str, content: str):
result = await self.file_system.write_file(file_name, content)
+ # Update agent state with new file system state
+ self.state.file_system_state = self.file_system.get_state()
logger.info(f'πŸ’Ύ {result}')
return ActionResult(
extracted_content=result,
@@ -542,6 +564,8 @@ class Agent(Generic[Context]):
@self.controller.registry.action('Append content to file_name in file system')
async def append_file(file_name: str, content: str):
result = await self.file_system.append_file(file_name, content)
+ # Update agent state with new file system state
+ self.state.file_system_state = self.file_system.get_state()
logger.info(f'πŸ’Ύ {result}')
return ActionResult(
extracted_content=result,
@@ -566,6 +590,14 @@ class Agent(Generic[Context]):
include_extracted_content_only_once=True,
)
+ def save_file_system_state(self) -> None:
+ """Save current file system state to agent state"""
+ if self.file_system:
+ self.state.file_system_state = self.file_system.get_state()
+ else:
+ logger.error('πŸ’Ύ File system is not set up. Cannot save state.')
+ raise ValueError('File system is not set up. Cannot save state.')
+
def _set_message_context(self) -> str | None:
return self.settings.message_context
@@ -829,6 +861,9 @@ class Agent(Generic[Context]):
# Log step completion summary
self._log_step_completion_summary(step_start_time, result)
+ # Save file system state after step completion
+ self.save_file_system_state()
+
# Emit both step created and executed events
if browser_state_summary and model_output:
# Extract key step data for the event
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index effdd5494..d9255aaf1 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -19,6 +19,7 @@ from browser_use.dom.history_tree_processor.service import (
HistoryTreeProcessor,
)
from browser_use.dom.views import SelectorMap
+from browser_use.filesystem.file_system import FileSystemState
from browser_use.llm.base import BaseChatModel
@@ -73,6 +74,7 @@ class AgentState(BaseModel):
stopped: bool = False
message_manager_state: MessageManagerState = Field(default_factory=MessageManagerState)
+ file_system_state: FileSystemState | None = None
# class Config:
# arbitrary_types_allowed = True
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index 76d6eedbb..0d0043c5e 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -1,192 +1,445 @@
import asyncio
import re
+from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
+from typing import Any
-INVALID_FILENAME_ERROR_MESSAGE = 'Error: Invalid filename format. Must be alphanumeric with .txt or .md extension.'
+from pydantic import BaseModel, Field
+INVALID_FILENAME_ERROR_MESSAGE = 'Error: Invalid filename format. Must be alphanumeric with supported extension.'
-class FileSystem:
- def __init__(self, dir_path: str):
- # Create a base directory
- self.base_dir = Path(dir_path)
- self.base_dir.mkdir(parents=True, exist_ok=True)
+
+class FileSystemError(Exception):
+ """Custom exception for file system operations that should be shown to LLM"""
+
+ pass
+
+
+class BaseFile(BaseModel, ABC):
+ """Base class for all file types"""
+
+ name: str
+ content: str = ''
+
+ class Config:
+ arbitrary_types_allowed = True
+
+ @property
+ @abstractmethod
+ def extension(self) -> str:
+ """Return the file extension"""
+ pass
+
+ @abstractmethod
+ def validate_content(self, content: str) -> bool:
+ """Validate if content is appropriate for this file type"""
+ pass
+
+ @abstractmethod
+ def read_file_content(self) -> str:
+ """Return file content formatted for LLM consumption"""
+ pass
+
+ @abstractmethod
+ def write_file_content(self, content: str | Any) -> str:
+ """Write content to file and return success message"""
+ pass
+
+ @abstractmethod
+ def append_file_content(self, content: str) -> str:
+ """Append content to file and return success message. May raise FileSystemError if not supported."""
+ pass
+
+ @abstractmethod
+ def display_content(self) -> str:
+ """Return content formatted for the describe function"""
+ pass
+
+ def update_content(self, content: str) -> None:
+ """Update file content"""
+ if not self.validate_content(content):
+ raise ValueError(f'Invalid content for {self.__class__.__name__}')
+ self.content = content
+
+ def get_size(self) -> int:
+ """Get file size in characters"""
+ return len(self.content)
+
+ def get_line_count(self) -> int:
+ """Get number of lines in file"""
+ return len(self.content.splitlines())
+
+ @property
+ def full_name(self) -> str:
+ """Get full filename with extension"""
+ return f'{self.name}.{self.extension}'
+
+
+class MarkdownFile(BaseFile):
+ """Markdown file implementation"""
+
+ @property
+ def extension(self) -> str:
+ return 'md'
+
+ def validate_content(self, content: str) -> bool:
+ """Markdown accepts any text content"""
+ return isinstance(content, str)
+
+ def read_file_content(self) -> str:
+ """Return markdown content as-is"""
+ return self.content
+
+ def write_file_content(self, content: str | Any) -> str:
+ """Write content to markdown file"""
+ content_str = str(content) if not isinstance(content, str) else content
+ self.update_content(content_str)
+ return f'Data written to {self.full_name} successfully.'
+
+ def append_file_content(self, content: str) -> str:
+ """Append content to markdown file"""
+ new_content = self.content + content
+ self.update_content(new_content)
+ return f'Data appended to {self.full_name} successfully.'
+
+ def display_content(self) -> str:
+ """Return content for display in describe function"""
+ return self.content
+
+
+class TxtFile(BaseFile):
+ """Plain text file implementation"""
+
+ @property
+ def extension(self) -> str:
+ return 'txt'
+
+ def validate_content(self, content: str) -> bool:
+ """Text files accept any string content"""
+ return isinstance(content, str)
+
+ def read_file_content(self) -> str:
+ """Return text content as-is"""
+ return self.content
+
+ def write_file_content(self, content: str | Any) -> str:
+ """Write content to text file"""
+ content_str = str(content) if not isinstance(content, str) else content
+ self.update_content(content_str)
+ return f'Text content written to {self.full_name} successfully.'
+
+ def append_file_content(self, content: str) -> str:
+ """Append content to text file"""
+ new_content = self.content + content
+ self.update_content(new_content)
+ return f'Content appended to {self.full_name} successfully.'
+
+ def display_content(self) -> str:
+ """Return content for display in describe function"""
+ return self.content
+
+
+class FileSystemState(BaseModel):
+ """Serializable state of the file system"""
+
+ files: dict[str, dict[str, Any]] = Field(default_factory=dict)
+ base_dir: str
+ extracted_content_count: int = 0
+
+ class Config:
+ arbitrary_types_allowed = True
+
+
+class FileSystem(BaseModel):
+ """Enhanced file system with in-memory storage and multiple file type support"""
+
+ base_dir: Path
+ files: dict[str, BaseFile] = Field(default_factory=dict)
+ extracted_content_count: int = 0
+
+ class Config:
+ arbitrary_types_allowed = True
+ validate_by_name = True
+
+ # File type registry
+ _file_types: dict[str, type[BaseFile]] = {
+ 'md': MarkdownFile,
+ 'txt': TxtFile,
+ }
+
+ def __init__(self, dir_path: str, **kwargs):
+ # Handle the Path conversion before calling super().__init__
+ base_dir = Path(dir_path)
+ base_dir.mkdir(parents=True, exist_ok=True)
# Create and use a dedicated subfolder for all operations
- self.dir = self.base_dir / 'data_storage'
- if self.dir.exists():
+ data_dir = base_dir / 'browseruse_agent_data'
+ if data_dir.exists():
raise ValueError(
'File system directory already exists - stopping for safety purposes. Please delete it first if you want to use this directory.'
)
- self.dir.mkdir(exist_ok=True)
+ data_dir.mkdir(exist_ok=True)
- # Initialize default files
- self.results_file = self.dir / 'results.md'
- self.todo_file = self.dir / 'todo.md'
- self.results_file.touch(exist_ok=True)
- self.todo_file.touch(exist_ok=True)
- self.extracted_content_count = 0
+ super().__init__(base_dir=data_dir, **kwargs)
- def get_dir(self) -> Path:
- return self.dir
-
- async def save_extracted_content(self, content: str) -> str:
- extracted_content_file_name = f'extracted_content_{self.extracted_content_count}.md'
- result = await self.write_file(extracted_content_file_name, content)
- self.extracted_content_count += 1
- return result
+ # Initialize default files
+ self._create_default_files()
+
+ def _create_default_files(self) -> None:
+ """Create default results and todo files"""
+ default_files = ['results.md', 'todo.md']
+ for full_filename in default_files:
+ # Check if file already exists using full filename as key
+ if full_filename not in self.files:
+ name_without_ext, extension = self._parse_filename(full_filename)
+ file_class = self._get_file_type_class(extension)
+ file_obj = file_class(name=name_without_ext)
+ self.files[full_filename] = file_obj # Use full filename as key
+ self._sync_file_to_disk(file_obj)
def _is_valid_filename(self, file_name: str) -> bool:
"""Check if filename matches the required pattern: name.extension"""
- pattern = r'^[a-zA-Z0-9_\-]+\.(txt|md)$'
+ # Build extensions pattern from _file_types
+ extensions = '|'.join(self._file_types.keys())
+ pattern = rf'^[a-zA-Z0-9_\-]+\.({extensions})$'
return bool(re.match(pattern, file_name))
- def display_file(self, file_name: str) -> str | None:
- if not self._is_valid_filename(file_name):
- return None
+ def _get_file_type_class(self, extension: str) -> type[BaseFile]:
+ """Get the appropriate file class for an extension"""
+ return self._file_types.get(extension.lower(), TxtFile)
- path = self.dir / file_name
- if not path.exists():
- return None
- try:
- return path.read_text()
- except Exception:
+ def _parse_filename(self, filename: str) -> tuple[str, str]:
+ """Parse filename into name and extension"""
+ if '.' not in filename:
+ raise ValueError('Filename must include extension')
+ name, extension = filename.rsplit('.', 1)
+ return name, extension.lower()
+
+ def _sync_file_to_disk(self, file_obj: BaseFile) -> None:
+ """Synchronously write file to disk"""
+ file_path = self.base_dir / file_obj.full_name
+ file_path.write_text(file_obj.content)
+
+ async def _async_sync_file_to_disk(self, file_obj: BaseFile) -> None:
+ """Asynchronously write file to disk"""
+ with ThreadPoolExecutor() as executor:
+ await asyncio.get_event_loop().run_in_executor(executor, self._sync_file_to_disk, file_obj)
+
+ def get_dir(self) -> Path:
+ """Get the file system directory"""
+ return self.base_dir
+
+ def get_file(self, full_filename: str) -> BaseFile | None:
+ """Get a file object by full filename"""
+ if not self._is_valid_filename(full_filename):
return None
- async def read_file(self, file_name: str) -> str:
- if not self._is_valid_filename(file_name):
+ # Use full filename as key
+ return self.files.get(full_filename)
+
+ def list_files(self) -> list[str]:
+ """List all files in the system"""
+ return [file_obj.full_name for file_obj in self.files.values()]
+
+ def display_file(self, full_filename: str) -> str | None:
+ """Display file content (sync version for compatibility)"""
+ file_obj = self.get_file(full_filename)
+ return file_obj.content if file_obj else None
+
+ async def read_file(self, full_filename: str) -> str:
+ """Read file content using file-specific read method"""
+ if not self._is_valid_filename(full_filename):
return INVALID_FILENAME_ERROR_MESSAGE
- path = self.dir / file_name
- if not path.exists():
- return f"File '{file_name}' not found."
+ file_obj = self.get_file(full_filename)
+ if not file_obj:
+ return f"File '{full_filename}' not found."
try:
- # Create a new executor for this operation
- with ThreadPoolExecutor() as executor:
- # Run file read in a thread to avoid blocking
- content = await asyncio.get_event_loop().run_in_executor(executor, lambda: path.read_text())
- return f'Read from file {file_name}.\n<content>\n{content}\n</content>'
+ content = file_obj.read_file_content()
+ return f'Read from file {full_filename}.\n<content>\n{content}\n</content>'
+ except FileSystemError as e:
+ return str(e)
except Exception:
- return f"Error: Could not read file '{file_name}'."
+ return f"Error: Could not read file '{full_filename}'."
- async def write_file(self, file_name: str, content: str) -> str:
- if not self._is_valid_filename(file_name):
+ async def write_file(self, full_filename: str, content: str | Any) -> str:
+ """Write content to file using file-specific write method"""
+ if not self._is_valid_filename(full_filename):
return INVALID_FILENAME_ERROR_MESSAGE
try:
- path = self.dir / file_name
- # Create a new executor for this operation
- with ThreadPoolExecutor() as executor:
- # Run file write in a thread to avoid blocking
- await asyncio.get_event_loop().run_in_executor(executor, lambda: path.write_text(content))
- return f'Data written to {file_name} successfully.'
- except Exception:
- return f"Error: Could not write to file '{file_name}'."
+ name_without_ext, extension = self._parse_filename(full_filename)
+ file_class = self._get_file_type_class(extension)
+
+ # Create or get existing file using full filename as key
+ if full_filename in self.files:
+ file_obj = self.files[full_filename]
+ else:
+ file_obj = file_class(name=name_without_ext)
+ self.files[full_filename] = file_obj # Use full filename as key
+
+ # Use file-specific write method
+ result = file_obj.write_file_content(content)
- async def append_file(self, file_name: str, content: str) -> str:
- if not self._is_valid_filename(file_name):
+ # Sync to disk
+ await self._async_sync_file_to_disk(file_obj)
+
+ return result
+ except FileSystemError as e:
+ return str(e)
+ except Exception as e:
+ return f"Error: Could not write to file '{full_filename}'. {str(e)}"
+
+ async def append_file(self, full_filename: str, content: str) -> str:
+ """Append content to file using file-specific append method"""
+ if not self._is_valid_filename(full_filename):
return INVALID_FILENAME_ERROR_MESSAGE
- path = self.dir / file_name
- if not path.exists():
- return f"File '{file_name}' not found."
+ file_obj = self.get_file(full_filename)
+ if not file_obj:
+ return f"File '{full_filename}' not found."
+
try:
- # Create a new executor for this operation
- with ThreadPoolExecutor() as executor:
- # Run file append in a thread to avoid blocking
- def append_to_file():
- with path.open('a') as f:
- f.write(content)
-
- await asyncio.get_event_loop().run_in_executor(executor, append_to_file)
- return f'Data appended to {file_name} successfully.'
+ result = file_obj.append_file_content(content)
+ await self._async_sync_file_to_disk(file_obj)
+ return result
+ except FileSystemError as e:
+ return str(e)
except Exception as e:
- return f"Error: Could not append to file '{file_name}'. {str(e)}"
+ return f"Error: Could not append to file '{full_filename}'. {str(e)}"
+
+ async def save_extracted_content(self, content: str) -> str:
+ """Save extracted content to a numbered file"""
+ extracted_filename = f'extracted_content_{self.extracted_content_count}.md'
+ result = await self.write_file(extracted_filename, content)
+ self.extracted_content_count += 1
+ return result
def describe(self) -> str:
- """List all files with their content information.
-
- Example output:
- <file>
- results.md - 42 lines
- <content>
- {preview_start}
- ... {n_lines} more lines ...
- {preview_end}
- </content>
- </file>
- """
- DISPLAY_CHARS = 400 # Total characters to display (split between start and end)
+ """List all files with their content information using file-specific display methods"""
+ DISPLAY_CHARS = 400
description = ''
- for f in self.dir.iterdir():
- # Only process files and skip todo.md
- if (not f.is_file()) or f.name == 'todo.md':
+ for file_obj in self.files.values():
+ # Skip todo.md from description
+ if file_obj.full_name == 'todo.md':
continue
try:
- content = f.read_text()
-
- # Handle empty files
- if not content:
- description += f'<file>\n{f.name} - [empty file]\n</file>\n\n'
- continue
-
- lines = content.splitlines()
- line_count = len(lines)
-
- # For small files, display the entire content
- whole_file_description = f'<file>\n{f.name} - {line_count} lines\n<content>\n{content}\n</content>\n</file>\n'
- if len(content) < int(1.5 * DISPLAY_CHARS):
- description += whole_file_description
- continue
-
- # For larger files, display start and end previews
- half_display_chars = DISPLAY_CHARS // 2
-
- # Get start preview
- start_preview = ''
- start_line_count = 0
- chars_count = 0
- for line in lines:
- if chars_count + len(line) + 1 > half_display_chars:
- break
- start_preview += line + '\n'
- chars_count += len(line) + 1
- start_line_count += 1
-
- # Get end preview
- end_preview = ''
- end_line_count = 0
- chars_count = 0
- for line in reversed(lines):
- if chars_count + len(line) + 1 > half_display_chars:
- break
- end_preview = line + '\n' + end_preview
- chars_count += len(line) + 1
- end_line_count += 1
-
- # Calculate lines in between
- middle_line_count = line_count - start_line_count - end_line_count
- if middle_line_count <= 0:
- # display the entire file
- description += whole_file_description
- continue
-
- start_preview = start_preview.strip('\n').rstrip()
- end_preview = end_preview.strip('\n').rstrip()
-
- # Format output
- description += f'<file>\n{f.name} - {line_count} lines\n<content>\n{start_preview}\n'
+ content = file_obj.display_content()
+ except Exception:
+ content = file_obj.content # fallback to raw content
+
+ # Handle empty files
+ if not content:
+ description += f'<file>\n{file_obj.full_name} - [empty file]\n</file>\n'
+ continue
+
+ lines = content.splitlines()
+ line_count = len(lines)
+
+ # For small files, display the entire content
+ whole_file_description = (
+ f'<file>\n{file_obj.full_name} - {line_count} lines\n<content>\n{content}\n</content>\n</file>\n'
+ )
+ if len(content) < int(1.5 * DISPLAY_CHARS):
+ description += whole_file_description
+ continue
+
+ # For larger files, display start and end previews
+ half_display_chars = DISPLAY_CHARS // 2
+
+ # Get start preview
+ start_preview = ''
+ start_line_count = 0
+ chars_count = 0
+ for line in lines:
+ if chars_count + len(line) + 1 > half_display_chars:
+ break
+ start_preview += line + '\n'
+ chars_count += len(line) + 1
+ start_line_count += 1
+
+ # Get end preview
+ end_preview = ''
+ end_line_count = 0
+ chars_count = 0
+ for line in reversed(lines):
+ if chars_count + len(line) + 1 > half_display_chars:
+ break
+ end_preview = line + '\n' + end_preview
+ chars_count += len(line) + 1
+ end_line_count += 1
+
+ # Calculate lines in between
+ middle_line_count = line_count - start_line_count - end_line_count
+ if middle_line_count <= 0:
+ description += whole_file_description
+ continue
+
+ start_preview = start_preview.strip('\n').rstrip()
+ end_preview = end_preview.strip('\n').rstrip()
+
+ # Format output
+ if not (start_preview or end_preview):
+ description += f'<file>\n{file_obj.full_name} - {line_count} lines\n<content>\n{middle_line_count} lines...\n</content>\n</file>\n'
+ else:
+ description += f'<file>\n{file_obj.full_name} - {line_count} lines\n<content>\n{start_preview}\n'
description += f'... {middle_line_count} more lines ...\n'
description += f'{end_preview}\n'
description += '</content>\n</file>\n'
- except Exception:
- description += f'<file>\n{f.name} - [error reading file]\n</file>\n\n'
-
return description.strip('\n')
def get_todo_contents(self) -> str:
- return self.todo_file.read_text()
+ """Get todo file contents"""
+ todo_file = self.files.get('todo.md')
+ return todo_file.content if todo_file else ''
+
+ def get_state(self) -> FileSystemState:
+ """Get serializable state of the file system"""
+ files_data = {}
+ for full_filename, file_obj in self.files.items():
+ files_data[full_filename] = {'type': file_obj.__class__.__name__, 'data': file_obj.model_dump()}
+
+ return FileSystemState(
+ files=files_data, base_dir=str(self.base_dir), extracted_content_count=self.extracted_content_count
+ )
+
+ @classmethod
+ def from_state(cls, state: FileSystemState) -> 'FileSystem':
+ """Restore file system from serializable state"""
+ # Create instance with proper Pydantic initialization
+ instance = cls.__new__(cls)
+ instance.__dict__.update(
+ {
+ 'base_dir': Path(state.base_dir),
+ 'files': {},
+ 'extracted_content_count': state.extracted_content_count,
+ '_file_types': {
+ 'md': MarkdownFile,
+ 'txt': TxtFile,
+ },
+ }
+ )
+
+ # Initialize Pydantic fields properly
+ instance.__pydantic_fields_set__ = {'base_dir', 'files', 'extracted_content_count'}
+
+ # Restore files
+ for full_filename, file_data in state.files.items():
+ file_type = file_data['type']
+
+ # Map type names to classes
+ type_mapping = {
+ 'MarkdownFile': MarkdownFile,
+ 'TxtFile': TxtFile,
+ }
+
+ file_class = type_mapping.get(file_type, TxtFile)
+ file_obj = file_class(**file_data['data'])
+ instance.files[full_filename] = file_obj # Use full filename as key
+
+ return instance
diff --git a/tests/ci/test_agent_sensitive_data.py b/tests/ci/test_agent_sensitive_data.py
index d1a83520b..09d5454b4 100644
--- a/tests/ci/test_agent_sensitive_data.py
+++ b/tests/ci/test_agent_sensitive_data.py
@@ -1,7 +1,7 @@
import pytest
from pydantic import BaseModel, Field
-from browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings
+from browser_use.agent.message_manager.service import MessageManager
from browser_use.agent.views import MessageManagerState
from browser_use.controller.registry.service import Registry
from browser_use.filesystem.file_system import FileSystem
@@ -32,7 +32,6 @@ def message_manager():
return MessageManager(
task='Test task',
system_message=SystemMessage(content='System message'),
- settings=MessageManagerSettings(),
state=MessageManagerState(),
file_system=FileSystem(file_system_path),
)
@@ -252,12 +251,12 @@ def test_filter_sensitive_data(message_manager):
message = UserMessage(content='My username is admin and password is secret123')
# Case 1: No sensitive data provided
- message_manager.settings.sensitive_data = None
+ message_manager.sensitive_data = None
result = message_manager._filter_sensitive_data(message)
assert result.content == 'My username is admin and password is secret123'
# Case 2: All sensitive data is properly replaced
- message_manager.settings.sensitive_data = {'username': 'admin', 'password': 'secret123'}
+ message_manager.sensitive_data = {'username': 'admin', 'password': 'secret123'}
result = message_manager._filter_sensitive_data(message)
assert '<secret>username</secret>' in result.content
assert '<secret>password</secret>' in result.content
@@ -269,13 +268,13 @@ def test_filter_sensitive_data(message_manager):
assert '<secret>password</secret>' in result.content[0].text
# Case 4: Test with empty values
- message_manager.settings.sensitive_data = {'username': 'admin', 'password': ''}
+ message_manager.sensitive_data = {'username': 'admin', 'password': ''}
result = message_manager._filter_sensitive_data(message)
assert '<secret>username</secret>' in result.content
# Only username should be replaced since password is empty
# Case 5: Test with domain-specific sensitive data format
- message_manager.settings.sensitive_data = {
+ message_manager.sensitive_data = {
'example.com': {'username': 'admin', 'password': 'secret123'},
'google.com': {'email': '[email protected]', 'password': 'google_pass'},
}
diff --git a/tests/ci/test_filesystem.py b/tests/ci/test_filesystem.py
new file mode 100644
index 000000000..3cf020cb0
--- /dev/null
+++ b/tests/ci/test_filesystem.py
@@ -0,0 +1,671 @@
+"""
+Comprehensive tests for the enhanced file system implementation.
+
+Tests cover:
+1. File class functionality (MarkdownFile, TxtFile)
+2. FileSystem initialization and setup
+3. Filename validation and parsing
+4. File operations (read, write, append)
+5. File access methods (get_file, list_files, display_file)
+6. Special methods (describe, save_extracted_content, get_todo_contents)
+7. Serialization and deserialization
+8. Display functionality with various file sizes
+9. Error handling and edge cases
+10. Key consistency for same-name different-extension files
+"""
+
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from browser_use.filesystem.file_system import (
+ FileSystem,
+ FileSystemState,
+ MarkdownFile,
+ TxtFile,
+)
+
+
+class TestFileClasses:
+ """Test individual file class functionality"""
+
+ def test_markdown_file_properties(self):
+ """Test MarkdownFile basic properties and methods"""
+ md_file = MarkdownFile(name='test', content='# Header\n\nContent')
+
+ assert md_file.extension == 'md'
+ assert md_file.full_name == 'test.md'
+ assert md_file.validate_content('any string')
+ assert md_file.read_file_content() == '# Header\n\nContent'
+ assert md_file.get_line_count() == 3
+ assert md_file.get_size() == 17
+
+ def test_markdown_file_write_and_append(self):
+ """Test MarkdownFile write and append methods"""
+ md_file = MarkdownFile(name='test', content='# Header\n\nContent')
+
+ write_result = md_file.write_file_content('New content')
+ assert 'successfully' in write_result.lower()
+ assert md_file.content == 'New content'
+
+ append_result = md_file.append_file_content('\nAppended')
+ assert 'successfully' in append_result.lower()
+ assert 'New content\nAppended' in md_file.content
+
+ def test_txt_file_properties(self):
+ """Test TxtFile basic properties and methods"""
+ txt_file = TxtFile(name='notes', content='Plain text content')
+
+ assert txt_file.extension == 'txt'
+ assert txt_file.full_name == 'notes.txt'
+ assert txt_file.validate_content('any string')
+ assert txt_file.read_file_content() == 'Plain text content'
+
+ def test_txt_file_write_and_append(self):
+ """Test TxtFile write and append methods"""
+ txt_file = TxtFile(name='notes', content='Initial content')
+
+ write_result = txt_file.write_file_content('New text content')
+ assert 'successfully' in write_result.lower()
+ assert txt_file.content == 'New text content'
+
+ append_result = txt_file.append_file_content('\nExtra line')
+ assert 'successfully' in append_result.lower()
+ assert 'New text content\nExtra line' in txt_file.content
+
+
+class TestFileSystemInitialization:
+ """Test FileSystem initialization and basic setup"""
+
+ def test_filesystem_directory_creation(self):
+ """Test that FileSystem creates proper directory structure"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Test directory exists
+ assert fs.get_dir().exists()
+ assert 'browseruse_agent_data' in str(fs.get_dir())
+
+ def test_default_files_creation(self):
+ """Test that default files are created during initialization"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Test default files exist
+ assert 'results.md' in fs.files
+ assert 'todo.md' in fs.files
+ assert fs.extracted_content_count == 0
+
+ # Print initial description for verification
+ initial_description = fs.describe()
+ print(f'\nπŸ“‹ INITIAL FILE SYSTEM DESCRIPTION:\n{initial_description}')
+
+ def test_filesystem_state_initialization(self):
+ """Test that FileSystem properly initializes internal state"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ assert isinstance(fs.files, dict)
+ assert len(fs.files) == 2 # results.md and todo.md
+ assert fs.extracted_content_count == 0
+
+
+class TestFilenameValidation:
+ """Test filename validation and parsing functionality"""
+
+ def test_valid_filename_patterns(self):
+ """Test that valid filenames are correctly identified"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ valid_files = ['test.md', 'file_name.txt', 'test123.md', 'my-file.txt', 'my_file.md']
+ for filename in valid_files:
+ assert fs._is_valid_filename(filename), f'Should accept {filename}'
+
+ def test_invalid_filename_patterns(self):
+ """Test that invalid filenames are correctly rejected"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ invalid_files = ['test.xyz', 'file.json', 'noextension', 'test.', '.md', 'test..md', 'test space.md']
+ for filename in invalid_files:
+ assert not fs._is_valid_filename(filename), f'Should reject {filename}'
+
+ def test_filename_parsing(self):
+ """Test filename parsing into name and extension"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ name, ext = fs._parse_filename('test.md')
+ assert name == 'test' and ext == 'md'
+
+ name, ext = fs._parse_filename('complex_file-name.txt')
+ assert name == 'complex_file-name' and ext == 'txt'
+
+ def test_file_type_class_retrieval(self):
+ """Test that appropriate file classes are returned for extensions"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ md_class = fs._get_file_type_class('md')
+ txt_class = fs._get_file_type_class('txt')
+ unknown_class = fs._get_file_type_class('xyz')
+
+ assert md_class == MarkdownFile
+ assert txt_class == TxtFile
+ assert unknown_class == TxtFile # Default fallback
+
+
+class TestFileOperations:
+ """Test all file operation methods"""
+
+ async def test_write_file_operations(self):
+ """Test write_file method with various scenarios"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Test valid file write
+ write_result = await fs.write_file('test1.md', '# Test Content')
+ assert 'successfully' in write_result.lower()
+ assert 'test1.md' in fs.files
+
+ # Test file exists on disk
+ disk_file = fs.get_dir() / 'test1.md'
+ assert disk_file.exists()
+
+ # Test invalid filename
+ invalid_result = await fs.write_file('invalid.xyz', 'content')
+ assert 'invalid filename format' in invalid_result.lower()
+
+ # Print file system state
+ operations_description = fs.describe()
+ print(f'\nπŸ“‹ FILE SYSTEM AFTER WRITE OPERATIONS:\n{operations_description}')
+
+ async def test_read_file_operations(self):
+ """Test read_file method with various scenarios"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Write a test file first
+ await fs.write_file('test1.md', '# Test Content')
+
+ # Test reading existing file
+ read_result = await fs.read_file('test1.md')
+ assert 'Test Content' in read_result
+ assert 'Read from file test1.md' in read_result
+
+ # Test reading non-existent file
+ not_found_result = await fs.read_file('nonexistent.md')
+ assert 'not found' in not_found_result.lower()
+
+ # Test invalid filename
+ invalid_read = await fs.read_file('invalid.xyz')
+ assert 'invalid filename format' in invalid_read.lower()
+
+ async def test_append_file_operations(self):
+ """Test append_file method with various scenarios"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Write initial file
+ await fs.write_file('test1.md', '# Test Content')
+
+ # Test appending to existing file
+ append_result = await fs.append_file('test1.md', '\n\nAppended content')
+ assert 'successfully' in append_result.lower()
+
+ # Verify append worked
+ after_append = await fs.read_file('test1.md')
+ assert 'Appended content' in after_append
+
+ # Test append to non-existent file
+ append_missing_result = await fs.append_file('missing.md', 'content')
+ assert 'not found' in append_missing_result.lower()
+
+ # Test invalid filename
+ invalid_append = await fs.append_file('invalid.xyz', 'content')
+ assert 'invalid filename format' in invalid_append.lower()
+
+
+class TestFileAccessMethods:
+ """Test file access and listing methods"""
+
+ async def test_get_file_method(self):
+ """Test get_file method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Add test files
+ await fs.write_file('doc1.md', 'Document 1')
+ await fs.write_file('doc2.txt', 'Document 2')
+ await fs.write_file('same_name.md', 'Markdown version')
+ await fs.write_file('same_name.txt', 'Text version')
+
+ # Test getting existing file
+ md_file = fs.get_file('doc1.md')
+ assert md_file is not None
+ assert md_file.content == 'Document 1'
+
+ # Test getting files with same name but different extension
+ same_md = fs.get_file('same_name.md')
+ same_txt = fs.get_file('same_name.txt')
+ assert same_md is not None and same_txt is not None
+ assert same_md.content != same_txt.content
+ assert same_md.content == 'Markdown version'
+ assert same_txt.content == 'Text version'
+
+ async def test_list_files_method(self):
+ """Test list_files method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Add test files
+ await fs.write_file('doc1.md', 'Document 1')
+ await fs.write_file('doc2.txt', 'Document 2')
+ await fs.write_file('same_name.md', 'Markdown version')
+ await fs.write_file('same_name.txt', 'Text version')
+
+ file_list = fs.list_files()
+ expected_files = {'results.md', 'todo.md', 'doc1.md', 'doc2.txt', 'same_name.md', 'same_name.txt'}
+ assert set(file_list) == expected_files
+
+ # Print file system state
+ access_description = fs.describe()
+ print(f'\nπŸ“‹ FILE SYSTEM WITH MULTIPLE FILES:\n{access_description}')
+
+ async def test_display_file_method(self):
+ """Test display_file method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ await fs.write_file('doc1.md', 'Document 1')
+
+ # Test displaying existing file
+ display_content = fs.display_file('doc1.md')
+ assert display_content == 'Document 1'
+
+ # Test displaying non-existent file
+ display_none = fs.display_file('nonexistent.md')
+ assert display_none is None
+
+
+class TestSpecialMethods:
+ """Test special methods like describe, save_extracted_content, etc."""
+
+ async def test_describe_method(self):
+ """Test describe method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Add content to test files
+ await fs.write_file('results.md', '# Results\n\nSome results here')
+ await fs.write_file('notes.txt', 'Short note')
+
+ description = fs.describe()
+
+ # Test that files are included/excluded properly
+ assert 'results.md' in description
+ assert 'notes.txt' in description
+ assert 'todo.md' not in description # Should be excluded
+
+ # Test XML formatting
+ assert '<file>' in description and '</file>' in description
+ assert '<content>' in description and '</content>' in description
+
+ print(f'\nπŸ“‹ FILE SYSTEM DESCRIPTION TEST:\n{description}')
+
+ async def test_get_todo_contents_method(self):
+ """Test get_todo_contents method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ await fs.write_file('todo.md', '# TODO\n\n- Task 1\n- Task 2')
+ todo_contents = fs.get_todo_contents()
+
+ assert 'Task 1' in todo_contents
+ assert 'Task 2' in todo_contents
+
+ async def test_save_extracted_content_method(self):
+ """Test save_extracted_content method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ initial_count = fs.extracted_content_count
+ extract_result = await fs.save_extracted_content('Extracted data')
+
+ assert 'successfully' in extract_result.lower()
+ assert fs.extracted_content_count == initial_count + 1
+
+ expected_filename = f'extracted_content_{initial_count}.md'
+ assert expected_filename in fs.files
+
+ # Print file system state
+ special_description = fs.describe()
+ print(f'\nπŸ“‹ FILE SYSTEM AFTER SPECIAL METHODS:\n{special_description}')
+
+
+class TestSerialization:
+ """Test serialization and deserialization functionality"""
+
+ async def test_get_state_method(self):
+ """Test get_state method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ # Create filesystem with test data
+ fs1 = FileSystem(temp_dir)
+ await fs1.write_file('doc1.md', '# Document 1\n\nContent here')
+ await fs1.write_file('doc2.txt', 'Plain text document')
+ await fs1.write_file('same.md', 'Markdown version')
+ await fs1.write_file('same.txt', 'Text version')
+ fs1.extracted_content_count = 5
+
+ state = fs1.get_state()
+
+ assert isinstance(state, FileSystemState)
+ expected_files = {'results.md', 'todo.md', 'doc1.md', 'doc2.txt', 'same.md', 'same.txt'}
+ assert set(state.files.keys()) == expected_files
+ assert state.extracted_content_count == 5
+
+ async def test_from_state_method(self):
+ """Test from_state method functionality"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ # Create original filesystem
+ fs1 = FileSystem(temp_dir)
+ await fs1.write_file('doc1.md', '# Document 1\n\nContent here')
+ await fs1.write_file('doc2.txt', 'Plain text document')
+ await fs1.write_file('same.md', 'Markdown version')
+ await fs1.write_file('same.txt', 'Text version')
+ fs1.extracted_content_count = 5
+
+ # Get state and restore
+ state = fs1.get_state()
+ fs2 = FileSystem.from_state(state)
+
+ # Test restoration
+ assert isinstance(fs2, FileSystem)
+ expected_files = {'results.md', 'todo.md', 'doc1.md', 'doc2.txt', 'same.md', 'same.txt'}
+ assert set(fs2.files.keys()) == expected_files
+ assert fs2.extracted_content_count == 5
+
+ # Test content preservation
+ doc1_content = await fs2.read_file('doc1.md')
+ assert 'Document 1' in doc1_content and 'Content here' in doc1_content
+
+ # Test same name different extension preservation
+ same_md_content = await fs2.read_file('same.md')
+ same_txt_content = await fs2.read_file('same.txt')
+ assert 'Markdown version' in same_md_content
+ assert 'Text version' in same_txt_content
+
+ # Print comparison
+ original_description = fs1.describe()
+ restored_description = fs2.describe()
+ print(f'\nπŸ“‹ ORIGINAL FILE SYSTEM:\n{original_description}')
+ print(f'\nπŸ“‹ RESTORED FILE SYSTEM:\n{restored_description}')
+
+
+class TestDisplayFunctionality:
+ """Test file system display functionality with various file sizes and content"""
+
+ async def test_empty_file_display(self):
+ """Test display of empty files"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ await fs.write_file('empty.md', '')
+ description = fs.describe()
+
+ assert '[empty file]' in description
+ print(f'\nπŸ“‹ EMPTY FILE DISPLAY:\n{description}')
+
+ async def test_small_file_display(self):
+ """Test display of small files (should show complete content)"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ small_content = '# Small File\n\nThis is a small file with just a few lines.\nLine 3\nLine 4'
+ await fs.write_file('small.md', small_content)
+ description = fs.describe()
+
+ assert 'Small File' in description and 'Line 4' in description
+ print(f'\nπŸ“‹ SMALL FILE DISPLAY:\n{description}')
+
+ async def test_medium_file_display(self):
+ """Test display of medium files (around threshold)"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Create content around threshold
+ medium_lines = [f'This is line {i + 1} with some content to make it longer' for i in range(20)]
+ medium_content = '\n'.join(medium_lines)
+ await fs.write_file('medium.txt', medium_content)
+
+ description = fs.describe()
+ assert 'line 1' in description and 'line 20' in description
+ print(f'\nπŸ“‹ MEDIUM FILE DISPLAY:\n{description[:500]}...')
+
+ async def test_large_file_display(self):
+ """Test display of large files (should show truncation)"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Create large content that will be truncated
+ large_lines = []
+ for i in range(100):
+ large_lines.append(
+ f'This is a very long line {i + 1} with lots of content to exceed the display character limit and force truncation behavior in the describe method'
+ )
+ large_content = '\n'.join(large_lines)
+ await fs.write_file('large.md', large_content)
+
+ description = fs.describe()
+ assert 'line 1' in description and 'line 100' in description
+ assert 'more lines' in description
+ print(f'\nπŸ“‹ LARGE FILE DISPLAY (truncated):\n{description[:800]}...')
+
+ async def test_threshold_file_display(self):
+ """Test display of files at exact threshold"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Create content at threshold (590 chars)
+ threshold_content = 'x' * 590
+ await fs.write_file('threshold.txt', threshold_content)
+ description = fs.describe()
+
+ assert threshold_content[:50] in description
+ print(f'\nπŸ“‹ THRESHOLD FILE DISPLAY:\n{description}')
+
+ async def test_line_count_accuracy(self):
+ """Test that line counts are displayed accurately"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ test_content = 'Line 1\nLine 2\nLine 3\nLine 4\nLine 5'
+ await fs.write_file('linecount.md', test_content)
+ description = fs.describe()
+
+ assert '5 lines' in description
+
+ async def test_xml_formatting(self):
+ """Test that XML formatting is correct"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ await fs.write_file('test.md', 'Test content')
+ description = fs.describe()
+
+ # Test balanced XML tags
+ assert description.count('<file>') == description.count('</file>')
+ assert '<content>' in description and '</content>' in description
+
+ async def test_comprehensive_display_output(self):
+ """Test comprehensive display with all file types and sizes"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Create various types of files
+ await fs.write_file('empty.md', '')
+ await fs.write_file('small.txt', 'Short content')
+
+ # Medium file
+ medium_lines = [f'Line {i + 1} content' for i in range(15)]
+ await fs.write_file('medium.md', '\n'.join(medium_lines))
+
+ # Large file
+ large_lines = [f'Very long line {i + 1} with extensive content for testing truncation behavior' for i in range(50)]
+ await fs.write_file('large.txt', '\n'.join(large_lines))
+
+ # Mixed file types
+ await fs.write_file('mixed1.md', '# Markdown file\n\nWith some content')
+ await fs.write_file('mixed2.txt', 'Plain text file\nWith some content')
+
+ sample_description = fs.describe()
+
+ print('\nπŸ“‹ COMPREHENSIVE DISPLAY OUTPUT:')
+ print('=' * 60)
+ print(sample_description)
+ print('=' * 60)
+ print('\nDescription Statistics:')
+ print(f'- Total length: {len(sample_description)} characters')
+ print(f'- Total files in system: {len(fs.files)}')
+ print(f'- Files shown in description: {sample_description.count("<file>")}')
+ print(f'- Files with truncation: {sample_description.count("more lines")}')
+
+ # Basic assertions
+ assert len(sample_description) > 0
+ assert sample_description.count('<file>') > 0
+
+
+class TestErrorHandling:
+ """Test error handling and edge cases"""
+
+ async def test_invalid_filename_error_handling(self):
+ """Test error handling for invalid filenames"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Test various invalid filename operations
+ invalid_read = await fs.read_file('invalid.xyz')
+ assert 'invalid filename format' in invalid_read.lower()
+
+ invalid_write = await fs.write_file('invalid.xyz', 'content')
+ assert 'invalid filename format' in invalid_write.lower()
+
+ invalid_append = await fs.append_file('invalid.xyz', 'content')
+ assert 'invalid filename format' in invalid_append.lower()
+
+ async def test_nonexistent_file_error_handling(self):
+ """Test error handling for non-existent files"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ read_missing = await fs.read_file('missing.md')
+ assert 'not found' in read_missing.lower()
+
+ append_missing = await fs.append_file('missing.md', 'content')
+ assert 'not found' in append_missing.lower()
+
+ def test_get_file_with_invalid_filename(self):
+ """Test get_file with invalid filename returns None"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ result = fs.get_file('invalid.xyz')
+ assert result is None
+
+ def test_display_file_with_nonexistent_file(self):
+ """Test display_file with non-existent file returns None"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ result = fs.display_file('nonexistent.md')
+ assert result is None
+
+
+class TestKeyConsistency:
+ """Test that all dictionary keys consistently use full filenames"""
+
+ async def test_full_filename_keys(self):
+ """Test that all dictionary keys use full filenames with extensions"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ # Add files with same names but different extensions
+ await fs.write_file('test.md', 'Markdown content')
+ await fs.write_file('test.txt', 'Text content')
+ await fs.write_file('document.md', 'Another markdown')
+ await fs.write_file('document.txt', 'Another text')
+
+ all_keys = list(fs.files.keys())
+
+ # Test all keys have extensions
+ assert all('.' in key for key in all_keys)
+
+ # Test no duplicate keys
+ assert len(all_keys) == len(set(all_keys))
+
+ async def test_same_name_different_extension_access(self):
+ """Test accessing files with same names but different extensions"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ await fs.write_file('test.md', 'Markdown content')
+ await fs.write_file('test.txt', 'Text content')
+
+ # Test both files are accessible
+ test_md = await fs.read_file('test.md')
+ test_txt = await fs.read_file('test.txt')
+
+ assert 'Markdown content' in test_md
+ assert 'Text content' in test_txt
+
+ async def test_serialization_key_preservation(self):
+ """Test that serialization preserves full filename keys"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ await fs.write_file('test.md', 'Markdown content')
+ await fs.write_file('test.txt', 'Text content')
+ await fs.write_file('document.md', 'Another markdown')
+ await fs.write_file('document.txt', 'Another text')
+
+ all_keys = list(fs.files.keys())
+
+ # Test serialization preserves keys
+ state = fs.get_state()
+ state_keys = list(state.files.keys())
+ assert set(state_keys) == set(all_keys)
+
+ # Test deserialization preserves keys
+ fs2 = FileSystem.from_state(state)
+ restored_keys = list(fs2.files.keys())
+ assert set(restored_keys) == set(all_keys)
+
+ # Print verification
+ consistency_description = fs.describe()
+ print(f'\nπŸ“‹ SAME-NAME DIFFERENT-EXTENSION FILES:\n{consistency_description}')
+
+
+class TestFileSystemDirectory:
+ """Test directory-related functionality"""
+
+ def test_get_dir_method(self):
+ """Test get_dir method returns correct directory"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fs = FileSystem(temp_dir)
+
+ dir_path = fs.get_dir()
+ assert isinstance(dir_path, Path)
+ assert dir_path.exists()
+ assert 'browseruse_agent_data' in str(dir_path)
+
+ def test_directory_already_exists_error(self):
+ """Test that error is raised if directory already exists"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ # Create first filesystem
+ fs1 = FileSystem(temp_dir)
+
+ # Try to create second filesystem in same directory - should raise error
+ with pytest.raises(ValueError, match='File system directory already exists'):
+ fs2 = FileSystem(temp_dir)