Skip to content

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

fix(filesystem): report missing replacement text

uczltw63648bbad7f2a
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index 103b4b7da..097eca84c 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -792,6 +792,8 @@ class FileSystem:
try:
content = file_obj.read()
+ if old_str not in content:
+ return f'Error: Could not find the specified text in file {full_filename}.'
content = content.replace(old_str, new_str)
await file_obj.write(content, self.data_dir)
sanitize_note = f" (auto-corrected from '{original_filename}')" if was_sanitized else ''
diff --git a/tests/ci/infrastructure/test_filesystem.py b/tests/ci/infrastructure/test_filesystem.py
index 273be8a0d..d8196f379 100644
--- a/tests/ci/infrastructure/test_filesystem.py
+++ b/tests/ci/infrastructure/test_filesystem.py
@@ -478,6 +478,18 @@ class TestFileSystem:
assert 'not found' in result
assert 'auto-corrected' in result
+ async def test_replace_file_reports_missing_text(self, temp_filesystem):
+ """Test that replacing absent text reports an error without changing the file."""
+ fs = temp_filesystem
+ original_content = '- [ ] First task\n- [ ] Second task'
+ await fs.write_file('todo.md', original_content)
+
+ result = await fs.replace_file_str('todo.md', '- [ ] Missing task', '- [x] Missing task')
+
+ assert result == 'Error: Could not find the specified text in file todo.md.'
+ assert fs.get_file('todo.md').content == original_content
+ assert (fs.data_dir / 'todo.md').read_text(encoding='utf-8') == original_content
+
async def test_append_json_file(self, temp_filesystem):
"""Test appending content to JSON files."""
fs = temp_filesystem