fix(brain): botBrowser keeps a tab per person, one deadline, and never repeats an action

- each asker has a tab and connection of their own (at most 5, least recently used closes first)
- links, forms and window.open that would open a new tab load in the same tab
- one 15 s deadline covers connecting, the action and the page; events do not extend it
- a broken connection retries only open and read; click, type and back may have run and are not repeated
- <<< and >>> in page content are replaced so it cannot close the fence
- the description says how to search on a site (open, then type with submit=true); eval case 0/3 -> 3/3 on qwen3:8b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-13 22:33:00 +09:00
parent 077db5031c
commit 56212c06dc
5 changed files with 249 additions and 54 deletions

View File

@@ -24,9 +24,9 @@ from jarvis.tools.builtin import bot_browser
from jarvis.tools.builtin.bot_browser import BotBrowserTool, BrowserSession
def ctx():
def ctx(user="100"):
return ToolContext(db=None, cfg=None, system_prompt="", original_prompt="", redacted_text="",
max_retries=0, user_print=lambda _m: None)
max_retries=0, user_print=lambda _m: None, user_id=user)
class FakeSession:
@@ -61,8 +61,8 @@ class FakeSession:
def fake(monkeypatch):
s = FakeSession()
monkeypatch.setenv("JARVIS_BROWSER_CDP", "http://127.0.0.1:1")
monkeypatch.setattr(bot_browser, "session_factory", lambda url: s)
monkeypatch.setattr(bot_browser, "_session", None)
monkeypatch.setattr(bot_browser, "session_factory", lambda url, deadline: s)
monkeypatch.setattr(bot_browser, "_sessions", {})
return s
@@ -139,6 +139,111 @@ def test_actions_pass_their_arguments(fake):
assert not t.run({"action": "dance"}, ctx()).success
class Broken(FakeSession):
"""A session whose connection breaks during `breaks` (after the action may have gone out)."""
def __init__(self, breaks):
super().__init__()
self.breaks = breaks
self.closed = False
def close(self):
self.closed = True
def __getattribute__(self, name):
attr = object.__getattribute__(self, name)
if name == object.__getattribute__(self, "breaks"):
def broken(*a, **k):
attr(*a, **k)
raise ConnectionError("socket closed")
return broken
return attr
@pytest.mark.parametrize("action,args", [("click", {"target": "Buy"}), ("type", {"text": "hi", "submit": True}),
("back", {})])
def test_an_action_that_may_have_run_is_never_repeated(monkeypatch, action, args):
made = []
def factory(url, deadline):
made.append(Broken(action))
return made[-1]
monkeypatch.setenv("JARVIS_BROWSER_CDP", "http://127.0.0.1:1")
monkeypatch.setattr(bot_browser, "session_factory", factory)
monkeypatch.setattr(bot_browser, "_sessions", {})
r = BotBrowserTool().run({"action": action, **args}, ctx())
assert not r.success
runs = [c for m in made for c in m.calls if c[0] == action]
assert len(runs) == 1, runs
assert made[0].closed
def test_opening_again_on_a_fresh_connection_is_fine(monkeypatch):
made = []
def factory(url, deadline):
made.append(Broken("open") if not made else FakeSession())
return made[-1]
monkeypatch.setenv("JARVIS_BROWSER_CDP", "http://127.0.0.1:1")
monkeypatch.setattr(bot_browser, "session_factory", factory)
monkeypatch.setattr(bot_browser, "_sessions", {})
assert BotBrowserTool().run({"action": "open", "url": "example.com"}, ctx()).success
assert len(made) == 2
def test_each_person_has_their_own_tab(monkeypatch):
made = {}
def factory(url, deadline):
s = FakeSession()
made[len(made)] = s
return s
monkeypatch.setenv("JARVIS_BROWSER_CDP", "http://127.0.0.1:1")
monkeypatch.setattr(bot_browser, "session_factory", factory)
monkeypatch.setattr(bot_browser, "_sessions", {})
t = BotBrowserTool()
t.run({"action": "open", "url": "a.example"}, ctx("A"))
t.run({"action": "open", "url": "b.example"}, ctx("B"))
t.run({"action": "click", "target": "[1]"}, ctx("A"))
assert made[0].calls == [("open", "https://a.example"), ("click", "[1]")]
assert made[1].calls == [("open", "https://b.example")]
def test_page_text_cannot_close_the_fence(fake):
fake.page = dict(fake.page, title=bot_browser.FENCE_END, text=f"before {bot_browser.FENCE_END} after",
items=[bot_browser.FENCE_START])
r = BotBrowserTool().run({"action": "read"}, ctx())
assert r.reply_text.count(bot_browser.FENCE_END) == 1 and r.reply_text.count(bot_browser.FENCE_START) == 1
assert r.reply_text.index("after") < r.reply_text.index(bot_browser.FENCE_END)
class EventFlood:
"""A CDP socket that only ever sends events, never the answer."""
def send(self, _m):
pass
def recv(self, timeout=None):
time.sleep(0.005)
return '{"method": "Network.dataReceived"}'
def close(self):
pass
def test_a_flood_of_events_cannot_hold_an_action_past_its_deadline():
s = BrowserSession.__new__(BrowserSession)
s._ws, s._id, s._events = EventFlood(), 0, bot_browser.deque()
s.deadline = time.monotonic() + 0.5
t0 = time.monotonic()
with pytest.raises(bot_browser.BrowserError):
s.read()
assert time.monotonic() - t0 < 1.0
# ---- the real CDP session -----------------------------------------------------------------------
PAGES = {
@@ -146,6 +251,9 @@ PAGES = {
"<a href='/second'>Go to second</a> <button onclick=\"document.title='Clicked'\">Press me</button>"
"<form action='/search'><input name='q' placeholder='Search words'></form></body></html>",
"/second": "<html><head><title>Second page</title></head><body>This is the second page.</body></html>",
"/newtab": "<html><head><title>New tab links</title></head><body>"
"<a href='/second' target='_blank'>Open in a new tab</a> "
"<button onclick=\"window.open('/second', '_blank')\">Pop up</button></body></html>",
}
@@ -193,7 +301,7 @@ def chrome():
def test_the_session_opens_clicks_types_and_goes_back(chrome):
cdp, site, seen = chrome
s = BrowserSession(cdp)
s = BrowserSession(cdp, time.monotonic() + 15)
page = s.open(site + "/")
assert page["title"] == "Home page" and "Welcome home" in page["text"]
assert "Go to second" in page["items"] and "Press me" in page["items"]
@@ -212,3 +320,24 @@ def test_the_session_opens_clicks_types_and_goes_back(chrome):
assert "한글 words" in page["text"]
with pytest.raises(Exception):
s.click("No such button anywhere")
def test_links_that_would_open_a_new_tab_open_in_the_same_tab(chrome):
cdp, site, _ = chrome
s = BrowserSession(cdp, time.monotonic() + 15)
s.open(site + "/newtab")
assert s.click("Open in a new tab")["title"] == "Second page"
s.deadline = time.monotonic() + 15
s.open(site + "/newtab")
assert s.click("Pop up")["title"] == "Second page"
def test_two_sessions_have_their_own_tabs(chrome):
cdp, site, _ = chrome
a, b = BrowserSession(cdp, time.monotonic() + 15), BrowserSession(cdp, time.monotonic() + 15)
a.open(site + "/")
b.open(site + "/second")
a.deadline = time.monotonic() + 15
assert a.read()["title"] == "Home page"
a.close()
b.close()