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: reuse local site sessions before headless channel queries

LohseZSaif88494ea84b8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b162bee..15a9a641 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable changes to this project will be documented in this file.
- 公开内容继续先读,不强制登录;安装后用简短表格说明能查什么。
- 保留小宇宙转录;去掉额外模型配置和重复的网站抓取实现。
- Bridge 随专用浏览器管理;按真实页面操作计时、定期保存登录。清理失败保留渠道,卸载只删台账文件。发布前必须有渠道真实验收。
+- 查询默认无头,优先只读复用本机已有的站点登录;显窗登录与无头查询共用配置。B站字幕、雪球社区自动同步登录,BOSS JD 使用上游浏览器接口。缺失接口和限流不再误报为需要重登。
English:
- Browser channels share one profile, close after ten idle minutes and reopen on demand.
@@ -28,14 +29,14 @@ English:
- 加一个平台只要一句话,需要的软件(Node.js、Chrome、ffmpeg、浏览器扩展)都会自动装好,不需要管理员密码;你只需要登录或者填一个 Key。
- 默认平台也能去掉,去掉后更新不会再加回来;去掉时会一起清掉它的登录和专用工具。
- 更新会把各平台用到的工具升到最新版;有新版本时,AI 会用大白话告诉你改了什么,你同意了才更新。
-- 登录由你本人在专用窗口完成;只复用专用浏览器已有会话,程序不读取个人 Chrome 登录。
+- 优先按站点复用本地已有登录,原浏览器不变;查询默认无头,需要本人登录时才显窗。
English:
- Adding a platform takes one sentence. Whatever it needs (Node.js, Chrome, ffmpeg, the browser extension) is installed for you, with no admin password; you only log in or enter a key.
- Default platforms can be removed, and updates won't add them back; removing one also clears its login and private tools.
- Updating also moves each platform's tools to their latest versions. When a new version is out, your AI tells you in plain words what changed and updates only if you say yes.
-- Reuse only the shared dedicated session; personal-browser authentication import is unavailable.
+- Reuse existing local site sessions read-only; queries default to headless, with a visible window for human login.
1.6 is a rebuild. Agents call one command, `agent-reach`; everything Agent Reach installs or stores lives under `~/.agent-reach/`.
1.6 是重构版本:Agent 只调一个命令 `agent-reach`,Agent Reach 装的、存的东西全部在 `~/.agent-reach/` 下。
@@ -48,7 +49,7 @@ English:
- **Skill placement / skill 放置**: one real copy at `~/.agents/skills/agent-reach/SKILL.md` (read directly by Codex, OpenCode, Cline, Warp, Zed); a link to it in the skill folder of Claude Code, OpenClaw, Hermes, Cursor, Gemini CLI, GitHub Copilot and Windsurf when installed (a copy where links are not allowed, e.g. Windows). `agent-reach skill link <dir>` covers any other AI. / 只放一份真文件,其他 AI 的 skill 目录里放指向它的链接(链接:一个指向原文件的快捷方式)。
- **Private upstream installs, latest allowed version / 上游私有安装,用最新可用版本**: tools go into `~/.agent-reach/tools/`; the user's own copies are untouched. New installations use the declared tested versions where available; otherwise they install the latest allowed version. `floor` and `exclude` define acceptable existing tools. `state.json` records the version actually installed and `doctor` shows it. Single-instance tools (OpenCLI) reuse the user's copy; if it is older than the floor, it is upgraded only with `--allow-upgrade`. / 优先安装已验收版本;已有工具按兼容范围复用;doctor 显示实际版本。
- **`add` gives a finished result / `add` 一步到位**: missing prerequisites are installed without an admin password: uv (official script), ffmpeg (`imageio-ffmpeg` in a private venv), Node.js (official release under `~/.agent-reach/tools/node/` when the system has none), CloakBrowser (falling back to installed Chrome on download failure). git is no longer needed (Boss installs from a GitHub archive). The user only logs in or enters a key. / 缺的依赖自动装好,用户只需登录或填 Key。
-- **Login state under `~/.agent-reach/` / 登录状态统一管理**: CLI tool logins in `sessions/`, browser logins in a dedicated Agent Reach browser. The browser opens by itself when a channel needs it and closes after 10 minutes without use. The OpenCLI extension is loaded automatically on each CloakBrowser launch; Windows system-Chrome fallback may need one Web Store click. Personal-browser authentication is never read or imported. / 专用浏览器按需自动打开,10 分钟不用自动关闭;macOS/Linux 自动装好扩展。
+- **Login state under `~/.agent-reach/` / 登录状态统一管理**: CLI tool logins in `sessions/`, browser logins in a dedicated Agent Reach browser. The browser opens by itself when a channel needs it and closes after 10 minutes without use. The OpenCLI extension is loaded automatically on each CloakBrowser launch; Windows system-Chrome fallback may need one Web Store click. Only the requested site’s cookies are copied read-only from an existing connected local browser; the source remains unchanged. / 专用浏览器按需自动打开,10 分钟不用自动关闭;macOS/Linux 自动装好扩展。
- **remove cleans up / 去掉渠道会清理干净**: deletes the channel's private tools nobody else uses, its CLI session, its login keys and its site cookies in the Agent Reach browser. The shared browser profile is retained for explicit logout/reuse; unused private tools are pruned.
- **Removable default channels / 默认渠道可去掉**: `state.json` records `removed_defaults`; `setup` and `update` never add them back; `add` brings one back.
- **doctor states / 体检**: not_added, needs_setup, needs_login, unverified, ready, broken; plus `regressed` per channel (passed in the previous check, fails in the latest).
diff --git a/README.md b/README.md
index 690ed1ff..a6bfdfdf 100644
--- a/README.md
+++ b/README.md
@@ -84,7 +84,7 @@ agent-reach read https://www.v2ex.com/t/123 # 按链接自动选渠道
### ✅ 在你用之前,你可能想知道
- **适用于哪些 Agent?** 任何能执行命令行的 Agent。`agent-reach setup` 会放一份使用说明(skill,就是告诉 AI 怎么用 Agent Reach 的说明文件),Codex、OpenCode 等直接能读到;Claude Code、OpenClaw、Cursor 等装了的话,会在它们的 skill 目录里放一个指向这份说明的链接(相当于快捷方式)。
-- **会碰我的浏览器和账号吗?** 浏览器渠道共用 Reach 专用浏览器,登录由你本人完成。经你明确授权,可一次性导入指定网站的登录态;不读取个人 Chrome 的 Cookie 数据库。详见[会话配置](agent_reach/skill/references/sessions.md)。
+- **会碰我的浏览器和账号吗?** 查询默认不弹窗口,会先尝试复用本机已登录的网站,只读复制该站 Cookie,原浏览器不变;不读 Cookie 数据库或密码库。确实需要重新登录时才打开 Reach 专用窗口,由你本人完成。详见[会话配置](agent_reach/skill/references/sessions.md)。
- **支持哪些系统?** 优先保证 macOS,Linux 可用,Windows 尽力支持。
- **要我自己装别的软件吗?** `agent-reach add` 会准备 Node、OpenCLI、专用浏览器和插件;已有登录优先复用,确实需要时再登录。
- **怎么知道有新版本?** Agent Reach 每天最多在后台查一次,有新版本时 Agent 会用大白话告诉你改了什么、问你要不要更新,你同意了才更新。
diff --git a/agent_reach/backends/boss_native.py b/agent_reach/backends/boss_native.py
index 7d526309..2a4e64d7 100644
--- a/agent_reach/backends/boss_native.py
+++ b/agent_reach/backends/boss_native.py
@@ -1,6 +1,9 @@
"""Subprocess entry in the pinned Boss tool's interpreter; public strict-CDP API only."""
import json
+import os
import sys
+import tempfile
+import time
from importlib.metadata import distribution
from pathlib import Path
@@ -17,13 +20,50 @@ def main():
from boss_agent_cli.api.client import BossClient
from boss_agent_cli.auth.manager import AuthManager
auth = AuthManager(Path(spec['data_dir']))
+ refs = Path(spec['data_dir']) / 'reach-job-refs.json'
+ if refs.is_symlink():
+ return {'ok': False, 'error': {'code': 'NEED_SETUP', 'message': 'Unmanaged job-reference path; left untouched'}}
with BossClient(auth, cdp_url=spec['cdp_url'], browser_source='existing-browser') as boss:
- raw = boss.search_jobs(spec['query'], city=spec.get('city') or '全国', page=1)
+ if spec['action'] == 'read':
+ try:
+ saved = json.loads(refs.read_text())
+ ref = saved['jobs'][spec['job_id']]
+ if time.time() - saved['at'] > 3600 or saved.get('session_stamp') != spec.get('session_stamp'):
+ raise KeyError('expired')
+ except (OSError, ValueError, KeyError, TypeError):
+ return {'ok': False, 'error': {'code': 'NEED_SETUP', 'message': 'No recent search reference; use the job link returned by a fresh search'}}
+ # Public upstream API, explicitly browser-only. Never job_detail()
+ # or job_card(), both of which can create an independent HTTP session.
+ raw = boss.job_card_browser(ref['security_id'], ref.get('lid', ''))
+ else:
+ raw = boss.search_jobs(spec['query'], city=spec.get('city') or '全国', page=1)
if raw.get('code') != 0:
code = raw.get('code')
mapped = {36: 'PLATFORM_BLOCKED', 37: 'PLATFORM_BLOCKED', 9: 'RATE_LIMITED', 1: 'NEED_LOGIN'}.get(code, 'UPSTREAM_BROKEN')
return {'ok': False, 'error': {'code': mapped, 'message': str(raw.get('message', 'Boss search failed'))[:300]}}
- rows = raw.get('zpData', {}).get('jobList', [])
+ if spec['action'] == 'read':
+ from boss_agent_cli.commands.detail import build_job_from_card
+ card = raw.get('zpData', {}).get('jobCard') or {}
+ if not card.get('postDescription'):
+ return {'ok': False, 'error': {'code': 'UPSTREAM_BROKEN', 'message': 'Upstream job card did not return a JD'}}
+ row = build_job_from_card(card, security_id='', greeted=False)
+ row.pop('security_id', None)
+ row['job_id'] = spec['job_id']
+ return {'ok': True, 'data': [row]}
+ rows = raw.get('zpData', {}).get('jobList', [])[:spec['limit']]
+ # Short-lived upstream references stay private; no securityId/lid is exposed
+ # in results, command arguments, or the model context.
+ content = {'at': time.time(), 'session_stamp': spec.get('session_stamp'),
+ 'jobs': {r['encryptJobId']: {'security_id': r['securityId'], 'lid': r.get('lid', '')}
+ for r in rows if r.get('encryptJobId') and r.get('securityId')}}
+ fd, tmp = tempfile.mkstemp(dir=refs.parent, prefix='.reach-job-refs-')
+ try:
+ with os.fdopen(fd, 'w') as stream:
+ json.dump(content, stream)
+ os.replace(tmp, refs)
+ finally:
+ if os.path.exists(tmp):
+ os.unlink(tmp)
# Do not export securityId/lid or raw browser credentials in unified results.
return {'ok': True, 'data': [{'title': r.get('jobName'), 'company': r.get('brandName'),
'salary': r.get('salaryDesc'), 'city': r.get('cityName'),
diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.py
index d487e5ee..1a4e7247 100644
--- a/agent_reach/backends/opencli.py
+++ b/agent_reach/backends/opencli.py
@@ -21,6 +21,10 @@ _NAV_REJECTED_HINT = (
def _opencli_error(text: str, login_hint: str):
"""Map OpenCLI's YAML error block (printed even with -f json) to a ReachError."""
+ # Node warnings can precede the upstream YAML envelope on stdout. Parse the
+ # envelope itself so warnings neither hide error codes nor flood the user.
+ import re
+
import yaml
from agent_reach.runtime.result import (
@@ -30,9 +34,10 @@ def _opencli_error(text: str, login_hint: str):
UPSTREAM_BROKEN,
ReachError,
)
-
+ start = re.search(r"(?m)^ok: false\s*$", text)
+ clean = text[start.start():] if start else text
try:
- doc = yaml.safe_load(text)
+ doc = yaml.safe_load(clean)
except yaml.YAMLError:
doc = None
err = (doc or {}).get("error") if isinstance(doc, dict) else None
@@ -43,6 +48,9 @@ def _opencli_error(text: str, login_hint: str):
return ReachError(PLATFORM_BLOCKED, message)
if code in {"RATE_LIMITED", "RATE_LIMIT"} or any(w in low for w in ("http 429", "too many requests", "访问过于频繁")):
return ReachError(RATE_LIMITED, message)
+ if re.search(r"\bHTTP 404\b", message, re.I) and code not in {"AUTH_REQUIRED", "LOGIN_REQUIRED"}:
+ return ReachError(UPSTREAM_BROKEN, message,
+ hint="The upstream route returned HTTP 404. Repeated login will not repair a missing endpoint.")
login_words = ("login", "log in", "logged in", "sign in", "http 401", "登录")
if "AUTH" in code or "LOGIN" in code or any(w in low for w in login_words):
return ReachError(NEED_LOGIN, message, hint=login_hint or None)
@@ -109,3 +117,27 @@ def opencli_items(rows) -> list:
)
)
return items
+
+
+def export_site_cookies(profile: str, domain: str) -> list:
+ """Read one site's cookies through the official existing Browser Bridge API."""
+ from pathlib import Path
+
+ from agent_reach.runtime import bridge
+ from agent_reach.runtime.result import NEED_SETUP, ReachError
+ from agent_reach.runtime.run import run_cmd
+ if not bridge.require_compatible():
+ return []
+ argv, _ = bridge.launch_spec()
+ module = Path(argv[-1]).parent / "browser" / "page.js"
+ if not module.is_file():
+ raise ReachError(NEED_SETUP, "This OpenCLI version does not expose its Page cookie API")
+ script = (f"import {{Page}} from {json.dumps(module.as_uri())};"
+ "const page=new Page('reach-site-session',undefined,process.argv[1]);"
+ "console.log(JSON.stringify(await page.getCookies({domain:process.argv[2]})));")
+ try:
+ result = json.loads(run_cmd([argv[0], "--input-type=module", "-e", script, profile, domain], timeout=15))
+ except (ReachError, ValueError):
+ # Never include upstream output here: it may contain credentials.
+ raise ReachError(NEED_SETUP, "The existing browser could not share this site's login") from None
+ return result if isinstance(result, list) else []
diff --git a/agent_reach/channels/bilibili.py b/agent_reach/channels/bilibili.py
index bbad2cc5..1112d8cc 100644
--- a/agent_reach/channels/bilibili.py
+++ b/agent_reach/channels/bilibili.py
@@ -81,6 +81,36 @@ def _bili_json(args: list, timeout: float) -> Any:
return payload.get("data") or {}
+def _reuse_subtitle_login(timeout: float) -> None:
+ """Use the official upstream credential writer; no browser launch or database read."""
+ import os
+ from pathlib import Path
+
+ from agent_reach.runtime import session_reuse, state, tools
+ saved = state.load().get("session_reuse", {}).get("bilibili", {})
+ if saved.get("blocked") or saved.get("source") == "manual":
+ return
+ cookies, source = session_reuse._source_cookies("bilibili", ("bilibili.com",))
+ jar = {c["name"]: c["value"] for c in cookies}
+ if not jar.get("SESSDATA"):
+ return # keep a saved native login when no connected local source exists
+ exe = tools.resolve("bili")
+ if not exe:
+ return
+ python = Path(exe).with_name("python.exe" if os.name == "nt" else "python")
+ script = (
+ "import json,sys;from bili_cli.auth import save_credential;"
+ "from bilibili_api import Credential;d=json.load(sys.stdin);"
+ "save_credential(Credential(sessdata=d.get('SESSDATA',''),bili_jct=d.get('bili_jct',''),"
+ "ac_time_value=d.get('ac_time_value',''),buvid3=d.get('buvid3',''),"
+ "buvid4=d.get('buvid4',''),dedeuserid=d.get('DedeUserID','')))"
+ )
+ run_cmd([str(python), "-c", script], timeout=timeout, env=session_env("bili-cli"),
+ input_data=json.dumps(jar), label="Bilibili site login reuse")
+ state.mutate(lambda data: data.setdefault("session_reuse", {}).__setitem__("bilibili", {
+ "source": source, "copied_cookies": len(jar), "at": state.now(), "verified": False, "source_changed": False}))
+
+
def _cli_video_item(v: dict, text=None) -> dict:
owner = v.get("owner") or {}
return make_item(
@@ -159,7 +189,7 @@ class BilibiliChannel(Channel):
),
Action(
"subtitle",
- "Full subtitle text of a video (needs a Bilibili login)",
+ "Subtitle text of the first video part, when available (may need a Bilibili login)",
(Param("target", "BV id or video link"),),
(("bili-cli", "_cli_subtitle"),),
live_test={"target": "BV1GJ411x7h7"},
@@ -193,9 +223,12 @@ class BilibiliChannel(Channel):
return [_api_video_item(v) for v in (data.get("list") or [])[:limit]]
def _cli_subtitle(self, *, target: str, timeout: float) -> list:
+ _reuse_subtitle_login(timeout)
data = _bili_json(["video", _bvid(target, timeout), "--subtitle"], timeout)
sub = data.get("subtitle") or {}
if not sub.get("available"):
+ if any(w.get("code") == "subtitle_unavailable" for w in data.get("warnings", []) if isinstance(w, dict)):
+ raise ReachError(UPSTREAM_BROKEN, "Bilibili could not retrieve subtitles; this does not prove the video has none")
if not (sessions_root() / "bili-cli" / ".bilibili-cli" / "credential.json").exists():
raise ReachError(NEED_LOGIN, "Bilibili is not logged in", hint=_BILI_LOGIN_HINT)
raise ReachError(NOT_FOUND, "this video has no subtitles")
diff --git a/agent_reach/channels/boss.py b/agent_reach/channels/boss.py
index 0eecb97d..d935f0d0 100644
--- a/agent_reach/channels/boss.py
+++ b/agent_reach/channels/boss.py
@@ -47,7 +47,7 @@ class BossChannel(Channel):
timeout=90,
),
Action("read", "Read a direct BOSS job URL", (Param("target", "full job URL"),),
- (("opencli", "_opencli_read"),), timeout=90),
+ (("boss-agent-cli", "_cli_read"), ("opencli", "_opencli_read")), timeout=90),
)
def can_handle(self, url: str) -> bool:
@@ -56,6 +56,18 @@ class BossChannel(Channel):
# ── unified entry backends ──
def _cli_search(self, *, query: str, city, limit: int, timeout: float) -> list:
+ return self._native({"action": "search", "query": query, "city": city, "limit": limit}, timeout)
+
+ def _cli_read(self, *, target: str, timeout: float) -> list:
+ import re
+
+ match = re.search(r"/job_detail/([A-Za-z0-9_-]+)\.html", str(target))
+ if not host_matches(str(target), "zhipin.com") or not match:
+ raise ReachError("BAD_INPUT", "Expected a direct BOSS job URL")
+ return self._native({"action": "read", "job_id": match.group(1)}, timeout)
+
+ 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.onboarding import require_boss_cdp
endpoint = require_boss_cdp()
@@ -63,8 +75,10 @@ class BossChannel(Channel):
if not exe:
raise ReachError(NEED_SETUP, "Run agent-reach add boss first")
python = Path(exe).with_name("python.exe" if os.name == "nt" else "python")
- payload = {"action": "search", "query": query, "city": city, "limit": limit, "cdp_url": endpoint,
- "data_dir": str(session_dir(self.session) / ".boss-agent")}
+ stamp = state.load().get("session_reuse", {}).get("boss", {}).get("at")
+ payload = {**payload, "cdp_url": endpoint, "data_dir": str(session_dir(self.session) / ".boss-agent"),
+ "session_stamp": stamp}
+ limit = payload.get("limit", 1)
runner = Path(__file__).parents[1] / "backends" / "boss_native.py"
try:
with execution_lock(endpoint):
@@ -107,7 +121,7 @@ class BossChannel(Channel):
title=r.get("title"),
url=f"https://www.zhipin.com/job_detail/{job_id}.html" if job_id else None,
author=r.get("company"),
- text=" · ".join(str(x) for x in (r.get("salary"), r.get("city"), r.get("experience"), r.get("education")) if x),
+ text=r.get("description") or " · ".join(str(x) for x in (r.get("salary"), r.get("city"), r.get("experience"), r.get("education")) if x),
raw=r,
)
)
diff --git a/agent_reach/channels/xiaohongshu.py b/agent_reach/channels/xiaohongshu.py
index 07305e74..fc678614 100644
--- a/agent_reach/channels/xiaohongshu.py
+++ b/agent_reach/channels/xiaohongshu.py
@@ -8,7 +8,7 @@ from .base import Action, Channel, Param
_XHS_LOGIN_HINT = (
"Run agent-reach login xiaohongshu to open the Agent Reach dedicated browser. "
- "The user completes login there. Never ask for a password or read their personal browser login."
+ "Reach first tries the existing local site login; the user completes any remaining login. Never ask for a password."
)
diff --git a/agent_reach/channels/xueqiu.py b/agent_reach/channels/xueqiu.py
index 2f2dd3f1..87f2a5dd 100644
--- a/agent_reach/channels/xueqiu.py
+++ b/agent_reach/channels/xueqiu.py
@@ -149,7 +149,7 @@ def _xueqiu_symbol(market: str, code: str) -> str:
def _import_from_browser() -> bool:
- """Copy the Xueqiu session the user has in the Agent Reach browser (only on `login --sync`)."""
+ """Sync the reused Xueqiu site session into the existing native API client."""
global _cookies_initialized
from agent_reach.runtime import browser, cdp
@@ -166,6 +166,13 @@ def _import_from_browser() -> bool:
return True
+def _prepare_community_session() -> None:
+ from agent_reach.runtime import session_reuse
+
+ session_reuse.prepare("xueqiu")
+ _import_from_browser()
+
+
def _xq_json(url: str) -> Any:
try:
return _get_json(url)
@@ -330,6 +337,7 @@ class XueqiuChannel(Channel):
]
def _xq_hot_posts(self, *, limit: int, timeout: float) -> list:
+ _prepare_community_session()
limit = max(0, min(limit, 50))
posts = _parse_hot_posts(_xq_json(_HOT_POSTS_URL.format(limit=limit)), limit) if limit else []
return [
@@ -338,6 +346,7 @@ class XueqiuChannel(Channel):
]
def _xq_hot_stocks(self, *, limit: int, timeout: float) -> list:
+ _prepare_community_session()
data = _xq_json(f"https://stock.xueqiu.com/v5/stock/hot_stock/list.json?size={limit}&type=10")
return [
make_item(
diff --git a/agent_reach/runtime/browser.py b/agent_reach/runtime/browser.py
index c92d8349..6bd900d6 100644
--- a/agent_reach/runtime/browser.py
+++ b/agent_reach/runtime/browser.py
@@ -332,7 +332,7 @@ def can_load_extension() -> bool:
return _load_state().get("backend") == "cloakbrowser" or os.name != "nt"
-def chrome_argv(exe: str, url: str, *, pipe: bool) -> List[str]:
+def chrome_argv(exe: str, url: str, *, pipe: bool, headless: bool = True) -> List[str]:
argv = [
exe,
"--remote-debugging-address=127.0.0.1",
@@ -341,6 +341,8 @@ def chrome_argv(exe: str, url: str, *, pipe: bool) -> List[str]:
"--no-first-run",
"--no-default-browser-check",
]
+ if headless:
+ argv += ["--headless=new"]
if pipe:
argv += ["--remote-debugging-pipe", "--enable-unsafe-extension-debugging"]
if os.environ.get("AGENT_REACH_TEST_MOCK_KEYCHAIN") == "1":
@@ -433,7 +435,7 @@ def _detach_kwargs() -> dict:
return {"cwd": str(root), "start_new_session": True}
-def _launch(url: str) -> None:
+def _launch(url: str, *, headless: bool = True) -> None:
"""Start the dedicated browser. Caller holds start_lock().
The watcher launches Cloak through its public SDK on every OS. System
@@ -452,9 +454,9 @@ def _launch(url: str) -> None:
ledger.remember_path(profile_dir(), "dedicated browser profile")
for name in ("watcher.log", "session.json", "last_used", "watcher.lock", "start.lock", "session.lock"):
ledger.remember_path(browser_root() / name, "browser lifecycle")
- update_state(started_at=time.time())
+ update_state(started_at=time.time(), headless=headless)
if not can_load_extension():
- subprocess.Popen(chrome_argv(exe, url, pipe=False), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ subprocess.Popen(chrome_argv(exe, url, pipe=False, headless=headless), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, **_detach_kwargs())
if not wait_for(is_running, START_WAIT):
raise ReachError(UPSTREAM_BROKEN, f"the Agent Reach browser did not open within {START_WAIT:.0f}s")
@@ -467,7 +469,8 @@ def _launch(url: str) -> None:
with open(watcher_log_path(), "wb") as log:
proc = subprocess.Popen(
[_load_state().get("launcher_python") or sys.executable, "-m", "agent_reach.runtime.browser_watcher",
- "--launch", url, "--chrome", exe, *(["--cloak"] if _load_state().get("backend") == "cloakbrowser" else [])],
+ "--launch", url, "--chrome", exe, *(["--cloak"] if _load_state().get("backend") == "cloakbrowser" else []),
+ *([] if headless else ["--headed"])],
stdin=subprocess.DEVNULL, stdout=log, stderr=log,
env={**os.environ, "PYTHONPATH": str(Path(__file__).parents[2]),
"CLOAKBROWSER_AUTO_UPDATE": "false",
@@ -523,19 +526,23 @@ def _remaining_start_wait() -> float:
return max(_RUNNING_GRACE, started + START_WAIT - time.time())
+def _close_for_restart() -> None:
+ from .result import UPSTREAM_BROKEN, ReachError
+ if not stop() or not wait_for(lambda: not watcher_running(), 20.0, interval=0.1):
+ raise ReachError(UPSTREAM_BROKEN, "Could not close the owned browser safely; saved profile retained")
+
+
def start(url: str = "about:blank") -> None:
- """Show `url` in the dedicated browser, launching it if needed (login)."""
+ """Explicit human login: show a window using the same saved profile."""
touch()
- if is_running():
- _require_owned()
- open_url(url)
- return
with start_lock():
if is_running():
_require_owned()
- open_url(url)
- return
- _launch(url)
+ if not _load_state().get("headless", False):
+ open_url(url)
+ return
+ _close_for_restart()
+ _launch(url, headless=False)
def ensure_running(context: Optional[str] = None) -> None:
@@ -544,6 +551,9 @@ def ensure_running(context: Optional[str] = None) -> None:
from .result import NEED_SETUP, UPSTREAM_BROKEN, ReachError
if is_running():
_require_owned()
+ if _load_state().get("headless") is not True:
+ setup()
+ return
if context is None:
context = bound_context()
if not context:
@@ -657,8 +667,10 @@ def restore_session() -> None:
and (row["name"], row["domain"], row.get("path", "/")) not in keys
and isinstance(row.get("expires", -1), (int, float))
and (row.get("expires", -1) <= 0 or row["expires"] > time.time())]
- if missing:
- cdp.call("Storage.setCookies", {"cookies": missing})
+ if missing and cdp.call("Storage.setCookies", {"cookies": missing}) is None:
+ from .result import UPSTREAM_BROKEN, ReachError
+ raise ReachError(UPSTREAM_BROKEN, "Saved login could not be restored; the saved session was retained")
+ update_state(restored_cookies=len(missing))
def clear_site(domains: List[str]) -> int:
@@ -803,7 +815,7 @@ def _ambiguous(candidates: List[str]):
)
-def setup(*, retry_cloak: bool = False) -> dict:
+def setup(*, retry_cloak: bool = False, headless: bool = True) -> dict:
"""Make the dedicated browser ready with the OpenCLI extension loaded and bound; returns status().
macOS/Linux: fully automatic. Windows: opens the Web Store page and waits for the user's click.
@@ -816,20 +828,22 @@ def setup(*, retry_cloak: bool = False) -> dict:
ensure_chrome(retry_cloak=True)
else:
ensure_chrome()
- if not can_load_extension():
+ if not can_load_extension() and not bound_context():
return _setup_from_store()
- refresh_extension()
+ if can_load_extension():
+ 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("running_backend") == _load_state().get("backend")
+ and _load_state().get("headless") == headless):
return status()
- stop() # (re)launch so this browser connects fresh and we can tell it apart
+ _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")
+ _launch("about:blank", headless=headless)
found: List[str] = []
def new_context() -> bool:
@@ -890,6 +904,7 @@ def status() -> dict:
"fallback_reason": _load_state().get("fallback_reason"),
"extension_version": extension_version(),
"running": running,
+ "headless": _load_state().get("headless") if running else None,
"opencli_context": ctx,
"opencli_connected": connected,
"idle_close_after_s": int(IDLE_LIMIT),
diff --git a/agent_reach/runtime/browser_binding.py b/agent_reach/runtime/browser_binding.py
index 141ad3d1..aec1bc6d 100644
--- a/agent_reach/runtime/browser_binding.py
+++ b/agent_reach/runtime/browser_binding.py
@@ -21,8 +21,8 @@ def setup_problems(channel: str):
def environment(channel: str):
- from . import browser
- browser.ensure_running()
+ from . import browser, session_reuse
+ session_reuse.prepare(channel, action_locked=True)
profile = browser.bound_context()
if not profile:
raise ReachError(NEED_SETUP, "OpenCLI has not connected to the dedicated browser")
diff --git a/agent_reach/runtime/browser_watcher.py b/agent_reach/runtime/browser_watcher.py
index 1a66c916..17129302 100644
--- a/agent_reach/runtime/browser_watcher.py
+++ b/agent_reach/runtime/browser_watcher.py
@@ -23,7 +23,7 @@ from urllib.parse import unquote, urlsplit
from . import bridge, browser
-def _launch_with_pipe(chrome: str, url: str):
+def _launch_with_pipe(chrome: str, url: str, *, headless: bool = True):
"""Start Chrome with the CDP pipe on its fds 3 (commands in) and 4 (replies out)."""
import fcntl
@@ -43,7 +43,7 @@ def _launch_with_pipe(chrome: str, url: str):
try:
proc = subprocess.Popen(
- browser.chrome_argv(chrome, url, pipe=True),
+ browser.chrome_argv(chrome, url, pipe=True, headless=headless),
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
close_fds=False, # Python fds are non-inheritable by default; only 3/4 get through
preexec_fn=place_pipe, # noqa: PLW1509 - single-threaded here
@@ -68,7 +68,7 @@ def _load_extension(conn) -> None:
print(f"Extensions.loadUnpacked failed: {reply.get('error')}", file=sys.stderr, flush=True)
-def _launch_cloak(url: str):
+def _launch_cloak(url: str, *, headless: bool = True):
"""Use the SDK's public launcher; one persistent profile, no site rules."""
from cloakbrowser import launch_persistent_context
@@ -84,20 +84,18 @@ def _launch_cloak(url: str):
ctx = launch_persistent_context(
- str(browser.profile_dir()), headless=False, locale="zh-CN",
+ str(browser.profile_dir()), headless=headless, locale="zh-CN",
args=["--remote-debugging-address=127.0.0.1", f"--remote-debugging-port={browser.CDP_PORT}"],
extension_paths=[str(browser.extension_dir())],
proxy=proxy_options,
)
if not ctx.pages:
ctx.new_page()
- if url != "about:blank":
- ctx.pages[0].goto(url, wait_until="domcontentloaded", timeout=30000)
return ctx
def watch(idle: Optional[float] = None, poll: float = 2.0, *, launch: Optional[str] = None,
- chrome: Optional[str] = None, cloak: bool = False) -> str:
+ chrome: Optional[str] = None, cloak: bool = False, headless: bool = True) -> str:
"""Run until the browser is gone. Returns why it stopped."""
idle = browser.IDLE_LIMIT if idle is None else idle
fd = browser._open_lock(browser.watcher_lock_path())
@@ -112,13 +110,18 @@ def watch(idle: Optional[float] = None, poll: float = 2.0, *, launch: Optional[s
if browser.is_running():
return "a browser is already using the debugging port"
if cloak:
- ctx = _launch_cloak(launch)
+ ctx = _launch_cloak(launch, headless=headless)
else:
- proc, conn = _launch_with_pipe(chrome or browser.ensure_chrome(), launch)
+ proc, conn = _launch_with_pipe(chrome or browser.ensure_chrome(), "about:blank", headless=headless)
_load_extension(conn)
browser.update_state(running_backend="cloakbrowser" if cloak else "chrome",
- profile_backend="cloakbrowser" if cloak else "chrome")
+ profile_backend="cloakbrowser" if cloak else "chrome", headless=headless)
browser.restore_session()
+ if launch != "about:blank":
+ if ctx is not None:
+ ctx.pages[0].goto(launch, wait_until="domcontentloaded", timeout=30000)
+ else:
+ browser.open_url(launch)
browser.update_state(bridge_pid=bridge_proc.pid if bridge_proc else None, bridge_note=None)
began = time.time()
@@ -178,8 +181,9 @@ def main() -> None:
parser.add_argument("--launch", default=None, help="start Chrome with this URL and own it (macOS/Linux)")
parser.add_argument("--chrome", default=None, help="Chrome binary for --launch")
parser.add_argument("--cloak", action="store_true", help="use CloakBrowser's public launcher")
+ parser.add_argument("--headed", action="store_true", help="show a window for human login")
ns = parser.parse_args()
- reason = watch(ns.idle, launch=ns.launch, chrome=ns.chrome, cloak=ns.cloak)
+ reason = watch(ns.idle, launch=ns.launch, chrome=ns.chrome, cloak=ns.cloak, headless=not ns.headed)
print(reason, file=sys.stderr, flush=True)
sys.exit(0 if reason in ("browser closed", "closed after idle") else 1)
diff --git a/agent_reach/runtime/cli.py b/agent_reach/runtime/cli.py
index 84f9c3e4..da3af0dd 100644
--- a/agent_reach/runtime/cli.py
+++ b/agent_reach/runtime/cli.py
@@ -56,7 +56,8 @@ For the user:
agent-reach add <channel> install channel dependencies and prepare its browser
agent-reach remove <channel> remove a channel (defaults too) and what only it used
agent-reach login|logout <channel> log in (the user does it) / forget the login
- agent-reach browser setup|status|stop shared dedicated browser
+ agent-reach browser setup|status|stop headless shared browser; login opens a window
+ agent-reach browser profiles|use ID choose an existing local login source
agent-reach skill [link <skills-dir>] where the agent skill is; link it for another AI
agent-reach doctor [--text] status of every channel and installed tool versions (no network)
agent-reach check [channel] [--text] live-test channels; --search tests search/jobs only
@@ -405,7 +406,8 @@ def _cmd_login(args: Sequence[str]) -> int:
except _ArgError as exc:
return _bad_input(None, "login", str(exc))
if ns.import_existing and ch.login_url:
- return _bad_input(ch.name, "login", "Personal-browser authentication import is unavailable; log in in the Reach dedicated window")
+ from . import session_reuse
+ return _mgmt("reuse login", session_reuse.prepare, ch.name, force=True)
if ns.import_existing and ch.session:
copied = import_legacy_state(ch.session, ch.legacy_state)
if copied:
@@ -416,6 +418,8 @@ def _cmd_login(args: Sequence[str]) -> int:
from . import manage
manage.add(ch.name)
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:
return _emit(envelope(channel=ch.name, action="login", error=err))
from . import manage
@@ -448,6 +452,8 @@ def _cmd_login(args: Sequence[str]) -> int:
if code != 0 or not has_login_state(ch.session):
return _emit(envelope(channel=ch.name, action="login",
error=ReachError(UPSTREAM_BROKEN, f"login did not complete (exit {code})")))
+ from . import state
+ state.mutate(lambda data: data.setdefault("session_reuse", {}).__setitem__(ch.name, {"source": "manual", "at": state.now()}))
return _emit(envelope(channel=ch.name, action="login", backend=ch.session, items=[{"logged_in": True}]))
@@ -466,6 +472,7 @@ def _cmd_logout(args: Sequence[str]) -> int:
manage._remove(legacy)
def forget(saved):
saved["checks"].pop(ch.name, None)
+ saved.setdefault("session_reuse", {})[ch.name] = {"blocked": True, "at": state.now()}
saved.get("reuse_sources", {}).pop(ch.name, None)
saved.setdefault("session_migrations", {})[ch.name] = {"at": state.now(), "logged_out": True}
saved.setdefault("session_revisions", {})[ch.name] = state.now()
@@ -479,17 +486,30 @@ def _cmd_logout(args: Sequence[str]) -> int:
if cfg.get(key):
cfg.delete(key)
removed = True
+ if not ch.login_url:
+ from . import state
+ state.mutate(lambda data: data.setdefault("session_reuse", {}).__setitem__(ch.name, {"blocked": True, "at": state.now()}))
return _emit(envelope(channel=ch.name, action="logout", backend=ch.session or "config", items=[{"removed": removed}]))
def _cmd_browser(args: Sequence[str]) -> int:
parser = _Parser(prog="browser", add_help=False)
- parser.add_argument("op", choices=("setup", "status", "stop"))
+ parser.add_argument("op", choices=("setup", "status", "stop", "profiles", "use"))
parser.add_argument("--retry-cloak", action="store_true")
+ parser.add_argument("profile", nargs="?")
try:
ns = parser.parse_args(list(args))
if ns.retry_cloak and ns.op != "setup":
raise _ArgError("--retry-cloak applies only to browser setup")
+ if ns.op in ("profiles", "use"):
+ from . import session_reuse
+ if ns.op == "use":
+ if not ns.profile:
+ raise _ArgError("browser use requires a connected profile ID")
+ return _mgmt("browser use", session_reuse.use, ns.profile)
+ 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)
return _mgmt("browser " + ns.op, getattr(browser, ns.op))
diff --git a/agent_reach/runtime/flow.py b/agent_reach/runtime/flow.py
index dd837704..e403c11a 100644
--- a/agent_reach/runtime/flow.py
+++ b/agent_reach/runtime/flow.py
@@ -1,7 +1,7 @@
"""Resumable setup and execution for the CLI.
The caller selects a channel and action. Reach handles its declared primary
-backend, reuses only its dedicated session, and records a real
+backend, reuses available local site sessions, and records a real
query result. No password, cookie, or browser database is exposed here.
"""
@@ -68,7 +68,7 @@ def _record(channel: str, action: str, out: dict) -> None:
def prepare(channel: str, *, action: Optional[str] = None,
install: bool = True) -> dict:
- """Prepare dependencies and the shared browser. No model and no implicit cookie export."""
+ """Prepare dependencies and the shared browser and reuse the requested site’s local login. No model."""
ch = manage._channel(channel)
selected = _action(ch, action)
with execution_lock("prepare:" + channel):
@@ -82,8 +82,8 @@ def prepare(channel: str, *, action: Optional[str] = None,
return _needs(channel, selected.name, "install", f"Run agent-reach add {channel}")
manage.add(channel)
if ch.login_url:
- from . import browser
- browser.ensure_running()
+ from . import session_reuse
+ session_reuse.prepare(channel)
return {"ok": True, "status": "prepared", "channel": channel,
"action": selected.name, "backend": selected.backends[0][0]}
diff --git a/agent_reach/runtime/manage.py b/agent_reach/runtime/manage.py
index 9d91c967..2f3ff78e 100644
--- a/agent_reach/runtime/manage.py
+++ b/agent_reach/runtime/manage.py
@@ -286,8 +286,11 @@ def _next_step(ch) -> Optional[str]:
def add(name: str, *, allow_upgrade: bool = False) -> dict:
"""Install whatever the channel needs (prerequisites included), add it, describe existing-session reuse."""
ch = _channel(name)
+ previously_added = is_added(ch)
installed = _install_channel(ch, allow_upgrade=allow_upgrade)
def save_channel(data):
+ if not previously_added:
+ data.setdefault("session_reuse", {}).pop(name, None)
data["channels"][name] = {"added_at": state.now()}
data["removed_defaults"] = [n for n in data["removed_defaults"] if n != name]
state.mutate(save_channel)
@@ -339,6 +342,7 @@ def remove(name: str) -> dict:
cfg.delete(key)
def forget(saved):
saved["channels"].pop(name, None)
+ saved.setdefault("session_reuse", {})[name] = {"blocked": True, "at": state.now()}
saved["checks"].pop(name, None)
if ch.level == "default" and name not in saved["removed_defaults"]:
saved["removed_defaults"].append(name)
diff --git a/agent_reach/runtime/onboarding.py b/agent_reach/runtime/onboarding.py
index 8ac3989c..9cb079fb 100644
--- a/agent_reach/runtime/onboarding.py
+++ b/agent_reach/runtime/onboarding.py
@@ -31,7 +31,7 @@ _CAPABILITY_LIMITS = {
'youtube': ['read 返回元信息和简介;没有独立 comments 动作。',
'字幕依赖可用轨道;转录还需配置服务及额度,登录不保证有字幕。'],
'bilibili': ['read 返回元信息和简介;没有独立 comments 动作。',
- 'Reach subtitle 路径可能要求登录,且视频须有可用字幕。'],
+ 'subtitle 当前读取首P已有字幕;可能要求登录,不代表整套多P视频。'],
'reddit': ['read 仅承诺其返回的帖子和评论;不保证完整评论树,不提供发评论动作。'],
'twitter': ['thread 仅覆盖实际返回的回复;不保证完整评论流,不提供发帖动作。'],
'xiaohongshu': ['只报告实际读取的正文、已加载评论和回复,不承诺完整导出。'],
@@ -128,7 +128,7 @@ def installation_report(result):
else:
lines += ['', '还没逐项联网测试。']
lines += ['摘要、标题和链接先从搜索引擎找;评论以已读内容为准,字幕需视频自带。', '',
- '**想查什么,直接说。** 需要登录时,我帮你打开页面,你自己登录就行。']
+ '**想查什么,直接说。** 会先尝试复用已有登录;确实需要你登录时,再打开窗口。']
return '\n'.join(lines) + '\n'
@@ -208,8 +208,8 @@ def cdp_status():
def require_boss_cdp():
- from . import browser
- browser.ensure_running()
+ from . import browser, session_reuse
+ session_reuse.prepare("boss", action_locked=True)
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 9df6753b..977b7fa9 100644
--- a/agent_reach/runtime/result.py
+++ b/agent_reach/runtime/result.py
@@ -36,7 +36,7 @@ DEFAULT_HINTS = {
"BUSY": "Another command uses this browser profile. Wait for it to finish; 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: "Login is required or expired. Guide the user to log in themselves; never log in on their behalf.",
+ 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.",
UPSTREAM_BROKEN: "The upstream tool failed. Tell the user this channel is unavailable right now; do not retry in a loop.",
TIMEOUT: "The operation timed out. Inspect channel status and the failed stage; do not reopen login windows or repeat requests in a loop.",
RATE_LIMITED: "The platform reported a rate limit. Reach pauses this channel; respect retry_after_seconds and do not switch backends.",
diff --git a/agent_reach/runtime/run.py b/agent_reach/runtime/run.py
index ed9f1c66..a7cf2e02 100644
--- a/agent_reach/runtime/run.py
+++ b/agent_reach/runtime/run.py
@@ -33,6 +33,7 @@ def run_cmd(
env: Optional[Mapping[str, str]] = None,
cwd: Optional[str] = None,
label: Optional[str] = None,
+ input_data: Optional[str] = None,
) -> str:
"""Run an upstream command and return stdout.
@@ -56,13 +57,14 @@ def run_cmd(
[exe, *argv[1:]],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
- stdin=subprocess.DEVNULL,
+ stdin=subprocess.PIPE if input_data is not None else subprocess.DEVNULL,
env=run_env,
cwd=cwd or os.path.expanduser("~"),
start_new_session=(os.name != "nt" and not supervised),
)
try:
- out, err = proc.communicate(timeout=max(timeout, 0.1))
+ kwargs = {"input": input_data.encode("utf-8")} if input_data is not None else {}
+ out, err = proc.communicate(timeout=max(timeout, 0.1), **kwargs)
except subprocess.TimeoutExpired:
if os.name == "nt":
# Kill this command's descendants too (Playwright driver + Chrome).
diff --git a/agent_reach/runtime/session_reuse.py b/agent_reach/runtime/session_reuse.py
new file mode 100644
index 00000000..e64cda53
--- /dev/null
+++ b/agent_reach/runtime/session_reuse.py
@@ -0,0 +1,102 @@
+"""Site-scoped local session reuse. Source browsers are read-only and never cloned.
+
+The user removed the dedicated-only policy. Use existing connected browsers,
+then saved Reach state, before requesting a human login. No password/keychain API.
+"""
+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 .result import NEED_SETUP, UPSTREAM_BROKEN, ReachError
+
+
+def _cookies(rows, domains) -> list:
+ out = []
+ for row in rows:
+ if not isinstance(row, dict) or not row.get("name") or "value" not in row:
+ continue
+ if not any(cdp.domain_matches(str(row.get("domain", "")), domain) for domain in domains):
+ continue
+ expires = row.get("expires", row.get("expirationDate", -1))
+ if not isinstance(expires, (int, float)) or (0 < expires <= time.time()):
+ continue
+ cookie = {k: row[k] for k in ("name", "value", "domain", "path", "secure", "httpOnly") if k in row}
+ cookie["expires"] = expires
+ same = {"no_restriction": "None", "lax": "Lax", "strict": "Strict",
+ "None": "None", "Lax": "Lax", "Strict": "Strict"}.get(str(row.get("sameSite", "")))
+ if same:
+ cookie["sameSite"] = same
+ out.append(cookie)
+ return out
+
+
+def profiles() -> list:
+ return [{"id": context, "dedicated": context == browser.bound_context()}
+ for context in browser.connected_contexts()]
+
+
+def use(profile: str) -> dict:
+ if profile == browser.bound_context() or profile not in browser.connected_contexts():
+ raise ReachError(NEED_SETUP, "Choose a connected local browser profile from browser profiles")
+ state.mutate(lambda data: data.update(local_browser_source=profile, session_reuse={}))
+ return {"source_profile": profile, "scope": "requested site only", "source_changed": False}
+
+
+def _source_cookies(channel: str, domains) -> tuple[list, str]:
+ from agent_reach.backends.opencli import export_site_cookies
+ contexts = [p["id"] for p in profiles() if not p["dedicated"]]
+ preferred = state.load().get("local_browser_source")
+ if preferred:
+ contexts = [preferred] if preferred in contexts else []
+ found = []
+ for context in contexts:
+ try:
+ cookies = _cookies([c for domain in domains for c in export_site_cookies(context, domain)], domains)
+ except ReachError:
+ continue # a disconnected source must not prevent use of saved Reach login
+ if cookies:
+ found.append((cookies, context))
+ if len(found) > 1:
+ raise ReachError(NEED_SETUP, "Several local browsers have cookies for this site; choose which account to reuse",
+ hint="Run agent-reach browser profiles, then browser use ID. No account was copied.")
+ if found:
+ return found[0]
+ # Older Reach versions stored the user's login in a per-site owned snapshot.
+ source = state.root() / "sessions" / (channel + "-cloak") / "profile" / "reach-session.json"
+ try:
+ data = json.loads(read_small_text_no_follow(source, max_bytes=2 * 1024 * 1024) or "{}")
+ cookies = _cookies(data.get("cookies", []), domains)
+ except (OSError, ValueError, PrivatePathError):
+ cookies = []
+ return cookies, "saved-reach-session" if cookies else "saved-profile"
+
+
+def prepare(channel: str, *, force: bool = False, action_locked: bool = False) -> dict:
+ """Try a local login once per hour/site; business success is verified 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"):
+ browser.ensure_running()
+ record = state.load().get("session_reuse", {}).get(channel, {})
+ if not force and (record.get("blocked") or record.get("source") == "manual"
+ or (record.get("copied_cookies", 0) > 0 and state.age_seconds(record.get("at")) < 3600)):
+ return record
+ cookies, source = _source_cookies(channel, site_domains(ch))
+ if cookies:
+ if cdp.call("Storage.setCookies", {"cookies": cookies}) is None:
+ raise ReachError(UPSTREAM_BROKEN, "Could not apply the local site session; the original browser is unchanged")
+ browser.save_session()
+ result = {"source": source, "copied_cookies": len(cookies), "at": state.now(),
+ "verified": False, "source_changed": False}
+ state.mutate(lambda data: data.setdefault("session_reuse", {}).__setitem__(channel, result))
+ return result
diff --git a/agent_reach/skill/SKILL.md b/agent_reach/skill/SKILL.md
index fd5311ad..82b1d0c9 100644
--- a/agent_reach/skill/SKILL.md
+++ b/agent_reach/skill/SKILL.md
@@ -34,7 +34,7 @@ metadata:
1. **公开信息**:有链接先用已有网页工具打开;找内容先用已有搜索工具,按需加 `site:平台域名`。正文、评论、字幕分别检查是否已满足请求。已有结果足够就直接回答,不准备渠道或登录。
2. **补充能力**:公开结果缺少用户需要的部分、现有工具不可用,或用户要求 Reach 已声明的结构化/站内动作时,再查 `agent-reach channels`,调用对应动作。已有免登录原生工具或公开接口可直接复用;不要求每个任务先重复做一次网页搜索。网页工具不可用时,Reach `web search` / `web read` 提供匿名保底。
-3. **按需认证**:仅当尚未满足的任务所选路径确实要求登录时,再加载 [会话配置](references/sessions.md),复用专用浏览器已保存的会话或请用户本人登录。没有配置浏览器说明需要配置;403、验证码、DNS/TLS 错误、限流、超时按各自原因处理。正文旁的登录按钮不算登录墙。
+3. **按需认证**:仅当尚未满足的任务所选路径确实要求登录时,再加载 [会话配置](references/sessions.md),先复用本机已有的该站登录和 Reach 保存的会话,失效或缺失时再请用户本人登录。没有配置浏览器说明需要配置;403、验证码、DNS/TLS 错误、限流、超时按各自原因处理。正文旁的登录按钮不算登录墙。
4. **交付已有结果**:保留公开结果,说明缺少正文、哪些评论或字幕;登录仅服务于剩余缺口。用户跳过登录也能拿到已读取的内容。评论计数、字幕轨道清单、页面壳、搜索摘要分别标注,不当成评论正文、字幕正文或完整文章。
平台名称和 URL 用来识别来源,不自动触发安装、`ensure` 或登录。用户要求安装、登录或退出时读会话配置;故障、升级或卸载时读 [维护说明](references/maintenance.md),查询时按需加载。
@@ -67,7 +67,7 @@ agent-reach read <链接> # 给链接,自动认出渠道
2. 实际调用 Reach 渠道前说一句"用 agent-reach 的 X 渠道"。
3. 多平台调研按会话分组;共用浏览器的命令串行,独立会话可以并行。
4. 只做读取。发帖、评论、点赞一律不做。
-5. 不读取或导入个人浏览器登录。需要认证时,只在 Reach 专用窗口由用户本人登录;不得输出 Cookie、Token 或凭据。
+5. 优先复用本地已有的站点登录:已连接的浏览器只读导出当前网站 Cookie,原浏览器不变;不得输出凭据。缺失或失效时,才由用户本人登录。
## 渠道
@@ -81,7 +81,7 @@ agent-reach read <链接> # 给链接,自动认出渠道
-`setup` 安装默认渠道;`add` 为浏览器渠道自动准备共用浏览器和插件。`login <渠道>` 打开该网站,由用户登录。先复用专用浏览器已保存的会话;程序定期保存登录,无需关窗。业务访问需要实际验证。
+`setup` 安装默认渠道;`add` 为浏览器渠道自动准备共用浏览器和插件。`login <渠道>` 打开该网站,由用户登录。先尝试复用本地浏览器已有的站点登录;程序定期保存,无需关窗。业务访问需要实际验证。
小红书 read 仅返回文字描述,不声称理解图片/视频。BOSS 搜索若 salary_encoded=true,不能猜数字;read 职位链接获取详情中的可读薪资。
@@ -118,11 +118,11 @@ agent-reach read <链接> # 给链接,自动认出渠道
## 共用专用浏览器
-所有浏览器渠道使用 `~/.agent-reach/browser/profile`,CloakBrowser 优先,下载失败回退本机 Chrome。OpenCLI 插件自动准备,网页提取由上游 OpenCLI 或原生 CLI 执行。BOSS 使用同一专用浏览器;不启动额外个人 Chrome。闲置 10 分钟自动关闭,下次调用自动重开。
+普通查询默认 headless,不弹窗;`login CHANNEL` 才显窗,下一次查询收回窗口转回无头,始终沿用同一配置。所有浏览器渠道使用 `~/.agent-reach/browser/profile`,CloakBrowser 优先,下载失败回退本机 Chrome。OpenCLI 插件自动准备,网页提取由上游 OpenCLI 或原生 CLI 执行。BOSS 使用同一专用浏览器;不启动额外个人 Chrome。闲置 10 分钟自动关闭,下次调用自动重开。
需要 Reach 时可直接运行 `agent-reach execute CHANNEL ACTION --params '{...}'`,程序准备依赖并执行真实动作,无需先额外搜索一次。`ensure CHANNEL` 留给安装验收和排障;需要本人登录会返回明确提示。`execute` 返回 `operation_id` 时,在用户完成后运行 `agent-reach resume OPERATION_ID`。本版没有 ask 或 Reach MCP 服务,无需模型 API Key。
-只复用专用浏览器已保存的登录,不读取或导入个人 Chrome 的登录。定期保存会话;真实页面操作和 Reach 调用重置十分钟计时。OpenCLI Bridge 随浏览器启动和回收;已有用户进程保留,版本冲突交由用户处理。详细步骤见 [sessions.md](references/sessions.md)。
+优先按站点复用本地已有登录;默认使用已连接的浏览器,只读复制当前网站 Cookie。多个来源对应不同账号时,用 `browser profiles` / `browser use ID` 选择,不随机切换。来源不可用时保留 Reach 已保存的会话。定期保存会话;真实页面操作和 Reach 调用重置十分钟计时。OpenCLI Bridge 随浏览器启动和回收;已有用户进程保留,版本冲突交由用户处理。详细步骤见 [sessions.md](references/sessions.md)。
`agent-reach add CHANNEL` 会准备渠道所需依赖、专用浏览器和插件;`remove CHANNEL` 清除该网站的登录和存储,保留其他网站。小宇宙保留为可选转录渠道,需要 Groq Key。
diff --git a/agent_reach/skill/SKILL_en.md b/agent_reach/skill/SKILL_en.md
index dc683fbf..e084078f 100644
--- a/agent_reach/skill/SKILL_en.md
+++ b/agent_reach/skill/SKILL_en.md
@@ -69,7 +69,7 @@ Results:
2. Say "using agent-reach channel X" before calling a Reach channel.
3. Serialize commands sharing one browser profile; independent sessions may run in parallel.
4. Read only. Never post, comment, or like.
-5. Never read or import personal-browser authentication. The user logs in only in the Reach browser. Never output credentials.
+5. Reuse existing local site sessions first through read-only, site-scoped Browser Bridge export. Keep source browsers unchanged and never print credentials. Human login is the fallback.
## Channels
@@ -82,7 +82,7 @@ The login column lists authentication entry points, not prerequisites for public
## Reuse before login
-`setup` installs defaults; adding a browser channel prepares the shared browser and extension. `login CHANNEL` opens the site for the user to log in. Reuse saved dedicated sessions and verify the requested action. Never import personal-browser login.
+`setup` installs defaults; adding a browser channel prepares the shared browser and extension. `login CHANNEL` opens the site for the user to log in. Reuse saved dedicated sessions and verify the requested action. Read only the requested site’s local session.
XHS read returns text descriptions, not image/video understanding. Never guess BOSS salary digits when salary_encoded=true; read the job detail instead.
@@ -117,10 +117,10 @@ After the user agrees, read [Maintenance](references/maintenance.md) and confirm
## Shared dedicated browser
-All browser channels use `~/.agent-reach/browser/profile`. CloakBrowser is preferred; installation/download failure falls back to installed Chrome. OpenCLI prepares the extension and performs website extraction. BOSS uses the same dedicated browser. The idle watcher closes it after ten minutes; the next action reopens it.
+Queries default to headless. Explicit login opens a window; the next query switches back using the same profile. All browser channels use `~/.agent-reach/browser/profile`. CloakBrowser is preferred; installation/download failure falls back to installed Chrome. OpenCLI prepares the extension and performs website extraction. BOSS uses the same dedicated browser. The idle watcher closes it after ten minutes; the next action reopens it.
Use `agent-reach execute CHANNEL ACTION --params '{...}'` to prepare and perform the real action once. Reserve `ensure CHANNEL` for setup checks and diagnosis. After the user completes a requested login, use `agent-reach resume OPERATION_ID` when an operation ID was returned. There is no Reach MCP server or model planner in this version, and no model API key is required.
-Reuse only the dedicated browser’s saved login. Never read or import personal-browser authentication. The user logs in in the Reach window; sessions are saved periodically. Human page input and Reach calls reset the idle timer. The official Bridge is supervised alongside the browser; existing user processes are preserved. See [Sessions](references/sessions.md).
+Reuse the requested site’s existing local login first. Use a connected local Browser Bridge source or saved Reach state; preserve the source. Choose explicitly when multiple source accounts are available. The user logs in in the Reach window; sessions are saved periodically. Human page input and Reach calls reset the idle timer. The official Bridge is supervised alongside the browser; existing user processes are preserved. See [Sessions](references/sessions.md).
`add CHANNEL` prepares dependencies, browser and extension. `remove CHANNEL` clears only that site's login/storage, preserving other sites. Xiaoyuzhou remains an optional transcription channel requiring a Groq key.
diff --git a/agent_reach/skill/references/sessions.md b/agent_reach/skill/references/sessions.md
index 365098e6..d269dc87 100644
--- a/agent_reach/skill/references/sessions.md
+++ b/agent_reach/skill/references/sessions.md
@@ -11,13 +11,19 @@
3. 只有实际返回 NEED_LOGIN 才请用户登录;`agent-reach login CHANNEL` 打开专用浏览器,登录由用户本人完成。BOSS 等原生工具按返回提示执行 `login CHANNEL --sync`。
4. 若返回 operation_id,用户完成后使用 `agent-reach resume OPERATION_ID`。保存的是任务参数,不会为等待登录另起常驻任务服务。
-## 保存与复用
+## 默认无头,优先复用已有登录
-只复用 Reach 专用浏览器中已保存的登录。程序不读取个人 Chrome 的 Cookie、登录文件或账号,也不提供导入入口。首次需要登录时,由用户在专用窗口完成。
+查询默认 headless,不弹窗口。`login CHANNEL` 专门给本人登录,会显示窗口;下一次查询先保存,再用同一配置转回无头。先恢复保存的会话,再打开目标页。
-登录期间会定期保存会话,无需关窗才能保存。鼠标点击、键盘和滚动等真实页面操作以及 Reach 调用会重置十分钟计时;没有操作时自动关闭,下次查询自动重开。网站要求扫码、验证码或确认时交给用户,失败不反复开窗。
+第一次调用网站时,优先从已连接的本地浏览器只读复制该站 Cookie;不会复制整个 Chrome 目录、其他网站登录、访问密码库或修改来源。没有可用来源时继续用 Reach 保存的会话,包括旧版分站快照。Cookie 存在不代表登录有效,必须看真实动作结果。
-OpenCLI Bridge 随专用浏览器由计时程序启动、回收。已有的兼容 Bridge 可复用,Reach 不关闭用户启动的进程;Reach 自己启动的桥始终随专用浏览器回收,其他客户端可由上游重新连接。版本冲突时提示用户处理,不自动重启别人的服务。
+原 Chrome 需已连接官方 OpenCLI 扩展;未连接时不能承诺自动复用,也不据此认定账号未登录。只有实际需要本人登录时才打开专用窗口。Cloak 内核不依赖该来源才能启动;已有专用会话仍可独立复用。
+
+多个本地浏览器都可能有该站账号时:`browser profiles` 查看连接,`browser use ID` 选择来源。`login CHANNEL --import-existing` 可主动刷新该站登录,不打开登录窗口。普通调用不会反复复制;退出和删除渠道后停止自动导入,避免登录复活。
+
+BOSS 搜索和搜索结果的 JD 读取都走上游 CLI 的浏览器通道,共用该配置;短期职位引用只保存在本地,不返回给模型。B站只在读字幕时尝试把已有站点登录交给官方 B站 CLI,普通搜索不准备浏览器。雪球社区动作会自动同步已有登录,无需额外执行同步命令。
+
+登录期间定期保存,无需关窗才能保存。真实页面操作和 Reach 调用重置十分钟计时。OpenCLI Bridge 随专用浏览器由计时程序管理;Reach 启动的桥随浏览器退出,用户已有桥保留。
CloakBrowser 下载失败后会记住 Chrome 回退,避免每次查询重新下载。修好网络后可用 `agent-reach browser setup --retry-cloak` 重试。
diff --git a/docs/cloakbrowser.md b/docs/cloakbrowser.md
index 16f7056a..646bbe63 100644
--- a/docs/cloakbrowser.md
+++ b/docs/cloakbrowser.md
@@ -4,7 +4,7 @@ CloakBrowser supplies the browser, and OpenCLI/boss-agent-cli supply website ext
`add` prepares Node, OpenCLI, the browser and extension. CloakBrowser runs through its public persistent-context launcher in a private tool environment. Its binaries are cached under `~/.agent-reach/cloak-binaries`; installation/download failure falls back to installed Chrome. The next browser action automatically prepares/reopens the same profile. BOSS uses this browser's CDP endpoint. On Windows the Cloak extension is loaded automatically; a system-Chrome fallback may need Web Store installation.
-Only the shared dedicated profile is reused. Personal-browser authentication import is unavailable. Human login is periodically saved; trusted page input and Reach calls reset idle closure. The official OpenCLI Bridge is supervised with the dedicated browser. Existing user-owned bridges are preserved; version conflicts require user action.
+Queries default to headless; human login opens a window using the same profile. Existing local site cookies are reused through a connected official Browser Bridge, read-only and scoped to the requested site. Saved Reach sessions remain usable when no local source is connected. Human login is periodically saved; trusted page input and Reach calls reset idle closure. The official OpenCLI Bridge is supervised with the dedicated browser. Existing user-owned bridges are preserved; version conflicts require user action.
Previous Reach-owned per-site snapshots are merged once without replacing newer shared cookies. Logout/removal clears the retired per-site state too. Chrome fallback is remembered; use `agent-reach browser setup --retry-cloak` after fixing the download connection.
diff --git a/docs/install.md b/docs/install.md
index 38802a9b..72127314 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -57,7 +57,7 @@ Before selecting Reach for a platform mention, check whether existing public too
When the user asks for a channel, run `agent-reach add <channel>`. Browser channels install Node, OpenCLI, the dedicated browser and its extension automatically. One profile under `~/.agent-reach/browser/profile` is shared by all sites. CloakBrowser is preferred; download failure falls back to installed Chrome. The owned browser closes after 10 idle minutes and reopens on the next action. The Chrome fallback on Windows may need one Web Store click.
-Reuse only already-saved Reach dedicated sessions. Never read or import personal-browser cookies or login files. The user logs in in the Reach window. Login is periodically saved without requiring the user to close the window. Human page interactions and Reach calls reset the idle timer. The Bridge is supervised with the browser; existing user-owned Bridge processes are preserved, and version conflicts are reported without restarting them.
+Queries default to headless and first try a read-only export of the requested site’s cookies from an existing connected local browser. No source browser is changed, no full Chrome profile is cloned, and no password/keychain is accessed. If no connected source is available, use saved Reach state. Multiple possible accounts require browser profiles/use selection. Only missing/expired login needs the human in a visible Reach window; the next query returns to headless with the same profile. Login is periodically saved without requiring the user to close the window. Human page interactions and Reach calls reset the idle timer. The Bridge is supervised with the browser; existing user-owned Bridge processes are preserved, and version conflicts are reported without restarting them.
If login is still needed, `agent-reach login CHANNEL` opens the shared dedicated browser. The user logs in there; for native tools, follow the returned sync instruction. `agent-reach execute CHANNEL ACTION --params '{...}'` prepares and executes the actual task once. If it returns `operation_id`, use `agent-reach resume OPERATION_ID` after the user finishes login. No additional model key is required.
diff --git a/docs/validation/dedicated-policy-20261020.md b/docs/validation/dedicated-policy-20261020.md
index 687a0ed5..d13758a8 100644
--- a/docs/validation/dedicated-policy-20261020.md
+++ b/docs/validation/dedicated-policy-20261020.md
@@ -1,5 +1,7 @@
# Dedicated browser policy audit — 2026-10-20
+Historical candidate record. The user subsequently authorized local site-session reuse. Current behavior and acceptance are in [headless-session-reuse-20261021.md](headless-session-reuse-20261021.md); dedicated-only authentication statements below are superseded, not current rules.
+
Candidate only. PR #815 remains a draft against `release/1.6`. No merge, tag or official release. Package version remains 1.6.0. The earlier 63c272a claim of complete acceptance was too broad.
## Review findings and fixes
diff --git a/docs/validation/headless-session-reuse-20261021.md b/docs/validation/headless-session-reuse-20261021.md
new file mode 100644
index 00000000..878c1a98
--- /dev/null
+++ b/docs/validation/headless-session-reuse-20261021.md
@@ -0,0 +1,43 @@
+# 无头查询与本地登录复用验收(2026-10-21)
+
+这是测试候选记录。目标是让用户直接说任务,由程序复用已有站点登录、准备依赖并执行;只有真正缺少登录或需要本人验证时才请用户操作。全部操作只读,未修改上游源码或原浏览器。此记录取代此前“只允许在专用浏览器登录”的候选规则。
+
+## 已改的流程
+
+1. 公开内容仍先用 Agent 已有搜索和读取,足够时直接回答。
+2. 需要 Reach 的动作时,普通查询默认无头。先从已连接的本地官方 Browser Bridge 只读复制所需网站 Cookie;不碰密码库、Cookie 数据库或其他网站。
+3. 没有来源连接时保留已有 Reach 会话。多个来源不猜账号,选择一次来源;Cookie 复制成功不等于登录已经验证。
+4. 本人登录才显窗,定期保存。下一次查询在同一配置转回无头,先恢复会话再打开目标页。
+5. 退出或删除渠道后停止自动导入;原浏览器不变。验证码停止,限流暂停一小时,不更换账号或后端重试。
+
+## 真实业务验收
+
+下表列明已取得的粒度;搜索卡片不算正文,已加载回复不等于完整评论树。最终源代码对应的计数和时间见 `release-acceptance.json`。
+
+| 渠道 | 结果 | 实际取得的内容 |
+|---|---|---|
+| 小红书 | 通过 | 搜索、文字描述、已加载评论和回复;图像内容未做识别 |
+| BOSS | 通过 | 深圳岗位搜索、搜索结果的 JD;均走同一浏览器 |
+| X / Twitter | 通过 | 搜索、主页、用户推文、所返回的线程回复 |
+| Reddit | 通过 | 搜索、帖子正文和返回的评论、板块列表;公开网页路径仍可免登录先用 |
+| Facebook | 通过 | 搜索卡片、用户主页信息;未声明完整帖子或评论导出 |
+| 雪球 | 通过 | 热帖、热股;公开行情和股票搜索不准备浏览器 |
+| B站 | 通过 | 首P已有字幕,所测样本返回 979 字;不代表整套多P视频 |
+| Instagram | 未通过 | 搜索接口返回 404;主页接口明确返回 429,已停止并进入限流保护 |
+| LinkedIn | 正式路由未通过 | 现有 1.8.7 卡在等待 Jobs;隔离的官方 2.0.1 + CDP 搜到职位,尚未接入正式路由 |
+
+Instagram 的 404 不应引导反复重登,错误映射已修正。限流解除后才能继续验收。领英的新后端是否接入,需要确认后再改依赖;独立试验结果不计正式通过。
+
+## 修复与边界
+
+- 默认无头已通过实际进程参数验证。显窗、无头切换使用同一配置,Cookie 和 localStorage 在本地测试页上保留;测试页状态随后清除。
+- 首次复用小红书前后,来源站点 Cookie 对照一致。凭据只在本机传递,不输出到模型上下文。
+- 修复后台执行线程重复获取共享浏览器锁造成的 BUSY。
+- BOSS JD 调用上游 `job_card_browser()`,不调用会走独立 HTTP 会话的 `job_detail()` / `job_card()`。短期职位引用保存在渠道私有目录,账号会话改变后失效,不输出 securityId/lid。
+- B站用上游官方凭据写入接口,站点登录通过进程标准输入传递。没有可用来源时沿用已保存的原生 CLI 登录;没有字幕与字幕下载失败分别报告。
+- 雪球只为社区动作自动同步登录。Node 警告不再盖住真正的上游错误;HTTP 404 不再仅因提示中有 login 字样被归为未登录。
+- macOS 回归测试通过;Windows 无头、登录复用和业务动作尚需真机复测。
+
+本轮尚未完成所有登录渠道的目标,不合并、不发布。发布门禁仍要求全部已声明动作的当前源码实测,单元测试不能代替业务结果。候选包不含账号、Cookie、Key、浏览器配置或浏览器二进制。
+
+本轮最终源码:`4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685`。17/17 个所测动作通过,对应 7 类登录渠道;全项目 40 个声明动作中仍有 23 个缺少本次源码的实测,所以发布门禁保持阻断。411 项单测、Ruff 和 Mypy 通过。官方 OpenCLI 1.8.7 的 2,340 个发布文件再次逐字节核对,无修改。
diff --git a/docs/validation/release-acceptance.json b/docs/validation/release-acceptance.json
index 2ccd6b9e..d401b05e 100644
--- a/docs/validation/release-acceptance.json
+++ b/docs/validation/release-acceptance.json
@@ -1,279 +1,368 @@
{
- "candidate": true,
- "version": "1.6.0",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
- "recorded_at": "2026-10-20T15:43:26Z",
- "release_ready": false,
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
"results": [
{
- "channel": "github",
+ "channel": "xiaohongshu",
"action": "search",
- "at": "2026-10-20T15:42:19Z",
+ "at": "2026-10-20T16:54:27Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
- "backend": "gh",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
"passed": true,
"item_count": 2,
- "elapsed_ms": 2089,
+ "text_chars": 0,
+ "elapsed_ms": 3103,
"error": null
},
{
- "channel": "youtube",
- "action": "search",
- "at": "2026-10-20T15:42:26Z",
+ "channel": "xiaohongshu",
+ "action": "read",
+ "at": "2026-10-20T16:54:40Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
- "backend": "yt-dlp",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
"passed": true,
- "item_count": 2,
- "elapsed_ms": 7279,
+ "item_count": 1,
+ "text_chars": 22,
+ "elapsed_ms": 5269,
"error": null
},
{
- "channel": "bilibili",
+ "channel": "xiaohongshu",
+ "action": "comments",
+ "at": "2026-10-20T16:54:58Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
+ "passed": true,
+ "item_count": 25,
+ "text_chars": 519,
+ "elapsed_ms": 9435,
+ "error": null
+ },
+ {
+ "channel": "reddit",
"action": "search",
- "at": "2026-10-20T15:42:27Z",
+ "at": "2026-10-20T16:55:17Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
- "backend": "bili-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
"passed": true,
"item_count": 2,
- "elapsed_ms": 1090,
+ "text_chars": 0,
+ "elapsed_ms": 10631,
"error": null
},
{
- "channel": "v2ex",
- "action": "hot",
- "at": "2026-10-20T15:42:30Z",
+ "channel": "reddit",
+ "action": "read",
+ "at": "2026-10-20T16:55:34Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
- "backend": "v2ex-api",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
"passed": true,
- "item_count": 3,
- "elapsed_ms": 2154,
+ "item_count": 1,
+ "text_chars": 17821,
+ "elapsed_ms": 9088,
"error": null
},
{
- "channel": "web",
- "action": "search",
- "at": "2026-10-20T15:42:31Z",
+ "channel": "reddit",
+ "action": "subreddit",
+ "at": "2026-10-20T16:55:49Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
- "backend": "exa",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
"passed": true,
"item_count": 2,
- "elapsed_ms": 1686,
+ "text_chars": 0,
+ "elapsed_ms": 6758,
"error": null
},
{
- "channel": "xiaohongshu",
+ "channel": "twitter",
"action": "search",
- "at": "2026-10-20T15:42:35Z",
+ "at": "2026-10-20T16:56:05Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
"backend": "opencli",
"passed": true,
"item_count": 2,
- "elapsed_ms": 3129,
+ "text_chars": 1058,
+ "elapsed_ms": 8377,
"error": null
},
{
- "channel": "xiaohongshu",
- "action": "read",
- "at": "2026-10-20T15:42:50Z",
+ "channel": "twitter",
+ "action": "profile",
+ "at": "2026-10-20T16:56:20Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
"backend": "opencli",
"passed": true,
"item_count": 1,
- "elapsed_ms": 7262,
+ "text_chars": 0,
+ "elapsed_ms": 6619,
"error": null
},
{
- "channel": "xiaohongshu",
- "action": "comments",
- "at": "2026-10-20T15:43:08Z",
+ "channel": "twitter",
+ "action": "tweets",
+ "at": "2026-10-20T16:56:42Z",
"os": "macOS",
"method": "real-cli",
- "source_sha256": "36a297596b48bf7872e2e602731a2e3fd36bc147a2cf6dedab997a545fa5c645",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
"backend": "opencli",
"passed": true,
- "item_count": 25,
- "elapsed_ms": 9729,
+ "item_count": 2,
+ "text_chars": 759,
+ "elapsed_ms": 13774,
"error": null
- }
- ],
- "pending": [
- {
- "channel": "bilibili",
- "action": "hot",
- "reason": "Not accepted on this candidate"
},
{
- "channel": "bilibili",
- "action": "read",
- "reason": "Not accepted on this candidate"
- },
- {
- "channel": "bilibili",
- "action": "subtitle",
- "reason": "Not accepted on this candidate"
- },
- {
- "channel": "boss",
- "action": "read",
- "reason": "Requires human platform verification before another request"
+ "channel": "twitter",
+ "action": "thread",
+ "at": "2026-10-20T16:57:02Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
+ "passed": true,
+ "item_count": 50,
+ "text_chars": 10375,
+ "elapsed_ms": 11982,
+ "error": null
},
{
- "channel": "boss",
+ "channel": "facebook",
"action": "search",
- "reason": "Requires human platform verification before another request"
+ "at": "2026-10-20T16:57:21Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
+ "passed": true,
+ "item_count": 1,
+ "text_chars": 22,
+ "elapsed_ms": 10282,
+ "error": null
},
{
"channel": "facebook",
"action": "profile",
- "reason": "Not accepted on this candidate"
+ "at": "2026-10-20T16:57:37Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "opencli",
+ "passed": true,
+ "item_count": 1,
+ "text_chars": 0,
+ "elapsed_ms": 8321,
+ "error": null
},
{
- "channel": "facebook",
+ "channel": "boss",
"action": "search",
- "reason": "Not accepted on this candidate"
+ "at": "2026-10-20T16:57:46Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "boss-agent-cli",
+ "passed": true,
+ "item_count": 2,
+ "text_chars": 58,
+ "elapsed_ms": 1220,
+ "error": null
},
{
- "channel": "github",
+ "channel": "boss",
"action": "read",
- "reason": "Not accepted on this candidate"
+ "at": "2026-10-20T16:57:55Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "boss-agent-cli",
+ "passed": true,
+ "item_count": 1,
+ "text_chars": 525,
+ "elapsed_ms": 626,
+ "error": null
},
{
- "channel": "instagram",
- "action": "posts",
- "reason": "Not accepted on this candidate"
+ "channel": "xueqiu",
+ "action": "hot_posts",
+ "at": "2026-10-20T16:58:04Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "xueqiu-api",
+ "passed": true,
+ "item_count": 2,
+ "text_chars": 274,
+ "elapsed_ms": 614,
+ "error": null
},
{
- "channel": "instagram",
- "action": "profile",
- "reason": "Not accepted on this candidate"
+ "channel": "xueqiu",
+ "action": "hot_stocks",
+ "at": "2026-10-20T16:58:13Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "xueqiu-api",
+ "passed": true,
+ "item_count": 2,
+ "text_chars": 43,
+ "elapsed_ms": 547,
+ "error": null
},
{
- "channel": "instagram",
- "action": "search",
- "reason": "Not accepted on this candidate"
- },
+ "channel": "bilibili",
+ "action": "subtitle",
+ "at": "2026-10-20T16:58:22Z",
+ "os": "macOS",
+ "method": "real-cli",
+ "source_sha256": "4b83ad3557945be1a47ab37790696fc2850737bf60398659fac15420b9919685",
+ "backend": "bili-cli",
+ "passed": true,
+ "item_count": 1,
+ "text_chars": 979,
+ "elapsed_ms": 1654,
+ "error": null
+ }
+ ],
+ "candidate": true,
+ "version": "1.6.0",
+ "recorded_at": "2026-10-20T16:58:46Z",
+ "release_ready": false,
+ "pending": [
{
- "channel": "linkedin",
- "action": "jobs",
- "reason": "Not accepted on this candidate"
+ "channel": "bilibili",
+ "action": "hot",
+ "reason": "Not accepted on this source"
},
{
- "channel": "linkedin",
+ "channel": "bilibili",
"action": "read",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
- "channel": "reddit",
+ "channel": "bilibili",
+ "action": "search",
+ "reason": "Not accepted on this source"
+ },
+ {
+ "channel": "github",
"action": "read",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
- "channel": "reddit",
+ "channel": "github",
"action": "search",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
- "channel": "reddit",
- "action": "subreddit",
- "reason": "Not accepted on this candidate"
+ "channel": "instagram",
+ "action": "posts",
+ "reason": "Platform returned HTTP 429; one-hour cooldown, no retries"
},
{
- "channel": "twitter",
+ "channel": "instagram",
"action": "profile",
- "reason": "Not accepted on this candidate"
+ "reason": "Platform returned HTTP 429; one-hour cooldown, no retries"
},
{
- "channel": "twitter",
+ "channel": "instagram",
"action": "search",
- "reason": "Not accepted on this candidate"
+ "reason": "Platform returned HTTP 429; one-hour cooldown, no retries"
},
{
- "channel": "twitter",
- "action": "thread",
- "reason": "Not accepted on this candidate"
+ "channel": "linkedin",
+ "action": "jobs",
+ "reason": "Official CDP trial succeeded; current route still fails, integration decision pending"
},
{
- "channel": "twitter",
- "action": "tweets",
- "reason": "Not accepted on this candidate"
+ "channel": "linkedin",
+ "action": "read",
+ "reason": "Official CDP trial succeeded; current route still fails, integration decision pending"
+ },
+ {
+ "channel": "v2ex",
+ "action": "hot",
+ "reason": "Not accepted on this source"
},
{
"channel": "v2ex",
"action": "node",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
"channel": "v2ex",
"action": "read",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
"channel": "v2ex",
"action": "user",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
"channel": "web",
"action": "read",
- "reason": "Not accepted on this candidate"
- },
- {
- "channel": "xiaoyuzhou",
- "action": "transcribe",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
- "channel": "xueqiu",
- "action": "hot_posts",
- "reason": "Not accepted on this candidate"
+ "channel": "web",
+ "action": "search",
+ "reason": "Not accepted on this source"
},
{
- "channel": "xueqiu",
- "action": "hot_stocks",
- "reason": "Not accepted on this candidate"
+ "channel": "xiaoyuzhou",
+ "action": "transcribe",
+ "reason": "Not accepted on this source"
},
{
"channel": "xueqiu",
"action": "quote",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
"channel": "xueqiu",
"action": "search",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
"channel": "youtube",
"action": "read",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
+ },
+ {
+ "channel": "youtube",
+ "action": "search",
+ "reason": "Not accepted on this source"
},
{
"channel": "youtube",
"action": "subtitle",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
},
{
"channel": "youtube",
"action": "transcribe",
- "reason": "Not accepted on this candidate"
+ "reason": "Not accepted on this source"
}
],
"additional_required_validation": [
- "Windows dedicated browser, extension connection, manual login, reopen and site cleanup"
+ "Windows headless startup, local site-session reuse, login mode switch, business actions and cleanup"
],
- "privacy": "Counts, timings and error codes only; no credentials, accounts or content URLs"
+ "privacy": "Counts, timings, error codes and source digest only; no account identifiers, credentials or content URLs"
}
diff --git a/tests/test_boss_channel.py b/tests/test_boss_channel.py
index 5da0be58..3cf47a71 100644
--- a/tests/test_boss_channel.py
+++ b/tests/test_boss_channel.py
@@ -18,3 +18,47 @@ def test_can_handle_matches_zhipin_hosts():
"https://[email protected]/job",
]:
assert ch.can_handle(url) is False, url
+
+
+def test_native_detail_uses_browser_only_and_keeps_references_private(monkeypatch, tmp_path):
+ import json
+ import sys
+ from types import SimpleNamespace
+
+ from agent_reach.backends import boss_native
+
+ source='https://github.com/can4hou6joeng4/boss-agent-cli/archive/'+boss_native.COMMIT+'.zip'
+ monkeypatch.setattr(boss_native,'distribution',lambda *a:SimpleNamespace(read_text=lambda *a:json.dumps({'url':source})))
+ calls=[]
+ class Boss:
+ def __init__(self,auth,**kwargs):
+ assert kwargs['browser_source']=='existing-browser'
+ def __enter__(self):return self
+ def __exit__(self,*args):pass
+ def search_jobs(self,*args,**kwargs):
+ return {'code':0,'zpData':{'jobList':[{'encryptJobId':'job','securityId':'private-reference','jobName':'Data'}]}}
+ def job_card_browser(self,ref,lid):
+ calls.append(ref)
+ return {'code':0,'zpData':{'jobCard':{'postDescription':'Real JD'}}}
+ def job_detail(self,*args):raise AssertionError('Independent HTTP used')
+ def job_card(self,*args):raise AssertionError('Hybrid HTTP used')
+ monkeypatch.setitem(sys.modules,'boss_agent_cli.api.client',SimpleNamespace(BossClient=Boss))
+ monkeypatch.setitem(sys.modules,'boss_agent_cli.auth.manager',SimpleNamespace(AuthManager=lambda *a:None))
+ monkeypatch.setitem(sys.modules,'boss_agent_cli.commands.detail',SimpleNamespace(
+ build_job_from_card=lambda card,**k:{'description':card['postDescription'],'security_id':k['security_id']}))
+ spec={'action':'search','query':'Data','limit':1,'data_dir':str(tmp_path),'cdp_url':'http://127.0.0.1:9222','session_stamp':'one'}
+ monkeypatch.setattr(sys,'argv',['boss_native',json.dumps(spec)])
+ result=boss_native.main()
+ assert 'private-reference' not in json.dumps(result)
+ path=tmp_path/'reach-job-refs.json'
+ assert path.stat().st_mode & 0o077 == 0
+ spec.update(action='read',job_id='job')
+ monkeypatch.setattr(sys,'argv',['boss_native',json.dumps(spec)])
+ result=boss_native.main()
+ assert result['data'][0]['description']=='Real JD'
+ assert calls==['private-reference']
+ assert 'security_id' not in result['data'][0]
+ spec['session_stamp']='changed-account'
+ monkeypatch.setattr(sys,'argv',['boss_native',json.dumps(spec)])
+ assert boss_native.main()['error']['code']=='NEED_SETUP'
+ assert calls==['private-reference']
diff --git a/tests/test_browser.py b/tests/test_browser.py
index 3ffbe755..fbc912d5 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -181,6 +181,7 @@ def test_cloak_launcher_shares_profile_and_keeps_bridge_off_proxy(home, monkeypa
assert browser_watcher._launch_cloak("about:blank") is context
kwargs = launch.call_args.kwargs
assert launch.call_args.args == (str(browser.profile_dir()),)
+ assert kwargs["headless"] is True
assert kwargs["extension_paths"] == [str(browser.extension_dir())]
assert kwargs["proxy"] == {"server": "http://127.0.0.1:7890", "username": "user", "password": "pass",
"bypass": "localhost,127.0.0.1,[::1]"}
@@ -201,3 +202,35 @@ def test_migration_keeps_old_profile_and_restores_one_shared_destination(home, m
browser.profile_dir().mkdir()
browser._prepare_shared_profile()
assert browser.profile_dir().is_dir() # migration never repeats on each start
+
+
+def test_chrome_queries_are_headless_and_human_login_is_visible():
+ assert '--headless=new' in browser.chrome_argv('/chrome','about:blank',pipe=False)
+ assert '--headless=new' not in browser.chrome_argv('/chrome','about:blank',pipe=False,headless=False)
+
+
+def test_cloak_manual_login_uses_the_same_profile_with_a_window(home, monkeypatch):
+ import sys
+ from types import SimpleNamespace
+ from unittest.mock import Mock
+
+ from agent_reach.runtime import browser_watcher
+ context=SimpleNamespace(pages=[Mock()])
+ launch=Mock(return_value=context)
+ monkeypatch.setitem(sys.modules,'cloakbrowser',SimpleNamespace(launch_persistent_context=launch))
+ browser_watcher._launch_cloak('https://example.test',headless=False)
+ assert launch.call_args.kwargs['headless'] is False
+ assert launch.call_args.args==(str(browser.profile_dir()),)
+ context.pages[0].goto.assert_not_called() # restoration precedes navigation in the watcher
+
+
+def test_restore_failure_preserves_the_original_snapshot(home, monkeypatch):
+ from agent_reach.runtime.result import ReachError
+ browser.browser_root().mkdir(parents=True)
+ path=browser.browser_root()/'session.json'
+ original=json.dumps({'cookies':[{'name':'sid','value':'saved','domain':'example.test'}]})
+ path.write_text(original)
+ monkeypatch.setattr(cdp,'call',lambda method,*a,**k:{'cookies':[]}if method=='Storage.getCookies'else None)
+ with pytest.raises(ReachError,match='retained'):
+ browser.restore_session()
+ assert path.read_text()==original
diff --git a/tests/test_release_policy.py b/tests/test_release_policy.py
index 259681ce..8f5afc29 100644
--- a/tests/test_release_policy.py
+++ b/tests/test_release_policy.py
@@ -57,7 +57,7 @@ def test_boss_detail_uses_upstream_browser_adapter_without_native_http(monkeypat
call = Mock(return_value=[{"title": "Data Engineer", "description": "JD"}])
monkeypatch.setattr(opencli, "opencli_call", call)
ch = BossChannel()
- assert ch.actions[1].backends == (("opencli", "_opencli_read"),)
+ assert ch.actions[1].backends == (("boss-agent-cli", "_cli_read"), ("opencli", "_opencli_read"))
assert ch._opencli_read(target="https://www.zhipin.com/job_detail/abc123.html", timeout=20)[0]["text"] == "JD"
assert call.call_args.args == ("boss", ["detail", "abc123"])
diff --git a/tests/test_session_onboarding.py b/tests/test_session_onboarding.py
index 7bea94b9..cd464c1b 100644
--- a/tests/test_session_onboarding.py
+++ b/tests/test_session_onboarding.py
@@ -1,4 +1,4 @@
-"""Dedicated-only authentication: prohibited imports never touch a source browser."""
+"""Local site-session reuse never navigates or modifies the source browser."""
import json
import pytest
@@ -20,11 +20,10 @@ def test_unmanaged_debugging_port_is_never_closed_or_navigated(monkeypatch):
@pytest.mark.parametrize("args", [
["browser", "import", "xiaohongshu", "--opencli-profile", "foreign"],
- ["browser", "profiles"],
["ensure", "xiaohongshu", "--reuse-profile", "foreign"],
["browser", "import", "xiaohongshu", "--state-file", "private.json"],
])
-def test_personal_login_import_is_unavailable(args, monkeypatch, capsys):
+def test_retired_raw_import_flags_are_not_accepted(args, monkeypatch, capsys):
monkeypatch.setattr(browser, "ensure_running", lambda: pytest.fail("opened browser"))
monkeypatch.setattr(cdp, "call", lambda *a, **k: pytest.fail("read credentials"))
assert cli.main(args) == 1
@@ -32,7 +31,129 @@ def test_personal_login_import_is_unavailable(args, monkeypatch, capsys):
assert not state.load().get("reuse_sources")
-def test_legacy_cookie_export_and_import_implementations_are_removed():
+def test_local_site_export_uses_the_unmodified_upstream_page_api(monkeypatch):
+ from unittest.mock import Mock
+
+ from agent_reach.backends import opencli
+ from agent_reach.runtime import bridge, run
+ source = state.root() / "upstream/dist/src/daemon.js"
+ module = source.parent / "browser/page.js"
+ module.parent.mkdir(parents=True)
+ module.write_text("// official API fixture")
+ monkeypatch.setattr(bridge, "launch_spec", lambda: (["node", str(source)], "1.8.7"))
+ command = Mock(return_value="[]")
+ monkeypatch.setattr(run, "run_cmd", command)
+ assert opencli.export_site_cookies("local", "xiaohongshu.com") == []
+ args = command.call_args.args[0]
+ assert module.as_uri() in args[3] and args[-2:] == ["local", "xiaohongshu.com"]
+ assert module.read_text() == "// official API fixture"
+
+
+def test_automatic_reuse_copies_only_the_requested_site_and_reuses_cache(monkeypatch):
+ from unittest.mock import Mock
+
from agent_reach.backends import opencli
- assert not hasattr(browser, "import_session")
- assert not hasattr(opencli, "export_site_cookies")
+ from agent_reach.runtime import session_reuse
+ monkeypatch.setattr(browser, 'ensure_running', lambda: None)
+ monkeypatch.setattr(browser, 'connected_contexts', lambda: ['daily', 'owned'])
+ monkeypatch.setattr(browser, 'bound_context', lambda: 'owned')
+ export = Mock(return_value=[{'name':'sid','value':'test','domain':'.xiaohongshu.com','expirationDate':9999999999,'sameSite':'lax'},
+ {'name':'foreign','value':'never-copy','domain':'other.test'},
+ {'name':'expired','value':'never-copy','domain':'.xiaohongshu.com','expirationDate':1}])
+ monkeypatch.setattr(opencli, 'export_site_cookies', export)
+ calls=[]
+ monkeypatch.setattr(cdp, 'call', lambda method, params=None: calls.append((method,params)) or {})
+ result=session_reuse.prepare('xiaohongshu')
+ assert result['copied_cookies']==1 and not result['verified'] and not result['source_changed']
+ cookie=calls[0][1]['cookies'][0]
+ assert cookie['name']=='sid' and cookie['sameSite']=='Lax' and cookie['expires']==9999999999
+ assert session_reuse.prepare('xiaohongshu')==result
+ export.assert_called_once_with('daily','xiaohongshu.com')
+
+
+def test_multiple_local_accounts_are_not_guessed(monkeypatch):
+ from agent_reach.backends import opencli
+ from agent_reach.runtime import session_reuse
+ monkeypatch.setattr(browser,'ensure_running',lambda:None)
+ monkeypatch.setattr(browser,'connected_contexts',lambda:['one','two'])
+ monkeypatch.setattr(opencli,'export_site_cookies',lambda *args:[{'name':'sid','value':'test','domain':'.xiaohongshu.com'}])
+ monkeypatch.setattr(cdp,'call',lambda *a,**k:pytest.fail('ambiguous account copied'))
+ with pytest.raises(ReachError,match='Several'):
+ session_reuse.prepare('xiaohongshu')
+
+
+def test_logout_blocks_automatic_session_revival(monkeypatch):
+ from agent_reach.runtime import session_reuse
+ monkeypatch.setattr(browser,'ensure_running',lambda:None)
+ state.mutate(lambda data:data.update(session_reuse={'xiaohongshu':{'blocked':True}}))
+ monkeypatch.setattr(session_reuse,'_source_cookies',lambda *a:pytest.fail('revived logged-out account'))
+ assert session_reuse.prepare('xiaohongshu')['blocked']
+
+
+def test_unavailable_source_keeps_saved_destination_and_does_not_open_login(monkeypatch):
+ from agent_reach.runtime import session_reuse
+ monkeypatch.setattr(browser,'ensure_running',lambda:None)
+ monkeypatch.setattr(browser,'connected_contexts',lambda:[])
+ monkeypatch.setattr(browser,'start',lambda *a:pytest.fail('opened a login window'))
+ monkeypatch.setattr(cdp,'call',lambda *a,**k:pytest.fail('changed saved session'))
+ result=session_reuse.prepare('xiaohongshu')
+ assert result['source']=='saved-profile' and result['copied_cookies']==0
+
+
+def test_dispatch_worker_reuses_session_without_relocking_the_calling_thread(monkeypatch):
+ from agent_reach.channels.xiaohongshu import XiaoHongShuChannel
+ from agent_reach.runtime import dispatch, run, session_reuse
+ monkeypatch.setattr(browser, 'ensure_running', lambda: None)
+ monkeypatch.setattr(browser, 'bound_context', lambda: 'owned')
+ monkeypatch.setattr(browser, 'save_session', lambda: None)
+ monkeypatch.setattr(session_reuse, '_source_cookies', lambda *a: ([], 'saved-profile'))
+ monkeypatch.setattr(run, 'run_cmd', lambda *a, **k: '[{"title":"real result shape"}]')
+ result=dispatch.run_action(XiaoHongShuChannel(), 'search', {'query':'test','limit':1}, timeout=2)
+ assert result['ok'], result.get('error')
+
+
+def test_bili_reuses_only_site_cookies_through_upstream_writer_and_private_stdin(monkeypatch):
+ from unittest.mock import Mock
+
+ from agent_reach.channels import bilibili
+ from agent_reach.runtime import session_reuse, tools
+ monkeypatch.setattr(session_reuse, '_source_cookies', lambda *a: ([{'name':'SESSDATA','value':'test-secret'}], 'daily'))
+ monkeypatch.setattr(tools,'resolve',lambda *a:'/private/bin/bili')
+ call=Mock(return_value='')
+ monkeypatch.setattr(bilibili,'run_cmd',call)
+ bilibili._reuse_subtitle_login(10)
+ args=call.call_args
+ assert 'test-secret' not in repr(args.args)
+ assert json.loads(args.kwargs['input_data']) == {'SESSDATA':'test-secret'}
+ assert 'save_credential' in args.args[0][-1]
+ assert args.kwargs['env']['HOME'].endswith('/.agent-reach/sessions/bili-cli')
+ state.mutate(lambda data: data['session_reuse'].__setitem__('bilibili', {'blocked':True}))
+ bilibili._reuse_subtitle_login(10)
+ assert call.call_count == 1
+
+
+def test_node_warning_does_not_hide_upstream_error_and_404_is_not_login():
+ from agent_reach.backends.opencli import _opencli_error
+ warning='(node:123) Warning: experimental proxy\n'
+ error=_opencli_error(warning+'ok: false\nerror:\n code: UNKNOWN\n message: HTTP 404 - make sure you are logged in to Instagram\n','login')
+ assert error.code=='UPSTREAM_BROKEN'
+ assert '(node:' not in error.message
+ assert _opencli_error(warning+'ok: false\nerror:\n code: AUTH_REQUIRED\n message: Login required\n','login').code=='NEED_LOGIN'
+
+
+def test_xueqiu_syncs_reused_browser_login_only_for_community_actions(monkeypatch):
+ from unittest.mock import Mock
+
+ from agent_reach.channels import xueqiu
+ from agent_reach.runtime import session_reuse
+ reuse=Mock()
+ sync=Mock()
+ monkeypatch.setattr(session_reuse,'prepare',reuse)
+ monkeypatch.setattr(xueqiu,'_import_from_browser',sync)
+ monkeypatch.setattr(xueqiu,'_xq_json',lambda *a:{})
+ ch=xueqiu.XueqiuChannel()
+ ch._xq_search(query='AAPL',limit=2,timeout=2)
+ reuse.assert_not_called()
+ ch._xq_hot_posts(limit=2,timeout=2)
+ reuse.assert_called_once_with('xueqiu')
+ sync.assert_called_once_with()
diff --git a/tests/test_unified_entry.py b/tests/test_unified_entry.py
index 015e2778..47831cdc 100644
--- a/tests/test_unified_entry.py
+++ b/tests/test_unified_entry.py
@@ -360,7 +360,8 @@ def fake_browser(monkeypatch, tmp_path):
state = {"contexts": ["daily"], "running": True, "opened": [], "launches": 0, "launch_delay": 0.0,
"watched": False}
- def fake_launch(url):
+ def fake_launch(url, *, headless=True):
+ browser.update_state(headless=headless)
state["launches"] += 1
time.sleep(state["launch_delay"])
state["running"] = True
@@ -537,7 +538,7 @@ def test_opencli_rebinds_once_when_the_owned_extension_disconnects(fake_browser,
from agent_reach.backends.opencli import opencli_call
from agent_reach.runtime import browser
browser.setup()
- monkeypatch.setattr(browser, "watcher_running", lambda: True)
+ monkeypatch.setattr(browser, "watcher_running", lambda: fake_browser["watched"])
fake_browser["contexts"].remove("dedicated")
command = Mock(return_value="[]")
monkeypatch.setattr("agent_reach.runtime.run.run_cmd", command)
@@ -581,3 +582,13 @@ def test_opencli_errors_map_to_unified_codes(yaml_text, code):
from agent_reach.backends.opencli import _opencli_error
assert _opencli_error(yaml_text, "").code == code
+
+
+def test_next_query_returns_from_visible_login_to_headless(fake_browser):
+ from agent_reach.runtime import browser
+ browser.setup()
+ context=browser.bound_context()
+ browser.update_state(headless=False)
+ browser.ensure_running()
+ assert browser._load_state()['headless'] is True
+ assert browser.bound_context()==context and fake_browser['launches']==2