Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

fix: identify dedicated browser by its own id, keep login window open, queue parallel queries

Pnant7ccfd04702c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 49ca87ce..db93f99c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,12 +18,16 @@ All notable changes to this project will be documented in this file.
- 保留小宇宙转录;去掉额外模型配置和重复的网站抓取实现。
- Bridge 随专用浏览器管理;按真实页面操作计时、定期保存登录。清理失败保留渠道,卸载只删台账文件。发布前必须有渠道真实验收。
- 查询默认无头,优先只读复用本机已有的站点登录;显窗登录与无头查询共用配置。B站字幕、雪球社区自动同步登录,BOSS JD 使用上游浏览器接口。缺失接口和限流不再误报为需要重登。
+- 专用浏览器按扩展保存在它自己配置里的编号识别,不会再把用户日常的 Chrome 认成专用浏览器;登录窗口开着时查询不再把它收掉。
+- 浏览器渠道可以并行查询:同一平台最多 2 条、合计 4 条同时跑,多出来的排队而不是立刻报"正忙";登录窗口、退出登录等操作等正在跑的查询结束再做。
English:
- Browser channels share one profile, close after ten idle minutes and reopen on demand.
- Adding a channel prepares its tools; removal clears only that site's login.
- Public content remains public-first, with a compact capability receipt.
- Keep Xiaoyuzhou transcription; remove the extra planner and duplicate site extraction.
+- The dedicated browser is identified by the id its extension saves inside its own profile, so the user's own Chrome is never mistaken for it; a query no longer closes an open login window.
+- Browser channels run queries in parallel: up to 2 per platform and 4 in total, with the rest queued instead of failing BUSY at once; login windows, logout and browser setup wait for running queries.
中文:
diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.py
index 1a4e7247..c0a11d6b 100644
--- a/agent_reach/backends/opencli.py
+++ b/agent_reach/backends/opencli.py
@@ -61,14 +61,13 @@ def _opencli_error(text: str, login_hint: str):
def opencli_call(site: str, args, *, timeout: float, login_hint: str = ""):
"""One bounded command, using an explicit existing browser binding. No retry."""
- from agent_reach.runtime.browser_binding import environment, execution_lock
+ from agent_reach.runtime.browser_binding import environment
from agent_reach.runtime.run import CommandFailed, run_cmd
env = environment(site)
argv = ["opencli", site, *args, "-f", "json"]
try:
- with execution_lock(env["OPENCLI_PROFILE"]):
- out = run_cmd(argv, timeout=timeout, env=env)
+ out = run_cmd(argv, timeout=timeout, env=env)
except CommandFailed as exc:
raise _opencli_error(exc.stdout or exc.stderr, login_hint) from None
try:
diff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.py
index 68a7cdfb..423d84b8 100644
--- a/agent_reach/channels/boss.py
+++ b/agent_reach/channels/boss.py
@@ -70,7 +70,7 @@ class BossChannel(Channel):
def _native(self, payload: dict, timeout: float) -> list:
from agent_reach.runtime import state
- from agent_reach.runtime.browser_binding import execution_lock
+ from agent_reach.runtime.browser_binding import wait_lock
from agent_reach.runtime.onboarding import require_boss_cdp
endpoint = require_boss_cdp()
exe = resolve("boss")
@@ -83,7 +83,7 @@ class BossChannel(Channel):
limit = payload.get("limit", 1)
runner = Path(__file__).parents[1] / "backends" / "boss_native.py"
try:
- with execution_lock(endpoint):
+ with wait_lock(endpoint, wait=timeout):
out = run_cmd([str(python), str(runner), json.dumps(payload)], timeout=timeout)
except CommandFailed as exc:
out = exc.stdout
diff --git a/agent_reach/runtime/browser.py b/agent_reach/runtime/browser.py
index 83029402..0071a1a4 100644
--- a/agent_reach/runtime/browser.py
+++ b/agent_reach/runtime/browser.py
@@ -550,10 +550,11 @@ def ensure_running(context: Optional[str] = None) -> None:
from .clock import off_the_clock
from .result import NEED_SETUP, UPSTREAM_BROKEN, ReachError
if is_running():
- _require_owned()
- if _load_state().get("headless") is not True:
- setup()
- return
+ _require_owned() # a visible login window is used as-is, never closed for a query
+ own = dedicated_context()
+ if own and own != bound_context() and own in connected_contexts():
+ update_state(opencli_context=own) # repair a record that points at another Chrome
+ context = own
if context is None:
context = bound_context()
if not context:
@@ -674,8 +675,8 @@ def restore_session() -> None:
def clear_site(domains: List[str]) -> int:
- from .browser_binding import execution_lock
- with execution_lock("browser:shared"):
+ from .browser_binding import exclusive_browser
+ with exclusive_browser():
return _clear_site(domains)
@@ -782,37 +783,31 @@ def bound_context() -> Optional[str]:
return _load_state().get("opencli_context") or None
-def bind() -> dict:
- """Record which OpenCLI profile is the dedicated browser (Windows Web Store flow).
+# Key the OpenCLI extension uses to persist its profile id inside each browser profile.
+_CONTEXT_ID_KEY = "opencli_context_id_v1"
+
- The first call snapshots profiles already connected (the user's own
- Chrome). After the user installs the extension in the dedicated window,
- the next call finds exactly one new profile and records it.
+def dedicated_context() -> Optional[str]:
+ """The OpenCLI profile id saved inside the running dedicated browser, read over its own CDP port.
+
+ Read from the dedicated profile itself, so another Chrome connecting at
+ the same moment can never be mistaken for it.
"""
- state = _load_state()
- now = connected_contexts()
- if state.get("opencli_context") in now:
- return {"status": "ready", "context": state["opencli_context"]}
- if "baseline" not in state:
- state["baseline"] = now
- _save_state(state)
- new = [c for c in now if c not in state["baseline"]]
- if len(new) == 1:
- state["opencli_context"] = new[0]
- _save_state(state)
- return {"status": "ready", "context": new[0]}
- if len(new) > 1:
- return {"status": "ambiguous", "candidates": new}
- return {"status": "waiting_for_extension"}
+ if not is_running():
+ return None
+ from . import cdp
+ return cdp.extension_value(_CONTEXT_ID_KEY)
-def _ambiguous(candidates: List[str]):
- from .result import NEED_SETUP, ReachError
- return ReachError(
- NEED_SETUP, f"more than one new OpenCLI profile connected: {', '.join(candidates)}",
- hint="Ask the user to close other Chrome windows that have the OpenCLI extension, then run setup again.",
- )
+def bind() -> dict:
+ """Record the dedicated browser's OpenCLI profile once its extension is connected."""
+ own = dedicated_context()
+ if own and own in connected_contexts():
+ if own != bound_context():
+ update_state(opencli_context=own)
+ return {"status": "ready", "context": own}
+ return {"status": "waiting_for_extension"}
def setup(*, retry_cloak: bool = False, headless: bool = True) -> dict:
@@ -834,36 +829,33 @@ def setup(*, retry_cloak: bool = False, headless: bool = True) -> dict:
refresh_extension()
touch()
with start_lock():
- ctx = bound_context()
- if (ctx and is_running() and watcher_running() and ctx in connected_contexts()
- and _load_state().get("running_backend") == _load_state().get("backend")
- and _load_state().get("headless") == headless):
- return status()
+ state = _load_state()
+ visible = is_running() and state.get("headless") is False
+ if (is_running() and watcher_running() and state.get("running_backend") == state.get("backend")
+ and (state.get("headless") == headless or visible)):
+ if bind()["status"] == "ready":
+ return status()
+ if visible:
+ from .result import ReachError
+ raise ReachError("BUSY", "A login window is open in the Agent Reach browser",
+ hint="Wait until the user says they finished logging in; do not close the window.")
_close_for_restart() # release profile and watcher before switching modes
- if ctx: # let OpenCLI notice the old connection is gone before taking the snapshot
- wait_for(lambda: ctx not in connected_contexts(), 10.0)
- baseline = connected_contexts()
_launch("about:blank", headless=headless)
- found: List[str] = []
- def new_context() -> bool:
+ def connected() -> bool:
if not is_running() and not watcher_running():
from .result import UPSTREAM_BROKEN, ReachError
raise ReachError(UPSTREAM_BROKEN, "The dedicated browser exited before its extension connected",
hint=f"Browser launch failed; inspect {watcher_log_path()}. No login was requested.")
- found[:] = [c for c in connected_contexts() if c not in baseline]
- return len(found) == 1
+ return bind()["status"] == "ready"
- if not wait_for(new_context, _remaining_start_wait(), interval=0.5):
+ if not wait_for(connected, _remaining_start_wait(), interval=0.5):
from .result import UPSTREAM_BROKEN, ReachError
- if found:
- raise _ambiguous(found)
raise ReachError(
UPSTREAM_BROKEN, "the OpenCLI extension did not connect to OpenCLI in the Agent Reach browser",
hint=f"Details: {watcher_log_path()}. Check `opencli profile list` works.",
)
- update_state(opencli_context=found[0], baseline=None)
touch()
return status()
@@ -883,8 +875,9 @@ def _setup_from_store() -> dict:
NEED_SETUP, "waiting for the OpenCLI extension in the Agent Reach browser",
hint="Ask the user to click 'Add to Chrome' in the window that just opened, then run `agent-reach browser setup` again.",
)
- if result["status"] == "ambiguous":
- raise _ambiguous(result["candidates"])
+ if result["status"] != "ready":
+ raise ReachError(NEED_SETUP, "waiting for the OpenCLI extension in the Agent Reach browser",
+ hint="Run `agent-reach browser setup` again after the extension is added.")
return status()
diff --git a/agent_reach/runtime/browser_binding.py b/agent_reach/runtime/browser_binding.py
index aec1bc6d..e5dc5cc8 100644
--- a/agent_reach/runtime/browser_binding.py
+++ b/agent_reach/runtime/browser_binding.py
@@ -2,10 +2,20 @@
import hashlib
import sys
-from contextlib import contextmanager
+import time
+from contextlib import ExitStack, contextmanager
+from typing import Iterator, List, Optional
from .result import NEED_SETUP, ReachError
+#: Reads of one site that may run at once in the shared browser (same account; keeps risk control calm).
+SITE_SLOTS = 2
+#: Browser queries of all sites that may run at once.
+BROWSER_SLOTS = 4
+#: Seconds a query waits in line for a free slot before reporting BUSY.
+QUEUE_WAIT = 120.0
+_POLL = 0.2
+
def profile_for(channel: str):
"""All browser channels use the same Reach-owned destination profile."""
@@ -22,7 +32,7 @@ def setup_problems(channel: str):
def environment(channel: str):
from . import browser, session_reuse
- session_reuse.prepare(channel, action_locked=True)
+ session_reuse.prepare(channel)
profile = browser.bound_context()
if not profile:
raise ReachError(NEED_SETUP, "OpenCLI has not connected to the dedicated browser")
@@ -34,8 +44,8 @@ def environment(channel: str):
"OPENCLI_CDP_ENDPOINT": "", "OPENCLI_CDP_TARGET": ""}
-# ponytail: one nonblocking OS file lock per profile; callers retry BUSY later.
-# No daemon, queue, stale-lock cleanup, or guessed browser ownership.
+# One OS file lock per name: nonblocking `execution_lock`, or `wait_lock` that
+# polls until a deadline. Slots are N such locks; no daemon or stale-lock cleanup.
@contextmanager
@@ -74,3 +84,71 @@ def execution_lock(profile: str):
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+
+
+def _try_any(names: List[str]) -> Optional[ExitStack]:
+ """Hold the first free lock among `names`, or None if all are taken."""
+ for name in names:
+ stack = ExitStack()
+ try:
+ stack.enter_context(execution_lock(name))
+ return stack
+ except ReachError as exc:
+ stack.close()
+ if exc.code != "BUSY":
+ raise
+ return None
+
+
+def _wait_any(names: List[str], wait: float, message: str) -> ExitStack:
+ deadline = time.monotonic() + max(0.0, wait)
+ while True:
+ held = _try_any(names)
+ if held is not None:
+ return held
+ if time.monotonic() >= deadline:
+ raise ReachError("BUSY", message, hint=(
+ "The shared browser stayed full while this command waited in line; retry in a minute. "
+ "Do not switch accounts or browsers."))
+ time.sleep(_POLL)
+
+
+@contextmanager
+def wait_lock(name: str, wait: Optional[float] = None) -> Iterator[None]:
+ """Exclusive lock on `name`, waiting up to `wait` seconds (default QUEUE_WAIT)."""
+ with _wait_any([name], QUEUE_WAIT if wait is None else wait, f"Waited too long for {name}"):
+ yield
+
+
+def _browser_slots() -> List[str]:
+ return [f"browser:slot:{i}" for i in range(BROWSER_SLOTS)]
+
+
+@contextmanager
+def query_slot(site: str, clock=None) -> Iterator[None]:
+ """A place in line for one browser query: at most SITE_SLOTS per site, BROWSER_SLOTS overall.
+
+ Time spent waiting in line does not count against `clock` (the action's --timeout).
+ """
+ with ExitStack() as stack:
+ if clock is not None:
+ clock.pause()
+ try:
+ stack.enter_context(_wait_any([f"site:{site}:{i}" for i in range(SITE_SLOTS)], QUEUE_WAIT,
+ f"{site} already has {SITE_SLOTS} queries running in the shared browser"))
+ stack.enter_context(_wait_any(_browser_slots(), QUEUE_WAIT, "The shared browser is full"))
+ finally:
+ if clock is not None:
+ clock.resume()
+ yield
+
+
+@contextmanager
+def exclusive_browser() -> Iterator[None]:
+ """Wait for running queries to finish and hold off new ones (login window, restart, clearing a site)."""
+ with ExitStack() as stack:
+ deadline = time.monotonic() + QUEUE_WAIT
+ for name in _browser_slots():
+ stack.enter_context(_wait_any([name], deadline - time.monotonic(),
+ "Browser queries are still running; try again shortly"))
+ yield
diff --git a/agent_reach/runtime/cdp.py b/agent_reach/runtime/cdp.py
index b563f1a0..5ff03bfa 100644
--- a/agent_reach/runtime/cdp.py
+++ b/agent_reach/runtime/cdp.py
@@ -128,6 +128,20 @@ def cookies(domain: str) -> List[dict]:
return [c for c in result.get("cookies", []) if domain_matches(c.get("domain", ""), domain)]
+def extension_value(key: str) -> Optional[str]:
+ """A string an extension saved in `chrome.storage.local` inside the dedicated browser, or None."""
+ expr = f"chrome.storage.local.get({json.dumps(key)}).then(r => r[{json.dumps(key)}] || null)"
+ for target in _json("/json/list") or []:
+ if target.get("type") != "service_worker" or not target.get("url", "").startswith("chrome-extension://"):
+ continue
+ result = call("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True},
+ target_id=target.get("id"))
+ value = ((result or {}).get("result") or {}).get("value")
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return None
+
+
class PipeConnection:
"""CDP over `--remote-debugging-pipe`: NUL-delimited JSON, we write `wfd`, read `rfd`.
diff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.py
index 9dadd509..1cd883f0 100644
--- a/agent_reach/runtime/cli.py
+++ b/agent_reach/runtime/cli.py
@@ -418,7 +418,9 @@ def _cmd_login(args: Sequence[str]) -> int:
try:
from . import manage
manage.add(ch.name)
- browser.start(ch.login_url)
+ from .browser_binding import exclusive_browser
+ with exclusive_browser(): # opening the window may restart the browser
+ browser.start(ch.login_url)
from . import state
state.mutate(lambda data: data.setdefault("session_reuse", {}).__setitem__(ch.name, {"source": "manual", "at": state.now()}))
except ReachError as err:
@@ -511,8 +513,14 @@ def _cmd_browser(args: Sequence[str]) -> int:
return _mgmt("browser profiles", lambda: {"profiles": session_reuse.profiles()})
if ns.profile:
raise _ArgError("a profile ID applies only to browser use")
- if ns.op == "setup":
- return _mgmt("browser setup", browser.setup, retry_cloak=ns.retry_cloak)
+ if ns.op in ("setup", "stop"):
+ from .browser_binding import exclusive_browser
+ def run(fn, **kw):
+ with exclusive_browser():
+ return fn(**kw)
+ if ns.op == "setup":
+ return _mgmt("browser setup", run, browser.setup, retry_cloak=ns.retry_cloak)
+ return _mgmt("browser stop", run, browser.stop)
return _mgmt("browser " + ns.op, getattr(browser, ns.op))
except _ArgError as exc:
return _bad_input(None, "browser", str(exc))
diff --git a/agent_reach/runtime/dispatch.py b/agent_reach/runtime/dispatch.py
index a42a6e4d..59de227f 100644
--- a/agent_reach/runtime/dispatch.py
+++ b/agent_reach/runtime/dispatch.py
@@ -10,7 +10,7 @@ from typing import Any, Dict, List, Optional
from agent_reach.channels.base import Action, Channel
from . import state
-from .browser_binding import execution_lock
+from .browser_binding import query_slot, wait_lock
from .clock import Clock, bind
from .result import (
BAD_INPUT,
@@ -133,14 +133,17 @@ def _remember(channel: Channel, action: str, backend: str, error: Optional[Reach
def _pace_browser(channel: str, action: str, clock: Clock) -> None:
if action not in {"search", "jobs"}:
return
- last = state.load().get("request_starts", {}).get(channel)
- age = max(0, time.time() - last) if isinstance(last, (int, float)) else state.age_seconds(last)
- wait = BROWSER_SEARCH_INTERVAL - age
- if wait > 0:
- if wait >= clock.remaining():
- raise ReachError(TIMEOUT, "Search pacing exceeds the remaining timeout; retry later")
- time.sleep(wait)
- state.mutate(lambda saved: saved.setdefault("request_starts", {}).__setitem__(channel, time.time()))
+ # Same-site queries may now run side by side; read, wait and record the start
+ # under one lock so two of them cannot both skip the interval.
+ with wait_lock(f"pace:{channel}", wait=max(0.0, clock.remaining())):
+ last = state.load().get("request_starts", {}).get(channel)
+ age = max(0, time.time() - last) if isinstance(last, (int, float)) else state.age_seconds(last)
+ wait = BROWSER_SEARCH_INTERVAL - age
+ if wait > 0:
+ if wait >= clock.remaining():
+ raise ReachError(TIMEOUT, "Search pacing exceeds the remaining timeout; retry later")
+ time.sleep(wait)
+ state.mutate(lambda saved: saved.setdefault("request_starts", {}).__setitem__(channel, time.time()))
def _call_with_deadline(fn, params: Dict[str, Any], clock: Clock) -> List[dict]:
@@ -239,10 +242,9 @@ def run_action(
return public
elif public_only:
raise ReachError(BAD_INPUT, "This input has no public web route; use a full supported URL")
- # One action per site keeps an agent's parallel requests from fighting
- # over the same persistent session; worker-level profile locks remain.
+ # Browser queries wait in line: a few per site and overall share the browser at once.
browser_action = any(b[0] in {"opencli", "boss-agent-cli"} for b in action.backends)
- lock = execution_lock("browser:shared") if browser_action else nullcontext()
+ lock = query_slot(channel.name, clock) if browser_action else nullcontext()
with lock:
limited = cooldown(channel.name)
if limited:
diff --git a/agent_reach/runtime/manage.py b/agent_reach/runtime/manage.py
index bf71681d..1aefc05a 100644
--- a/agent_reach/runtime/manage.py
+++ b/agent_reach/runtime/manage.py
@@ -265,7 +265,9 @@ def _install_channel(ch, *, allow_upgrade: bool = False) -> List[dict]:
installed = [tools.ensure(t, allow_upgrade=allow_upgrade) for t in channel_tools(ch)]
if _uses_browser(ch):
from . import browser
- browser.setup()
+ from .browser_binding import exclusive_browser
+ with exclusive_browser(): # setup may restart the browser; let running queries finish first
+ browser.setup()
ch.on_add()
return installed
diff --git a/agent_reach/runtime/onboarding.py b/agent_reach/runtime/onboarding.py
index 3e63c23a..1d9ebcd4 100644
--- a/agent_reach/runtime/onboarding.py
+++ b/agent_reach/runtime/onboarding.py
@@ -209,7 +209,7 @@ def cdp_status():
def require_boss_cdp():
from . import browser, session_reuse
- session_reuse.prepare("boss", action_locked=True)
+ session_reuse.prepare("boss")
if not cdp_status()['boss_tab_present']:
browser.open_url('https://www.zhipin.com/web/geek/jobs')
browser.touch()
diff --git a/agent_reach/runtime/result.py b/agent_reach/runtime/result.py
index bd763dc6..d2323af6 100644
--- a/agent_reach/runtime/result.py
+++ b/agent_reach/runtime/result.py
@@ -33,7 +33,7 @@ BAD_INPUT = "BAD_INPUT"
FINAL_CODES = frozenset({NOT_FOUND, BAD_INPUT, PLATFORM_BLOCKED, RATE_LIMITED, NEED_LOGIN, "BUSY"})
DEFAULT_HINTS = {
- "BUSY": "Another command uses this browser profile. Wait for it to finish; do not switch profiles.",
+ "BUSY": "The shared browser stayed full while this command waited in line, or a login window is open. Retry later; do not switch profiles.",
PLATFORM_BLOCKED: "Stop automation. Keep this profile; the user must resolve the platform verification in the official page. Do not switch backends or retry.",
NEED_SETUP: "This backend is not installed. Ask the user to run `agent-reach doctor` for setup steps.",
NEED_LOGIN: "The attempted saved/local session did not grant access. Offer site-scoped local reuse or let the user log in themselves; never ask for a password.",
diff --git a/agent_reach/runtime/session_reuse.py b/agent_reach/runtime/session_reuse.py
index 1c2013c0..ee7d8bc2 100644
--- a/agent_reach/runtime/session_reuse.py
+++ b/agent_reach/runtime/session_reuse.py
@@ -7,12 +7,11 @@ from __future__ import annotations
import json
import time
-from contextlib import nullcontext
from agent_reach.utils.paths import PrivatePathError, read_small_text_no_follow
from . import browser, cdp, state
-from .browser_binding import execution_lock
+from .browser_binding import wait_lock
from .result import NEED_SETUP, UPSTREAM_BROKEN, ReachError
@@ -89,15 +88,14 @@ def _source_cookies(channel: str, domains) -> tuple[list, str]:
return cookies, "saved-reach-session" if cookies else "saved-profile"
-def prepare(channel: str, *, force: bool = False, action_locked: bool = False) -> dict:
+def prepare(channel: str, *, force: bool = False) -> dict:
"""Reuse an imported site session until explicitly refreshed; verify access separately."""
from .manage import _channel, site_domains
ch = _channel(channel)
if not ch.login_url:
return {"source": "not_required", "copied_cookies": 0}
- # Dispatch holds the shared lock in its calling thread while the backend
- # runs in a deadline worker. Never reacquire that OS lock from the worker.
- with nullcontext() if action_locked else execution_lock("browser:shared"):
+ # One copy per site at a time; queries of other sites keep running.
+ with wait_lock(f"session:{channel}"):
browser.ensure_running()
record = state.load().get("session_reuse", {}).get(channel, {})
if not force and (record.get("blocked") or record.get("source") == "manual"
diff --git a/tests/test_browser_slots.py b/tests/test_browser_slots.py
new file mode 100644
index 00000000..de38e5e4
--- /dev/null
+++ b/tests/test_browser_slots.py
@@ -0,0 +1,108 @@
+# -*- coding: utf-8 -*-
+"""Parallel browser queries: per-site and overall slots, queueing, exclusive operations."""
+
+import threading
+import time
+
+import pytest
+
+from agent_reach.runtime import browser_binding as bb
+from agent_reach.runtime.clock import Clock
+from agent_reach.runtime.result import ReachError
+
+
[email protected](autouse=True)
+def _home(monkeypatch, tmp_path):
+ monkeypatch.setenv("HOME", str(tmp_path))
+
+
+def _enter_later(fn):
+ """Run `with fn():` in a thread; returns (entered event, release event, thread, errors)."""
+ entered, release, errors = threading.Event(), threading.Event(), []
+
+ def run():
+ try:
+ with fn():
+ entered.set()
+ release.wait(10)
+ except ReachError as exc:
+ errors.append(exc)
+
+ t = threading.Thread(target=run)
+ t.start()
+ return entered, release, t, errors
+
+
+def test_third_query_of_a_site_waits_in_line_while_other_sites_run(monkeypatch):
+ with bb.query_slot("xiaohongshu"), bb.query_slot("xiaohongshu"):
+ with bb.query_slot("twitter"): # another site is not blocked by a full site
+ pass
+ entered, release, t, errors = _enter_later(lambda: bb.query_slot("xiaohongshu"))
+ assert not entered.wait(0.6) # queued, not refused
+ assert entered.wait(5)
+ release.set()
+ t.join(5)
+ assert errors == []
+
+
+def test_queue_gives_up_with_busy_after_the_wait(monkeypatch):
+ monkeypatch.setattr(bb, "QUEUE_WAIT", 0.3)
+ with bb.query_slot("twitter"), bb.query_slot("twitter"):
+ with pytest.raises(ReachError) as info:
+ with bb.query_slot("twitter"):
+ pass
+ assert info.value.code == "BUSY"
+
+
+def test_overall_limit_holds_across_sites(monkeypatch):
+ monkeypatch.setattr(bb, "QUEUE_WAIT", 0.3)
+ with bb.query_slot("a"), bb.query_slot("a"), bb.query_slot("b"), bb.query_slot("b"):
+ with pytest.raises(ReachError):
+ with bb.query_slot("c"):
+ pass
+
+
+def test_waiting_in_line_does_not_use_the_query_timeout():
+ clock = Clock(1.0)
+ with bb.query_slot("x"), bb.query_slot("x"):
+ entered, release, t, errors = _enter_later(lambda: bb.query_slot("x", clock))
+ time.sleep(1.2) # longer than the whole budget
+ assert entered.wait(5)
+ assert clock.remaining() > 0.5
+ release.set()
+ t.join(5)
+
+
+def test_exclusive_waits_for_running_queries_and_holds_off_new_ones(monkeypatch):
+ q_entered, q_release, q_thread, _ = _enter_later(lambda: bb.query_slot("twitter"))
+ assert q_entered.wait(5)
+ x_entered, x_release, x_thread, x_errors = _enter_later(bb.exclusive_browser)
+ assert not x_entered.wait(0.5) # a query is still running
+ q_release.set()
+ assert x_entered.wait(5)
+ monkeypatch.setattr(bb, "QUEUE_WAIT", 0.3)
+ with pytest.raises(ReachError):
+ with bb.query_slot("xiaohongshu"):
+ pass
+ x_release.set()
+ x_thread.join(5)
+ q_thread.join(5)
+ assert x_errors == []
+
+
+def test_parallel_same_site_searches_stay_spaced(monkeypatch):
+ from agent_reach.runtime import dispatch
+
+ monkeypatch.setattr(dispatch, "BROWSER_SEARCH_INTERVAL", 0.8)
+ starts = []
+
+ def search():
+ dispatch._pace_browser("twitter", "search", Clock(10.0))
+ starts.append(time.monotonic())
+
+ threads = [threading.Thread(target=search) for _ in range(2)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(10)
+ assert len(starts) == 2 and abs(starts[1] - starts[0]) >= 0.7
diff --git a/tests/test_public_first.py b/tests/test_public_first.py
index 8f224622..de5e80e1 100644
--- a/tests/test_public_first.py
+++ b/tests/test_public_first.py
@@ -24,7 +24,7 @@ def public_search(monkeypatch):
def test_public_success_never_installs_binds_or_opens_a_browser(monkeypatch, public_search):
from agent_reach.runtime import browser, dispatch
- for module, name in ((manage, "add"), (tools, "ensure"), (browser, "ensure_running"), (dispatch, "execution_lock")):
+ for module, name in ((manage, "add"), (tools, "ensure"), (browser, "ensure_running"), (dispatch, "query_slot")):
monkeypatch.setattr(module, name, Mock(side_effect=AssertionError("public query touched browser setup")))
monkeypatch.setattr(LinkedInChannel, "_jobs", Mock(side_effect=AssertionError("used site tool")))
out = run_action(LinkedInChannel(), "jobs", {"query": "Data Engineer", "location": "深圳", "limit": 2})
diff --git a/tests/test_unified_entry.py b/tests/test_unified_entry.py
index b059a8aa..fbbd3f42 100644
--- a/tests/test_unified_entry.py
+++ b/tests/test_unified_entry.py
@@ -377,6 +377,8 @@ def fake_browser(monkeypatch, tmp_path):
real_watcher_running = browser.watcher_running
monkeypatch.setattr(browser, "connected_contexts", lambda: list(state["contexts"]))
+ # The dedicated profile's own saved OpenCLI id, readable only while it runs.
+ monkeypatch.setattr(browser, "dedicated_context", lambda: "dedicated" if state["running"] else None)
monkeypatch.setattr(browser, "is_running", lambda: state["running"])
monkeypatch.setattr(browser, "_profile_pids", lambda: [999] if state["running"] else [])
monkeypatch.setattr(browser, "watcher_running", lambda: state["watched"] or real_watcher_running())
@@ -392,9 +394,8 @@ def fake_browser(monkeypatch, tmp_path):
def _bind_dedicated(fake_browser):
from agent_reach.runtime import browser
- browser.bind()
fake_browser["contexts"].append("dedicated")
- browser.bind()
+ assert browser.bind()["status"] == "ready"
def test_browser_action_sets_up_unbound_browser_by_itself(fake_browser):
@@ -495,22 +496,39 @@ def test_idle_watcher_exits_when_browser_is_closed(fake_browser):
assert browser_watcher.watch(idle=600, poll=0.1) == "browser closed"
-def test_bind_ignores_profiles_that_were_already_connected(fake_browser):
+def test_bind_waits_for_the_dedicated_browsers_own_profile(fake_browser):
from agent_reach.runtime import browser
+ fake_browser["contexts"].append("other") # another Chrome with the extension connects first
assert browser.bind()["status"] == "waiting_for_extension"
+ assert browser.bound_context() is None
fake_browser["contexts"].append("dedicated")
assert browser.bind() == {"status": "ready", "context": "dedicated"}
assert browser.bound_context() == "dedicated"
-def test_bind_refuses_to_guess_between_two_new_profiles(fake_browser):
+def test_setup_never_binds_the_users_chrome_reconnecting_at_the_same_time(fake_browser, monkeypatch):
from agent_reach.runtime import browser
- browser.bind()
- fake_browser["contexts"] += ["a", "b"]
- assert browser.bind()["status"] == "ambiguous"
- assert browser.bound_context() is None
+ real_launch = browser._launch
+
+ def launch_while_daily_reconnects(url, *, headless=True):
+ fake_browser["contexts"].remove("daily") # the user's Chrome drops its Bridge connection ...
+ real_launch(url, headless=headless)
+ fake_browser["contexts"].insert(0, "daily") # ... and reconnects while ours starts
+
+ monkeypatch.setattr(browser, "_launch", launch_while_daily_reconnects)
+ browser.setup()
+ assert browser.bound_context() == "dedicated"
+
+
+def test_wrong_record_is_repaired_before_a_query_uses_it(fake_browser):
+ from agent_reach.runtime import browser
+
+ browser.setup()
+ browser.update_state(opencli_context="daily") # e.g. written by an older Agent Reach
+ browser.ensure_running()
+ assert browser.bound_context() == "dedicated"
def test_windows_without_extension_still_needs_the_users_click(fake_browser, monkeypatch):
@@ -601,11 +619,22 @@ def test_opencli_errors_map_to_unified_codes(yaml_text, code):
assert _opencli_error(yaml_text, "").code == code
-def test_next_query_returns_from_visible_login_to_headless(fake_browser):
+def test_query_uses_an_open_login_window_without_closing_it(fake_browser):
from agent_reach.runtime import browser
browser.setup()
- context=browser.bound_context()
- browser.update_state(headless=False)
+ browser.update_state(headless=False) # the user is logging in in a visible window
browser.ensure_running()
- assert browser._load_state()['headless'] is True
- assert browser.bound_context()==context and fake_browser['launches']==2
+ browser.setup() # e.g. `agent-reach add` while the window is open
+ assert browser._load_state()["headless"] is False
+ assert fake_browser["running"] and fake_browser["launches"] == 1
+
+
+def test_open_login_window_without_extension_is_busy_not_closed(fake_browser):
+ from agent_reach.runtime import browser
+ browser.setup()
+ browser.update_state(headless=False)
+ fake_browser["contexts"].remove("dedicated")
+ with pytest.raises(ReachError) as info:
+ browser.setup()
+ assert info.value.code == "BUSY"
+ assert fake_browser["running"] and fake_browser["launches"] == 1