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(cli): make P0 configuration paths explicit

Pnanta67ee8b8c9cb
diff --git a/agent_reach/cli.py b/agent_reach/cli.py
index 3cd45f61..ead38582 100644
--- a/agent_reach/cli.py
+++ b/agent_reach/cli.py
@@ -87,7 +87,21 @@ def main():
p_conf.add_argument("value", nargs="*", help="The value(s) to set")
p_conf.add_argument("--from-browser", metavar="BROWSER",
choices=["chrome", "firefox", "edge", "brave", "opera"],
- help="Auto-extract ALL platform cookies from browser (chrome/firefox/edge/brave/opera)")
+ help="Extract cookies for one explicitly selected platform")
+ p_conf.add_argument(
+ "--platform",
+ choices=["twitter", "xiaohongshu", "bilibili", "xueqiu"],
+ help="Platform to import (required with --from-browser)",
+ )
+ p_conf.add_argument(
+ "--profile",
+ help="Exact browser profile; a missing profile fails instead of falling back",
+ )
+ p_conf.add_argument(
+ "--sync-legacy-twitter",
+ action="store_true",
+ help="With twitter-cookies, also write legacy xfetch/bird credential files",
+ )
# ── doctor ──
p_doctor = sub.add_parser("doctor", help="Check platform availability")
@@ -132,6 +146,26 @@ def main():
args = parser.parse_args()
+ if args.command == "configure" and args.from_browser:
+ if not args.platform:
+ p_conf.error("--platform is required with --from-browser")
+ manual_keys = {
+ "twitter": "twitter-cookies",
+ "xiaohongshu": "xhs-cookies",
+ }
+ if args.platform in manual_keys:
+ p_conf.error(
+ f"{args.platform} requires Cookie-Editor export; use "
+ f"`agent-reach configure {manual_keys[args.platform]} ...`"
+ )
+ if args.sync_legacy_twitter:
+ p_conf.error("--sync-legacy-twitter is only valid with twitter-cookies")
+ elif args.command == "configure":
+ if args.profile or args.platform:
+ p_conf.error("--platform/--profile require --from-browser")
+ if args.sync_legacy_twitter and args.key != "twitter-cookies":
+ p_conf.error("--sync-legacy-twitter is only valid with twitter-cookies")
+
# Suppress loguru noise unless --verbose
_configure_logging(getattr(args, "verbose", False))
@@ -207,7 +241,7 @@ def _cmd_install(args):
# linkedin: manual setup, no auto-install
}
OPENCLI_ONLY_CHANNELS = {"opencli", "facebook", "instagram"}
- COOKIE_CHANNELS = {"twitter", "xueqiu", "bilibili"}
+ COOKIE_CHANNELS = {"twitter", "xueqiu", "bilibili", "xiaohongshu"}
requested_channels = set()
if args.channels:
@@ -280,34 +314,31 @@ def _cmd_install(args):
print()
print(f"[dry-run] Would install optional channels: {', '.join(sorted(requested_channels))}")
- # ── Auto-import cookies (only if cookie-needing channels are requested) ──
+ # ── Cookie setup (explicit only — install never reads browser credentials) ──
needs_cookies = bool(requested_channels & COOKIE_CHANNELS)
- if env == "local" and needs_cookies and not safe_mode and not dry_run:
+ if env == "local" and needs_cookies and not dry_run:
print()
- print("Importing cookies from browser...")
- print(" (macOS may ask for your login password to access the Keychain — this is normal,")
- print(" it only happens once during install. Enter your password or click 'Allow'.)")
- try:
- from agent_reach.cookie_extract import configure_from_browser
- results = configure_from_browser("chrome", config)
- found = False
- for platform, success, message in results:
- if success:
- print(f" ✅ {platform}: {message}")
- found = True
- if not found:
- results = configure_from_browser("firefox", config)
- for platform, success, message in results:
- if success:
- print(f" ✅ {platform}: {message}")
- found = True
- if not found:
- print(" -- No cookies found (normal if you haven't logged into these sites)")
- except Exception:
- print(" -- Could not read browser cookies (browser might be open or password was denied)")
+ print("Cookie login is never read automatically.")
+ print("Run only the platform command you intend to authorize:")
+ for channel in sorted(requested_channels & COOKIE_CHANNELS):
+ if channel == "twitter":
+ print(
+ " agent-reach configure twitter-cookies "
+ "'<Cookie-Editor Header String>'"
+ )
+ elif channel == "xiaohongshu":
+ print(
+ " agent-reach configure xhs-cookies "
+ "'<Cookie-Editor JSON or Header String>'"
+ )
+ else:
+ print(
+ " agent-reach configure --from-browser chrome "
+ f"--platform {channel}"
+ )
elif env == "local" and needs_cookies and dry_run:
print()
- print("[dry-run] Would try to import cookies from Chrome/Firefox")
+ print("[dry-run] Cookie import remains explicit; install will not read a browser")
# Environment-specific advice
if env == "server":
@@ -634,18 +665,19 @@ def _install_system_deps():
# ── yt-dlp JS runtime config (YouTube requires external JS runtime) ──
if shutil.which("node"):
- ytdlp_config_dir = os.path.expanduser("~/.config/yt-dlp")
- ytdlp_config = os.path.join(ytdlp_config_dir, "config")
+ from agent_reach.utils.paths import get_ytdlp_config_path
+
+ ytdlp_config = get_ytdlp_config_path()
needs_config = True
- if os.path.exists(ytdlp_config):
- with open(ytdlp_config, "r") as f:
+ if ytdlp_config.exists():
+ with ytdlp_config.open("r", encoding="utf-8") as f:
if "--js-runtimes" in f.read():
needs_config = False
print(" ✅ yt-dlp JS runtime already configured")
if needs_config:
try:
- os.makedirs(ytdlp_config_dir, exist_ok=True)
- with open(ytdlp_config, "a") as f:
+ ytdlp_config.parent.mkdir(parents=True, exist_ok=True)
+ with ytdlp_config.open("a", encoding="utf-8") as f:
f.write("--js-runtimes node\n")
print(" ✅ yt-dlp configured to use Node.js as JS runtime (YouTube)")
except Exception:
@@ -739,7 +771,7 @@ def _install_xhs_deps():
print(" 1. 下载 binary:https://github.com/xpzouying/xiaohongshu-mcp/releases")
print(" (建议放到 ~/.agent-reach/tools/ 下)")
print(" 2. 启动服务(首次运行会下载约 150MB 浏览器,请等待完成)")
- print(" 3. 扫码登录后接入:mcporter config add xiaohongshu http://localhost:18060/mcp")
+ print(" 3. 扫码登录后接入:mcporter config add xiaohongshu http://localhost:18060/mcp --scope home")
print(" 4. 验证:agent-reach doctor")
return
@@ -947,14 +979,22 @@ def _install_mcporter():
)
if "exa" not in r.stdout:
subprocess.run(
- ["mcporter", "config", "add", "exa", "https://mcp.exa.ai/mcp"],
+ [
+ "mcporter",
+ "config",
+ "add",
+ "exa",
+ "https://mcp.exa.ai/mcp",
+ "--scope",
+ "home",
+ ],
capture_output=True, encoding="utf-8", errors="replace", timeout=10,
)
print(" ✅ Exa search configured (free, no API key needed)")
else:
print(" ✅ Exa search already configured")
except Exception:
- print(" [!] Could not configure Exa. Run manually: mcporter config add exa https://mcp.exa.ai/mcp")
+ print(" [!] Could not configure Exa. Run manually: mcporter config add exa https://mcp.exa.ai/mcp --scope home")
# NOTE: xhs-cli is now optional, installed via --channels=xiaohongshu
@@ -967,11 +1007,11 @@ def _install_mcporter_safe():
if shutil.which("mcporter"):
print(" ✅ mcporter already installed")
- print(" To configure Exa search: mcporter config add exa https://mcp.exa.ai/mcp")
+ print(" To configure Exa search: mcporter config add exa https://mcp.exa.ai/mcp --scope home")
else:
print(" -- mcporter not installed")
print(" To install: npm install -g mcporter")
- print(" Then configure Exa: mcporter config add exa https://mcp.exa.ai/mcp")
+ print(" Then configure Exa: mcporter config add exa https://mcp.exa.ai/mcp --scope home")
def _detect_environment():
@@ -1028,18 +1068,34 @@ def _cmd_configure(args):
from agent_reach.cookie_extract import configure_from_browser
browser = args.from_browser
- print(f"Extracting cookies from {browser}...")
+ platform = "xhs" if args.platform == "xiaohongshu" else args.platform
+ print(f"Extracting {args.platform} cookies from {browser}...")
print()
- results = configure_from_browser(browser, config)
+ results = configure_from_browser(
+ browser,
+ config,
+ platform=platform,
+ profile=args.profile,
+ )
found_any = False
- for platform, success, message in results:
+ for result in results:
+ if hasattr(result, "platform"):
+ result_platform = result.platform
+ success = result.success
+ message = result.message
+ targets = getattr(result, "targets", ())
+ else:
+ result_platform, success, message = result
+ targets = ()
if success:
- print(f" ✅ {platform}: {message}")
+ print(f" ✅ {result_platform}: {message}")
+ if targets:
+ print(f" 写入:{', '.join(targets)}")
found_any = True
else:
- print(f" -- {platform}: {message}")
+ print(f" -- {result_platform}: {message}")
print()
if found_any:
@@ -1051,7 +1107,10 @@ def _cmd_configure(args):
# ── Manual configure ──
if not args.key:
print("Usage: agent-reach configure <key> <value>")
- print(" or: agent-reach configure --from-browser chrome")
+ print(
+ " or: agent-reach configure --from-browser chrome "
+ "--platform twitter"
+ )
return
value = " ".join(args.value) if args.value else ""
@@ -1079,8 +1138,20 @@ def _cmd_configure(args):
config.set("twitter_auth_token", auth_token)
config.set("twitter_ct0", ct0)
- # Sync credentials to twitter-cli env
print("✅ Twitter cookies configured!")
+ if getattr(args, "sync_legacy_twitter", False):
+ from agent_reach.cookie_extract import (
+ _sync_bird_env,
+ _sync_xfetch_session,
+ )
+
+ _sync_xfetch_session(auth_token, ct0)
+ _sync_bird_env(auth_token, ct0)
+ print(
+ " Legacy copies written to "
+ "~/.config/xfetch/session.json and "
+ "~/.config/bird/credentials.env"
+ )
print("Testing Twitter access...", end=" ")
try:
@@ -1184,6 +1255,7 @@ def _configure_xhs_cookies(value):
Format: JSON array of {name, value, domain, path, expires, httpOnly, secure, sameSite}.
"""
import json
+ import os
import shutil
import subprocess
@@ -1259,7 +1331,6 @@ def _configure_xhs_cookies(value):
# Create with 0o600 atomically so the file is never world-readable
# between open() and a follow-up chmod() (same pattern Config.save()
# uses in config.py).
- import os
import stat
from agent_reach.utils.paths import make_private_dir
@@ -1318,6 +1389,7 @@ def _configure_xhs_cookies(value):
cookie_path_in_container = "/app/cookies.json"
# Write cookies into the container
+ tmp_path = None
try:
# Write to temp file then docker cp
import tempfile
@@ -1329,7 +1401,6 @@ def _configure_xhs_cookies(value):
[docker, "cp", tmp_path, f"{container_name}:{cookie_path_in_container}"],
capture_output=True, encoding="utf-8", timeout=10,
)
- os.unlink(tmp_path)
if result.returncode != 0:
print(f"[X] Failed to copy cookies: {result.stderr}")
@@ -1350,6 +1421,14 @@ def _configure_xhs_cookies(value):
except Exception as e:
print(f"[X] Failed to write cookies: {e}")
return
+ finally:
+ if tmp_path:
+ try:
+ os.unlink(tmp_path)
+ except FileNotFoundError:
+ pass
+ except OSError as e:
+ print(f" [!] Could not remove temporary cookie file: {e}")
# Verify login status via mcporter
mcporter = shutil.which("mcporter")
@@ -1489,9 +1568,6 @@ def _cmd_doctor(args=None):
rprint(format_report(results))
- # Auto-install skill if not already present (fixes #154)
- _install_skill(force=False)
-
def _cmd_setup():
from agent_reach.config import Config
@@ -1512,7 +1588,7 @@ def _cmd_setup():
if not shutil.which("mcporter"):
print(" 当前状态: -- mcporter 未安装")
print(" 安装:npm install -g mcporter")
- print(" 然后:mcporter config add exa https://mcp.exa.ai/mcp")
+ print(" 然后:mcporter config add exa https://mcp.exa.ai/mcp --scope home")
print()
else:
try:
@@ -1526,17 +1602,25 @@ def _cmd_setup():
setup_now = input(" 现在自动配置 Exa 吗?[Y/n]: ").strip().lower()
if setup_now in ("", "y", "yes"):
add_r = subprocess.run(
- ["mcporter", "config", "add", "exa", "https://mcp.exa.ai/mcp"],
+ [
+ "mcporter",
+ "config",
+ "add",
+ "exa",
+ "https://mcp.exa.ai/mcp",
+ "--scope",
+ "home",
+ ],
capture_output=True, encoding="utf-8", errors="replace", timeout=10,
)
if add_r.returncode == 0:
print(" ✅ Exa 已配置")
else:
print(" [!] 自动配置失败,请手动执行:")
- print(" mcporter config add exa https://mcp.exa.ai/mcp")
+ print(" mcporter config add exa https://mcp.exa.ai/mcp --scope home")
except Exception:
print(" [!] 无法检查 Exa 配置,请手动执行:")
- print(" mcporter config add exa https://mcp.exa.ai/mcp")
+ print(" mcporter config add exa https://mcp.exa.ai/mcp --scope home")
print()
# Step 2: GitHub token
diff --git a/agent_reach/guides/setup-exa.md b/agent_reach/guides/setup-exa.md
index 2d027edc..0dfdc2d5 100644
--- a/agent_reach/guides/setup-exa.md
+++ b/agent_reach/guides/setup-exa.md
@@ -17,7 +17,7 @@ npm install -g mcporter
### 2. 注册 Exa MCP
```bash
-mcporter config add exa https://mcp.exa.ai/mcp
+mcporter config add exa https://mcp.exa.ai/mcp --scope home
```
### 3. 验证
diff --git a/agent_reach/guides/setup-xiaohongshu.md b/agent_reach/guides/setup-xiaohongshu.md
index 18eb8f13..f855da7f 100644
--- a/agent_reach/guides/setup-xiaohongshu.md
+++ b/agent_reach/guides/setup-xiaohongshu.md
@@ -79,7 +79,7 @@ docker run -d \
-p 18060:18060 \
xpzouying/xiaohongshu-mcp
-mcporter config add xiaohongshu http://localhost:18060/mcp
+mcporter config add xiaohongshu http://localhost:18060/mcp --scope home
```
xhs-cli 是当前推荐方案,不需要 Docker,安装更简单。
diff --git a/docs/install.md b/docs/install.md
index 4eff1447..7c57e82a 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -143,7 +143,7 @@ Some channels need credentials only the user can provide. Based on the doctor ou
> 3. 点击插件 → Export → Header String
> 4. 把导出的字符串发给 Agent
>
-> **本地电脑用户**也可以用 `agent-reach configure --from-browser chrome` 一键自动提取(支持 Twitter + 小红书 + 雪球)。OpenCLI 平台(Reddit、小红书桌面后端、Facebook、Instagram)优先复用 Chrome 登录态,不需要把 Cookie 发给 Agent。
+> Twitter 与小红书只接受用户通过 Cookie-Editor 明确导出的内容,不会自动读取浏览器 Cookie。雪球、Bilibili 可按平台显式导入,例如 `agent-reach configure --from-browser chrome --platform xueqiu`;命令不会扫描或保存其他平台。OpenCLI 平台(Reddit、小红书桌面后端、Facebook、Instagram)优先复用 Chrome 登录态,不需要把 Cookie 发给 Agent。
**Twitter search & posting:**
> "To unlock Twitter search, I need your Twitter cookies. Install the Cookie-Editor Chrome extension, go to x.com/twitter.com, click the extension → Export → Header String, and paste it to me."
@@ -195,7 +195,7 @@ agent-reach install --channels opencli
> 1. 从 https://github.com/xpzouying/xiaohongshu-mcp/releases 下载对应平台 binary 到 `~/.agent-reach/tools/`
> 2. 启动服务(首次运行会自动下载约 150MB 无头浏览器,耐心等完成)
> 3. 让用户扫码登录(agent 调 `get_login_qrcode` 工具取二维码)
-> 4. 接入:`mcporter config add xiaohongshu http://localhost:18060/mcp`
+> 4. 接入:`mcporter config add xiaohongshu http://localhost:18060/mcp --scope home`
> 5. 调用时务必带 `--timeout 120000`
>
> **存量用户(xhs-cli):** 已装好的 xhs-cli 继续作为备选后端工作(上游 2026-03 起停更,不推荐新装)。`xhs login` 自动提取浏览器 Cookie;失败时用 Cookie-Editor 导出后:
@@ -229,10 +229,10 @@ agent-reach install --channels facebook,instagram
> "雪球需要登录后的 Cookie。请先在 Chrome 里登录 xueqiu.com,然后运行:"
```bash
-agent-reach configure --from-browser chrome
+agent-reach configure --from-browser chrome --platform xueqiu
```
-> Cookie 会随其他平台一起自动提取。
+> 只会读取并保存雪球需要的最小 Cookie;不会顺带读取其他平台。
**小宇宙播客 / Xiaoyuzhou Podcast (Groq Whisper):**
> "小宇宙播客转文字已默认安装,只需要一个免费的 Groq API Key。"
@@ -297,7 +297,7 @@ pip install linkedin-scraper-mcp
> **登录后启动 MCP 服务:**
> ```bash
> linkedin-scraper-mcp --transport streamable-http --port 8001
-> mcporter config add linkedin http://localhost:8001/mcp
+> mcporter config add linkedin http://localhost:8001/mcp --scope home
> ```
>
> 详见 https://github.com/stickerdaniel/linkedin-mcp-server
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index eb70f50c..0d9817ff 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -9,7 +9,7 @@
**解决方案:** 在 Chrome 里登录 xueqiu.com,然后运行:
```bash
-agent-reach configure --from-browser chrome
+agent-reach configure --from-browser chrome --platform xueqiu
```
再次运行 `agent-reach doctor` 确认恢复 ✅。Cookie 过期后重新运行即可。
diff --git a/tests/test_p0_cli.py b/tests/test_p0_cli.py
new file mode 100644
index 00000000..800db005
--- /dev/null
+++ b/tests/test_p0_cli.py
@@ -0,0 +1,362 @@
+# -*- coding: utf-8 -*-
+"""Regression tests for P0 CLI safety and configuration failures."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from argparse import Namespace
+from pathlib import Path
+
+import pytest
+
+import agent_reach.cli as cli
+
+
+class _MemoryConfig:
+ def __init__(self):
+ self.data = {}
+
+ def get(self, key, default=None):
+ return self.data.get(key, default)
+
+ def set(self, key, value):
+ self.data[key] = value
+
+
+def test_browser_cookie_import_requires_explicit_platform(monkeypatch):
+ """A bare --from-browser must fail before any browser credential access."""
+ import agent_reach.config as config_module
+ import agent_reach.cookie_extract as cookie_extract
+
+ monkeypatch.setattr(config_module, "Config", _MemoryConfig)
+ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)
+ monkeypatch.setattr(
+ cookie_extract,
+ "configure_from_browser",
+ lambda *_args, **_kwargs: pytest.fail("browser cookie reader must not run"),
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["agent-reach", "configure", "--from-browser", "chrome"],
+ )
+
+ with pytest.raises(SystemExit) as exc:
+ cli.main()
+
+ assert exc.value.code == 2
+
+
+def test_browser_cookie_import_passes_explicit_platform_and_profile(
+ monkeypatch, capsys
+):
+ """The CLI forwards an allowed minimal-cookie platform and exact profile."""
+ import agent_reach.config as config_module
+ import agent_reach.cookie_extract as cookie_extract
+
+ captured = {}
+
+ def fake_configure(browser, config, **kwargs):
+ captured.update(browser=browser, config=config, **kwargs)
+ return [("Twitter/X", True, "saved to config.yaml")]
+
+ monkeypatch.setattr(config_module, "Config", _MemoryConfig)
+ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)
+ monkeypatch.setattr(cookie_extract, "configure_from_browser", fake_configure)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "agent-reach",
+ "configure",
+ "--from-browser",
+ "chrome",
+ "--platform",
+ "xueqiu",
+ "--profile",
+ "Profile 2",
+ ],
+ )
+
+ cli.main()
+
+ assert captured["browser"] == "chrome"
+ assert captured["platform"] == "xueqiu"
+ assert captured["profile"] == "Profile 2"
+ assert "Cookies configured" in capsys.readouterr().out
+
+
+ ("platform", "manual_key"),
+ [("twitter", "twitter-cookies"), ("xiaohongshu", "xhs-cookies")],
+)
+def test_browser_cookie_import_rejects_cookie_editor_only_platforms(
+ monkeypatch, capsys, platform, manual_key
+):
+ """Twitter/XHS browser stores are never opened by the automatic importer."""
+ import agent_reach.cookie_extract as cookie_extract
+
+ monkeypatch.setattr(cli, "_configure_logging", lambda _verbose=False: None)
+ monkeypatch.setattr(
+ cookie_extract,
+ "configure_from_browser",
+ lambda *_args, **_kwargs: pytest.fail("browser cookie reader must not run"),
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "agent-reach",
+ "configure",
+ "--from-browser",
+ "chrome",
+ "--platform",
+ platform,
+ ],
+ )
+
+ with pytest.raises(SystemExit) as exc:
+ cli.main()
+
+ assert exc.value.code == 2
+ assert manual_key in capsys.readouterr().err
+
+
+def test_install_does_not_implicitly_read_browser_cookies(monkeypatch, tmp_path, capsys):
+ """Installing a cookie-backed channel prints an explicit command instead."""
+ import agent_reach.config as config_module
+ import agent_reach.cookie_extract as cookie_extract
+
+ monkeypatch.setattr(config_module, "Config", _MemoryConfig)
+ monkeypatch.setattr(
+ cli.os.path,
+ "expanduser",
+ lambda value: value.replace("~", str(tmp_path)),
+ )
+ monkeypatch.setattr(cli, "_install_system_deps", lambda: None)
+ monkeypatch.setattr(cli, "_install_mcporter", lambda: None)
+ monkeypatch.setattr(cli, "_install_twitter_deps", lambda: None)
+ monkeypatch.setattr(cli, "_install_skill", lambda: None)
+ monkeypatch.setattr(
+ "agent_reach.doctor.check_all",
+ lambda _config: {},
+ )
+ monkeypatch.setattr(
+ "agent_reach.doctor.format_report",
+ lambda _results: "report",
+ )
+ monkeypatch.setattr(
+ cookie_extract,
+ "configure_from_browser",
+ lambda *_args, **_kwargs: pytest.fail("install must not read browser cookies"),
+ )
+
+ cli._cmd_install(
+ Namespace(
+ env="local",
+ proxy="",
+ safe=False,
+ dry_run=False,
+ channels="twitter",
+ )
+ )
+
+ output = capsys.readouterr().out
+ assert "configure twitter-cookies" in output
+ assert "Importing cookies from browser" not in output
+
+
[email protected]("sync_legacy", [False, True])
+def test_manual_twitter_cookie_legacy_copies_are_opt_in(
+ monkeypatch, capsys, sync_legacy
+):
+ """The source-of-truth config is always written; legacy copies are optional."""
+ import shutil
+
+ import agent_reach.config as config_module
+ import agent_reach.cookie_extract as cookie_extract
+
+ calls = []
+ config = _MemoryConfig()
+ monkeypatch.setattr(config_module, "Config", lambda: config)
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ monkeypatch.setattr(
+ cookie_extract,
+ "_sync_xfetch_session",
+ lambda auth, ct0: calls.append(("xfetch", auth, ct0)),
+ )
+ monkeypatch.setattr(
+ cookie_extract,
+ "_sync_bird_env",
+ lambda auth, ct0: calls.append(("bird", auth, ct0)),
+ )
+
+ cli._cmd_configure(
+ Namespace(
+ from_browser=None,
+ key="twitter-cookies",
+ value=["auth-value", "ct0-value"],
+ sync_legacy_twitter=sync_legacy,
+ )
+ )
+
+ assert config.get("twitter_auth_token") == "auth-value"
+ assert config.get("twitter_ct0") == "ct0-value"
+ assert bool(calls) is sync_legacy
+ output = capsys.readouterr().out
+ assert ("Legacy copies written" in output) is sync_legacy
+
+
+def test_doctor_never_installs_or_updates_skill(monkeypatch, capsys):
+ """A diagnostic command is read-only and must not mutate agent instructions."""
+ import agent_reach.config as config_module
+
+ monkeypatch.setattr(config_module, "Config", _MemoryConfig)
+ monkeypatch.setattr("agent_reach.doctor.check_all", lambda _config: {})
+ monkeypatch.setattr("agent_reach.doctor.format_report", lambda _results: "report")
+ monkeypatch.setattr(
+ cli,
+ "_install_skill",
+ lambda *_args, **_kwargs: pytest.fail("doctor must not install skill"),
+ )
+
+ cli._cmd_doctor(Namespace(json=False))
+
+ assert "report" in capsys.readouterr().out
+
+
+def _docker_result(args, returncode=0, stdout="", stderr=""):
+ return subprocess.CompletedProcess(args, returncode, stdout, stderr)
+
+
+def test_xhs_docker_cookie_copy_succeeds_without_local_os_binding_error(
+ monkeypatch, capsys
+):
+ """The Docker branch must be able to unlink its temporary file."""
+ calls = []
+
+ def fake_which(name):
+ if name == "docker":
+ return "/usr/bin/docker"
+ return None
+
+ def fake_run(args, **_kwargs):
+ calls.append(args)
+ if args[1] == "ps":
+ return _docker_result(args, stdout="xiaohongshu-mcp\n")
+ if args[1:3] == ["exec", "xiaohongshu-mcp"]:
+ return _docker_result(args, stdout="/app/data/cookies.json\n")
+ return _docker_result(args)
+
+ monkeypatch.setattr("shutil.which", fake_which)
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ cli._configure_xhs_cookies("web_session=xhs_secret")
+
+ output = capsys.readouterr().out
+ assert "Cookies written to xiaohongshu-mcp:/app/data/cookies.json" in output
+ assert "cannot access local variable 'os'" not in output
+ assert any(call[1] == "cp" for call in calls)
+
+
+def test_xhs_docker_cookie_copy_always_removes_temporary_file(monkeypatch, capsys):
+ """Failed docker cp must not leave a plaintext cookie file behind."""
+ copied_from = []
+
+ def fake_which(name):
+ if name == "docker":
+ return "/usr/bin/docker"
+ return None
+
+ def fake_run(args, **_kwargs):
+ if args[1] == "ps":
+ return _docker_result(args, stdout="xiaohongshu-mcp\n")
+ if args[1:3] == ["exec", "xiaohongshu-mcp"]:
+ return _docker_result(args, stdout="/app/data/cookies.json\n")
+ if args[1] == "cp":
+ copied_from.append(args[2])
+ return _docker_result(args, returncode=1, stderr="copy failed")
+ return _docker_result(args)
+
+ monkeypatch.setattr("shutil.which", fake_which)
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ cli._configure_xhs_cookies("web_session=xhs_secret")
+
+ assert copied_from
+ assert not Path(copied_from[0]).exists()
+ assert "Failed to copy cookies: copy failed" in capsys.readouterr().out
+
+
+def test_system_install_uses_platform_specific_ytdlp_config(
+ monkeypatch, tmp_path
+):
+ """macOS installation writes the same config path that doctor reads."""
+ import shutil
+
+ import agent_reach.utils.paths as paths
+
+ monkeypatch.setattr(paths.sys, "platform", "darwin")
+ monkeypatch.setattr(paths.Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(
+ cli.os.path,
+ "expanduser",
+ lambda value: str(tmp_path / ".legacy-config")
+ if value == "~/.config/yt-dlp"
+ else value.replace("~", str(tmp_path)),
+ )
+ monkeypatch.setattr(
+ shutil,
+ "which",
+ lambda name: f"/usr/bin/{name}" if name in {"gh", "node", "npm"} else None,
+ )
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda args, **_kwargs: _docker_result(
+ args,
+ stdout="/tmp/npm-root\n" if args[1:3] == ["root", "-g"] else "",
+ ),
+ )
+
+ cli._install_system_deps()
+
+ config_path = (
+ tmp_path / "Library" / "Application Support" / "yt-dlp" / "config"
+ )
+ assert config_path.read_text(encoding="utf-8") == "--js-runtimes node\n"
+ assert not (tmp_path / ".legacy-config" / "config").exists()
+
+
+def test_mcporter_install_adds_exa_to_home_scope(monkeypatch):
+ """Installer config remains available across working directories."""
+ import shutil
+
+ calls = []
+
+ monkeypatch.setattr(
+ shutil,
+ "which",
+ lambda name: "/usr/bin/mcporter" if name == "mcporter" else None,
+ )
+
+ def fake_run(args, **_kwargs):
+ calls.append(args)
+ if args[:3] == ["mcporter", "config", "list"]:
+ return _docker_result(args, stdout='{"servers": []}')
+ return _docker_result(args)
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ cli._install_mcporter()
+
+ assert [
+ "mcporter",
+ "config",
+ "add",
+ "exa",
+ "https://mcp.exa.ai/mcp",
+ "--scope",
+ "home",
+ ] in calls