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
fix(code-use): prevent done() execution inside conditional blocks
Magnus Müller4ac49de9cf15
diff --git a/browser_use/code_use/namespace.py b/browser_use/code_use/namespace.pyindex d1556443b..5f1f4a260 100644--- a/browser_use/code_use/namespace.py+++ b/browser_use/code_use/namespace.py@@ -592,8 +592,9 @@ def create_namespace('done() should be called individually after verifying the result from any logic.\n''Consider validating your output first, THEN call done() in a final step without if/else/elif blocks only if the task is truly complete.')- logger.warning(msg)+ logger.error(msg)print(msg)+ raise RuntimeError(msg)# Build special contextspecial_context = {diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.pyindex c7dffb403..120c13ec6 100644--- a/browser_use/filesystem/file_system.py+++ b/browser_use/filesystem/file_system.py@@ -112,6 +112,14 @@ class CsvFile(BaseFile):return 'csv'+class JsonlFile(BaseFile):+ """JSONL (JSON Lines) file implementation"""++ @property+ def extension(self) -> str:+ return 'jsonl'++class PdfFile(BaseFile):"""PDF file implementation"""@@ -183,6 +191,7 @@ class FileSystem:'md': MarkdownFile,'txt': TxtFile,'json': JsonFile,+ 'jsonl': JsonlFile,'csv': CsvFile,'pdf': PdfFile,}@@ -261,7 +270,7 @@ class FileSystem:_, extension = self._parse_filename(full_filename)except Exception:return f'Error: Invalid filename format {full_filename}. Must be alphanumeric with a supported extension.'- if extension in ['md', 'txt', 'json', 'csv']:+ if extension in ['md', 'txt', 'json', 'jsonl', 'csv']:import anyioasync with await anyio.open_file(full_filename, 'r') as f:@@ -489,6 +498,8 @@ class FileSystem:file_obj = TxtFile(**file_info)elif file_type == 'JsonFile':file_obj = JsonFile(**file_info)+ elif file_type == 'JsonlFile':+ file_obj = JsonlFile(**file_info)elif file_type == 'CsvFile':file_obj = CsvFile(**file_info)elif file_type == 'PdfFile':diff --git a/tests/ci/test_code_use_done_validation.py b/tests/ci/test_code_use_done_validation.pynew file mode 100644index 000000000..a35e2a305--- /dev/null+++ b/tests/ci/test_code_use_done_validation.py@@ -0,0 +1,140 @@+"""Tests for done() call validation in code-use mode."""++import pytest++from browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfile+from browser_use.code_use.namespace import create_namespace+from browser_use.filesystem.file_system import FileSystem+++async def browser_session_with_namespace():+ """Create a browser session and namespace for testing."""+ browser_profile = BrowserProfile(headless=True, disable_security=True)+ browser_session = BrowserSession(browser_profile=browser_profile)+ await browser_session.start()++ import tempfile++ with tempfile.TemporaryDirectory() as tmp_dir:+ file_system = FileSystem(base_dir=tmp_dir)+ namespace = create_namespace(browser_session=browser_session, file_system=file_system)++ yield namespace, file_system++ await browser_session.stop()+++async def test_done_in_if_block_raises_error(browser_session_with_namespace):+ """Test that done() inside if block raises RuntimeError."""+ namespace, _ = browser_session_with_namespace++ # Simulate code with done() in if block+ test_code = """+if True:+ await done("test", success=True)+"""++ namespace['_current_cell_code'] = test_code+ namespace['_all_code_blocks'] = {'python_0': test_code}++ # Try to call done() - should raise RuntimeError+ with pytest.raises(RuntimeError) as exc_info:+ done_func = namespace['done']+ await done_func(text='test', success=True)++ assert 'done() should be called individually' in str(exc_info.value)+++async def test_done_in_else_block_raises_error(browser_session_with_namespace):+ """Test that done() inside else block raises RuntimeError."""+ namespace, _ = browser_session_with_namespace++ # Simulate code with done() in else block+ test_code = """+if False:+ pass+else:+ await done("test", success=False)+"""++ namespace['_current_cell_code'] = test_code+ namespace['_all_code_blocks'] = {'python_0': test_code}++ # Try to call done() - should raise RuntimeError+ with pytest.raises(RuntimeError) as exc_info:+ done_func = namespace['done']+ await done_func(text='test', success=False)++ assert 'done() should be called individually' in str(exc_info.value)+++async def test_done_in_elif_block_raises_error(browser_session_with_namespace):+ """Test that done() inside elif block raises RuntimeError."""+ namespace, _ = browser_session_with_namespace++ # Simulate code with done() in elif block+ test_code = """+if False:+ pass+elif True:+ await done("test", success=True)+"""++ namespace['_current_cell_code'] = test_code+ namespace['_all_code_blocks'] = {'python_0': test_code}++ # Try to call done() - should raise RuntimeError+ with pytest.raises(RuntimeError) as exc_info:+ done_func = namespace['done']+ await done_func(text='test', success=True)++ assert 'done() should be called individually' in str(exc_info.value)+++async def test_done_standalone_works(browser_session_with_namespace):+ """Test that done() works normally when not in conditional."""+ namespace, _ = browser_session_with_namespace++ # Simulate standalone done() call+ test_code = """+result = "task complete"+await done(result, success=True)+"""++ namespace['_current_cell_code'] = test_code+ namespace['_all_code_blocks'] = {'python_0': test_code}++ # Should not raise any error+ done_func = namespace['done']+ await done_func(text='task complete', success=True)++ # Verify task was marked as done+ assert namespace.get('_task_done') is True+ assert namespace.get('_task_success') is True+++async def test_done_after_if_block_works(browser_session_with_namespace):+ """Test that done() works when called after an if block (not inside it)."""+ namespace, _ = browser_session_with_namespace++ # Simulate done() after if block+ test_code = """+if some_condition:+ result = "success"+else:+ result = "failure"++await done(result, success=True)+"""++ namespace['_current_cell_code'] = test_code+ namespace['_all_code_blocks'] = {'python_0': test_code}++ # Should not raise any error+ done_func = namespace['done']+ await done_func(text='result', success=True)++ # Verify task was marked as done+ assert namespace.get('_task_done') is Truediff --git a/tests/ci/test_filesystem.py b/tests/ci/test_filesystem.pyindex 8275a72b0..1f42b098c 100644--- a/tests/ci/test_filesystem.py+++ b/tests/ci/test_filesystem.py@@ -13,6 +13,7 @@ from browser_use.filesystem.file_system import (FileSystem,FileSystemState,JsonFile,+ JsonlFile,MarkdownFile,TxtFile,)@@ -67,6 +68,18 @@ class TestBaseFile:assert csv_file.get_size == len(csv_content)assert csv_file.get_line_count == 3+ def test_jsonl_file_creation(self):+ """Test JsonlFile creation and basic properties."""+ jsonl_content = '{"id": 1, "name": "John"}\n{"id": 2, "name": "Jane"}'+ jsonl_file = JsonlFile(name='data', content=jsonl_content)++ assert jsonl_file.name == 'data'+ assert jsonl_file.content == jsonl_content+ assert jsonl_file.extension == 'jsonl'+ assert jsonl_file.full_name == 'data.jsonl'+ assert jsonl_file.get_size == len(jsonl_content)+ assert jsonl_file.get_line_count == 2+def test_file_content_operations(self):"""Test content update and append operations."""file_obj = TxtFile(name='test')@@ -241,6 +254,7 @@ class TestFileSystem:assert 'md' in extensionsassert 'txt' in extensionsassert 'json' in extensions+ assert 'jsonl' in extensionsassert 'csv' in extensionsdef test_filename_validation(self, temp_filesystem):@@ -253,7 +267,9 @@ class TestFileSystem:assert fs._is_valid_filename('file-name.md') is Trueassert fs._is_valid_filename('file123.txt') is Trueassert fs._is_valid_filename('data.json') is True+ assert fs._is_valid_filename('data.jsonl') is Trueassert fs._is_valid_filename('users.csv') is True+ assert fs._is_valid_filename('WebVoyager_data.jsonl') is True # with underscores# Invalid filenamesassert fs._is_valid_filename('test.doc') is False # wrong extension@@ -263,6 +279,7 @@ class TestFileSystem:assert fs._is_valid_filename('[email protected]') is False # special charsassert fs._is_valid_filename('.md') is False # no nameassert fs._is_valid_filename('.json') is False # no name+ assert fs._is_valid_filename('.jsonl') is False # no nameassert fs._is_valid_filename('.csv') is False # no namedef test_filename_parsing(self, temp_filesystem):@@ -476,6 +493,55 @@ class TestFileSystem:expected_content = 'name,age,city\nJohn,30,New York\nJane,25,London\nBob,35,Paris'assert file_obj.content == expected_content+ async def test_write_jsonl_file(self, temp_filesystem):+ """Test writing JSONL (JSON Lines) files."""+ fs = temp_filesystem++ # Write valid JSONL content+ jsonl_content = '{"id": 1, "name": "John", "age": 30}\n{"id": 2, "name": "Jane", "age": 25}'+ result = await fs.write_file('data.jsonl', jsonl_content)+ assert result == 'Data written to file data.jsonl successfully.'++ # Verify content was written+ content = await fs.read_file('data.jsonl')+ assert jsonl_content in content++ # Verify file object was created+ assert 'data.jsonl' in fs.files+ file_obj = fs.get_file('data.jsonl')+ assert file_obj is not None+ assert isinstance(file_obj, JsonlFile)+ assert file_obj.content == jsonl_content++ # Write to new JSONL file+ result = await fs.write_file('WebVoyager_data.jsonl', '{"task": "test", "url": "https://example.com"}')+ assert result == 'Data written to file WebVoyager_data.jsonl successfully.'+ assert 'WebVoyager_data.jsonl' in fs.files++ async def test_append_jsonl_file(self, temp_filesystem):+ """Test appending content to JSONL files."""+ fs = temp_filesystem++ # First write some JSONL content+ await fs.write_file('data.jsonl', '{"id": 1, "name": "John", "age": 30}')++ # Append additional JSONL record+ result = await fs.append_file('data.jsonl', '\n{"id": 2, "name": "Jane", "age": 25}')+ assert result == 'Data appended to file data.jsonl successfully.'++ # Verify content was appended+ file_obj = fs.get_file('data.jsonl')+ assert file_obj is not None+ expected_content = '{"id": 1, "name": "John", "age": 30}\n{"id": 2, "name": "Jane", "age": 25}'+ assert file_obj.content == expected_content++ # Append another record+ await fs.append_file('data.jsonl', '\n{"id": 3, "name": "Bob", "age": 35}')+ expected_content = (+ '{"id": 1, "name": "John", "age": 30}\n{"id": 2, "name": "Jane", "age": 25}\n{"id": 3, "name": "Bob", "age": 35}'+ )+ assert file_obj.content == expected_content+async def test_save_extracted_content(self, temp_filesystem):"""Test saving extracted content with auto-numbering."""fs = temp_filesystem