Skip to content

The agent that turns websites into APIs!

fix(windows): make file decoding and runtime launchers portable

kalil0321494d3d21a029
diff --git a/scripts/validation/windows-audit.md b/scripts/validation/windows-audit.md
new file mode 100644
index 0000000..d93a12a
--- /dev/null
+++ b/scripts/validation/windows-audit.md
@@ -0,0 +1,64 @@
+# Windows compatibility audit — issue #134
+
+Inspected on 2026-09-23 against local commit
+`dd2528546fffd9ef0a00d545f5fe93ac88055ca0` plus the working-tree fixes.
+
+## Fixed
+
+- Prompt templates and included partials now explicitly use UTF-8. Reading the
+ Python partial as GBK reproduced the reported `0x94` error at byte 129 exactly.
+- Configuration, history, messages, metadata and the Cursor dependency stamp
+ have explicit UTF-8 encodings. Invalid UTF-8 configuration/history uses the
+ existing corrupt-file recovery path. Previously generated JSON remains
+ compatible because the writers escape non-ASCII characters by default.
+- HAR readers use UTF-8 with optional BOM support. Previously a decode error
+ could silently hide the domain or entry count.
+- Node/npm diagnostic capture uses UTF-8 with replacement of invalid diagnostic
+ bytes. Other external-tool diagnostics retain the native locale with tolerant
+ decoding. Python client capture explicitly configures both the child pipes
+ and the parent decoder for UTF-8, preserving Unicode stdout/stderr in JSON mode.
+- Chrome profile discovery uses Windows LOCALAPPDATA and Linux Chrome/XDG
+ configuration locations in addition to the existing macOS path. This fixes
+ false "profile not found" fallback; it does not import profile cookies.
+- Windows agent-browser probes and generated-client runners use the executable
+ resolved by `shutil.which`, including `.cmd` launchers. No explicit shell was
+ added. OpenCode and Cursor startup already resolved npx/npm this way.
+
+## Verification
+
+`tests/test_windows_compatibility.py` covers GBK and CP1252 text-file defaults,
+all ten code-generation languages, recursive partials, Unicode persistence,
+HAR files with/without BOM, corrupt-file recovery, platform-specific Chrome
+directories, and `.cmd` resolution in interactive and JSON execution paths.
+
+Two checks run actual subprocesses: UTF-8 diagnostics under a simulated GBK
+parent, and `run --json` executing a real Python client in a fresh venv beneath
+a path containing spaces and Chinese characters. The latter checks exact
+Chinese, accented, em-dash and emoji output on stdout and stderr. It requires
+no network, package installation or model credentials.
+
+Local results: 1,004 passed, one Windows-only native `.cmd` probe skipped, five
+coroutine warnings. The macOS FSEvents backend crashed during the ordinary full
+suite; the successful full run substituted watchdog's PollingObserver only in
+the test harness, with no production observer changes. Application state was
+isolated by patching Path.home into a temporary directory, and uv used no-sync
+mode plus a temporary cache. Ruff and mypy passed on application/test code,
+excluding pre-existing local generated clients in `src/reverse_api/scripts`.
+
+The existing CI matrix will run these tests on Windows/Python 3.11–3.13 when the
+changes are pushed. No native Windows run or live model generation was performed
+as part of this local audit.
+
+## Remaining verification boundaries
+
+- Chrome launch, capture finalization and Ctrl+C need a native Windows run.
+- Managed OpenCode shutdown terminates its tracked launcher; descendant cleanup
+ across npx/cmd/Node needs native verification. This audit did not change it.
+- Prompt shell quoting already documents unsupported Windows paths containing
+ dollar signs/backticks. cmd.exe and PowerShell have different expansion rules;
+ the `.cmd` resolution fix is not a general shell-escaping guarantee.
+- Non-Python client output retains the native decoder; replacing invalid bytes
+ avoids crashes but cannot guarantee lossless output from arbitrary toolchains.
+
+References: [Python subprocess behavior](https://docs.python.org/3/library/subprocess.html)
+and [Chromium user-data locations](https://chromium.googlesource.com/chromium/src/+/main/docs/user_data_dir.md).
diff --git a/src/reverse_api/agent_browser.py b/src/reverse_api/agent_browser.py
index 31537d6..2753fe7 100644
--- a/src/reverse_api/agent_browser.py
+++ b/src/reverse_api/agent_browser.py
@@ -13,6 +13,7 @@ import os
import shlex
import shutil
import subprocess
+import sys
from dataclasses import dataclass
from typing import Any
@@ -95,11 +96,17 @@ def agent_browser_extra_notes() -> str:
def _probe_help_argv(argv_without_help: list[str]) -> str | None:
+ argv = [*argv_without_help, "--help"]
+ if sys.platform == "win32":
+ # CreateProcess does not search PATHEXT for npm's .cmd launchers.
+ argv[0] = shutil.which(argv[0]) or argv[0]
try:
proc = subprocess.run(
- [*argv_without_help, "--help"],
+ argv,
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
timeout=240,
check=False,
)
@@ -228,6 +235,8 @@ def ensure_agent_browser_runtime() -> AgentBrowserSetup:
[npm, "install", "-g", "--yes", pkg],
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
timeout=600,
check=False,
env={**os.environ, "CI": "1"},
diff --git a/src/reverse_api/browser.py b/src/reverse_api/browser.py
index 7b16182..7df1d8e 100644
--- a/src/reverse_api/browser.py
+++ b/src/reverse_api/browser.py
@@ -2,6 +2,7 @@
import io
import json
+import os
import random
import signal
import sys
@@ -164,14 +165,18 @@ console.log('Stealth mode activated');
"""
-# Default Chrome profile path on macOS
-CHROME_USER_DATA_DIR = Path.home() / "Library/Application Support/Google/Chrome"
-
-
def get_chrome_profile_dir() -> Path | None:
- """Get Chrome user data directory if it exists."""
- if CHROME_USER_DATA_DIR.exists():
- return CHROME_USER_DATA_DIR
+ """Get Chrome's platform-specific user data directory if it exists."""
+ if sys.platform == "win32":
+ root = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData/Local")
+ profile = root / "Google/Chrome/User Data"
+ elif sys.platform == "darwin":
+ profile = Path.home() / "Library/Application Support/Google/Chrome"
+ else:
+ root = Path(os.environ.get("CHROME_CONFIG_HOME") or os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
+ profile = root / "google-chrome"
+ if profile.is_dir():
+ return profile
return None
@@ -215,7 +220,7 @@ class ManualBrowser:
"end_time": end_time,
"har_file": str(self.har_path),
}
- with open(self.metadata_path, "w") as f:
+ with open(self.metadata_path, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2)
def _handle_signal(self, signum: int, frame: FrameType | None) -> None:
@@ -508,4 +513,3 @@ class ManualBrowser:
console.print(" [dim]metadata synced[/dim]")
return self.har_path
-
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.py
index 3191639..93dc46d 100644
--- a/src/reverse_api/cli.py
+++ b/src/reverse_api/cli.py
@@ -492,7 +492,7 @@ def _build_dry_run_payload(
else:
try:
ver = subprocess.run(
- [node, "--version"], capture_output=True, text=True, timeout=5
+ [node, "--version"], capture_output=True, text=True, errors="replace", timeout=5
).stdout.strip()
checks.append({"name": "node", "status": "ok", "message": ver})
except Exception as e:
@@ -2832,7 +2832,7 @@ def show_run(run_id: str | None, as_json: bool) -> None:
recording = har_dir / "recording.har"
if recording.exists():
try:
- har_data = json.loads(recording.read_text())
+ har_data = json.loads(recording.read_text(encoding="utf-8-sig"))
har_entries = len(har_data.get("log", {}).get("entries", []))
except Exception:
pass
@@ -2921,8 +2921,11 @@ def _run_non_python_script(script: Path, script_args: tuple[str, ...]) -> None:
steps, tool = build_script_commands(script, script_args)
except ValueError as e:
raise click.ClickException(str(e)) from e
- if shutil.which(tool) is None:
+ executable = shutil.which(tool)
+ if executable is None:
raise click.ClickException(f"cannot run {script.name}: '{tool}' is missing from PATH — install it and retry")
+ if sys.platform == "win32":
+ steps[0][0] = executable
returncode = 0
for cmd in steps:
returncode = subprocess.run(cmd, cwd=str(script.parent)).returncode
@@ -3014,7 +3017,8 @@ def _run_script_machine_payload(
error=str(e),
error_kind_hint="misuse",
)
- if shutil.which(tool) is None:
+ executable = shutil.which(tool)
+ if executable is None:
return _build_run_payload(
identifier=identifier,
run_id=run_id,
@@ -3024,10 +3028,12 @@ def _run_script_machine_payload(
error=f"cannot run {script.name}: '{tool}' is missing from PATH — install it and retry",
error_kind_hint="config_invalid",
)
+ if sys.platform == "win32":
+ steps[0][0] = executable
result = None
for cmd in steps:
emit_event("process_started", run_id=run_id, script_path=str(script))
- result = subprocess.run(cmd, cwd=str(script.parent), capture_output=True, text=True)
+ result = subprocess.run(cmd, cwd=str(script.parent), capture_output=True, text=True, errors="replace")
if result.returncode != 0:
break
assert result is not None, "build_script_commands returned no execution steps"
@@ -3051,19 +3057,22 @@ def _run_script_machine_payload(
if not venv_dir.exists():
emit_event("venv_setup_started", run_id=run_id, path=str(venv_dir))
- subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True, capture_output=True, text=True)
- subprocess.run([str(venv_pip), "install", "-q", "requests"], check=True, capture_output=True, text=True)
+ subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True, capture_output=True, text=True, errors="replace")
+ subprocess.run([str(venv_pip), "install", "-q", "requests"], check=True, capture_output=True, text=True, errors="replace")
emit_event("venv_setup_completed", run_id=run_id, path=str(venv_dir))
requirements = script.parent / "requirements.txt"
if requirements.exists():
emit_event("requirements_install_started", run_id=run_id, path=str(requirements))
- subprocess.run([str(venv_pip), "install", "-q", "-r", str(requirements)], check=True, capture_output=True, text=True)
+ subprocess.run([str(venv_pip), "install", "-q", "-r", str(requirements)], check=True, capture_output=True, text=True, errors="replace")
emit_event("requirements_install_completed", run_id=run_id, path=str(requirements))
cmd = [str(venv_python), str(script), *script_args]
emit_event("process_started", run_id=run_id, script_path=str(script))
- result = subprocess.run(cmd, capture_output=True, text=True)
+ result = subprocess.run(
+ cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
+ )
stderr = result.stderr or ""
if result.returncode != 0 and "ModuleNotFoundError: No module named" in stderr:
@@ -3072,10 +3081,13 @@ def _run_script_machine_payload(
emit_event("dependency_missing", run_id=run_id, package=missing)
if auto_install:
emit_event("dependency_install_started", run_id=run_id, package=missing)
- subprocess.run([str(venv_pip), "install", "-q", missing], check=True, capture_output=True, text=True)
+ subprocess.run([str(venv_pip), "install", "-q", missing], check=True, capture_output=True, text=True, errors="replace")
emit_event("dependency_install_completed", run_id=run_id, package=missing)
emit_event("process_retried", run_id=run_id, script_path=str(script))
- result = subprocess.run(cmd, capture_output=True, text=True)
+ result = subprocess.run(
+ cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
+ )
else:
return _build_run_payload(
identifier=identifier,
@@ -3324,7 +3336,10 @@ def run_script(
# Execute with real-time stdout, capture stderr for import error detection
cmd = [python_path, str(script), *script_args]
- result = subprocess.run(cmd, stderr=subprocess.PIPE, text=True)
+ result = subprocess.run(
+ cmd, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace",
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
+ )
# Print stderr so the user sees it, then check for missing imports
if result.stderr:
diff --git a/src/reverse_api/config.py b/src/reverse_api/config.py
index 18061ef..efc216a 100644
--- a/src/reverse_api/config.py
+++ b/src/reverse_api/config.py
@@ -46,7 +46,7 @@ class ConfigManager:
"""Load configuration from disk."""
if self.config_path.exists():
try:
- with open(self.config_path) as f:
+ with open(self.config_path, encoding="utf-8") as f:
user_config = json.load(f)
# Backward compatibility: migrate old config keys
@@ -61,14 +61,14 @@ class ConfigManager:
# Only keep valid keys
valid_config = {k: v for k, v in user_config.items() if k in self.config}
self.config.update(valid_config)
- except (json.JSONDecodeError, OSError):
+ except (json.JSONDecodeError, UnicodeError, OSError):
# Fallback to defaults if file is corrupted
pass
def save(self) -> None:
"""Save configuration to disk."""
self.config_path.parent.mkdir(parents=True, exist_ok=True)
- with open(self.config_path, "w") as f:
+ with open(self.config_path, "w", encoding="utf-8") as f:
json.dump(self.config, f, indent=4)
def get(self, key: str, default: Any = None) -> Any:
diff --git a/src/reverse_api/cursor_engineer.py b/src/reverse_api/cursor_engineer.py
index d6a43ed..a04b3f3 100644
--- a/src/reverse_api/cursor_engineer.py
+++ b/src/reverse_api/cursor_engineer.py
@@ -39,6 +39,8 @@ def _cursor_node_version_error() -> str | None:
timeout=10,
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
)
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
return f"failed to check Node.js version (Cursor SDK requires Node.js 22.13+): {e}"
@@ -64,7 +66,7 @@ def _ensure_cursor_bridge_deps() -> str | None:
return f"cursor bridge package-lock.json unavailable: {e}"
if _SDK_MARKER.is_dir():
try:
- if _BRIDGE_INSTALL_STAMP.read_text().strip() == lock_digest:
+ if _BRIDGE_INSTALL_STAMP.read_text(encoding="utf-8").strip() == lock_digest:
return None
except OSError:
pass
@@ -79,6 +81,8 @@ def _ensure_cursor_bridge_deps() -> str | None:
timeout=600,
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
)
except subprocess.CalledProcessError as e:
tail = (e.stderr or e.stdout or "")[-2000:]
@@ -88,7 +92,7 @@ def _ensure_cursor_bridge_deps() -> str | None:
if not _SDK_MARKER.is_dir():
return "@cursor/sdk did not install under cursor_bridge/node_modules"
try:
- _BRIDGE_INSTALL_STAMP.write_text(f"{_bridge_lock_digest()}\n")
+ _BRIDGE_INSTALL_STAMP.write_text(f"{_bridge_lock_digest()}\n", encoding="utf-8")
except OSError as e:
return f"failed to record cursor bridge dependency state: {e}"
return None
diff --git a/src/reverse_api/messages.py b/src/reverse_api/messages.py
index 763fc91..696d36e 100644
--- a/src/reverse_api/messages.py
+++ b/src/reverse_api/messages.py
@@ -27,7 +27,7 @@ class MessageStore:
"content": content,
**kwargs,
}
- with open(self.messages_path, "a") as f:
+ with open(self.messages_path, "a", encoding="utf-8") as f:
f.write(json.dumps(message) + "\n")
def save_prompt(self, prompt: str) -> None:
@@ -66,7 +66,7 @@ class MessageStore:
if not self.messages_path.exists():
return []
messages = []
- with open(self.messages_path) as f:
+ with open(self.messages_path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
diff --git a/src/reverse_api/prompts/__init__.py b/src/reverse_api/prompts/__init__.py
index f48a698..3336cec 100644
--- a/src/reverse_api/prompts/__init__.py
+++ b/src/reverse_api/prompts/__init__.py
@@ -25,7 +25,7 @@ def _resolve_includes(text: str) -> str:
end = text.index(_INCLUDE_SUFFIX, start + len(_INCLUDE_PREFIX))
partial_name = text[start + len(_INCLUDE_PREFIX) : end]
partial_path = _PARTIALS_DIR / f"{partial_name}.md"
- partial_text = partial_path.read_text()
+ partial_text = partial_path.read_text(encoding="utf-8")
partial_text = _resolve_includes(partial_text)
text = text[:start] + partial_text + text[end + 1 :]
return text
@@ -43,7 +43,7 @@ def load(template_name: str, **kwargs: str) -> str:
The fully rendered prompt string.
"""
path = _PROMPTS_DIR / f"{template_name}.md"
- text = path.read_text()
+ text = path.read_text(encoding="utf-8")
text = _resolve_includes(text)
if kwargs:
text = text.format_map(kwargs)
diff --git a/src/reverse_api/session.py b/src/reverse_api/session.py
index ba07dae..f0c5828 100644
--- a/src/reverse_api/session.py
+++ b/src/reverse_api/session.py
@@ -17,16 +17,16 @@ class SessionManager:
"""Load history from disk."""
if self.history_path.exists():
try:
- with open(self.history_path) as f:
+ with open(self.history_path, encoding="utf-8") as f:
self.history = json.load(f)
- except (json.JSONDecodeError, OSError):
+ except (json.JSONDecodeError, UnicodeError, OSError):
# Fallback to empty history if file is corrupted
self.history = []
def save(self) -> None:
"""Save history to disk."""
self.history_path.parent.mkdir(parents=True, exist_ok=True)
- with open(self.history_path, "w") as f:
+ with open(self.history_path, "w", encoding="utf-8") as f:
json.dump(self.history, f, indent=4)
def add_run(self, run_id: str, prompt: str, **kwargs: Any) -> None:
diff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.py
index 813b479..00b3b9a 100644
--- a/src/reverse_api/utils.py
+++ b/src/reverse_api/utils.py
@@ -864,7 +864,7 @@ def extract_domain_from_har(har_path: Path) -> str | None:
try:
import json
- with open(har_path) as f:
+ with open(har_path, encoding="utf-8-sig") as f:
har_data = json.load(f)
entries = har_data.get("log", {}).get("entries", [])
diff --git a/tests/test_agent_browser.py b/tests/test_agent_browser.py
index 390f41d..d7c25f7 100644
--- a/tests/test_agent_browser.py
+++ b/tests/test_agent_browser.py
@@ -43,7 +43,8 @@ def test_global_binary_short_circuits_npm():
assert agent_browser.agent_browser_shell_invoker() == "agent-browser"
run.assert_called_once()
argv = run.call_args[0][0]
- assert argv == ["agent-browser", "--help"]
+ executable = "/fake/agent-browser" if agent_browser.sys.platform == "win32" else "agent-browser"
+ assert argv == [executable, "--help"]
def test_global_help_failure():
@@ -196,4 +197,3 @@ def test_check_missing_node_is_error():
st = agent_browser.check_agent_browser_runtime()
assert not st.ok
assert st.error and "node" in st.error.lower()
-
diff --git a/tests/test_cursor_engineer.py b/tests/test_cursor_engineer.py
index 433a55f..b94d8e1 100644
--- a/tests/test_cursor_engineer.py
+++ b/tests/test_cursor_engineer.py
@@ -208,6 +208,8 @@ def test_ensure_bridge_reinstalls_when_lock_stamp_is_not_current(
timeout=600,
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
)
expected = hashlib.sha256((bridge / "package-lock.json").read_bytes()).hexdigest()
assert stamp.read_text().strip() == expected
diff --git a/tests/test_windows_compatibility.py b/tests/test_windows_compatibility.py
new file mode 100644
index 0000000..1415959
--- /dev/null
+++ b/tests/test_windows_compatibility.py
@@ -0,0 +1,222 @@
+"""Locale regressions runnable on every OS, including Windows CI."""
+
+import builtins
+import io
+import json
+import subprocess
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from reverse_api.config import ConfigManager
+from reverse_api.messages import MessageStore
+from reverse_api.opencode_engineer import OpenCodeEngineer
+from reverse_api.prompts import load
+from reverse_api.session import SessionManager
+from reverse_api.utils import OUTPUT_LANGUAGE_EXTENSIONS, extract_domain_from_har
+
+UNICODE_TEXT = "guidelines — 中文 café 🐍"
+
+
[email protected](params=["gbk", "cp1252"])
+def legacy_locale(request, monkeypatch):
+ """Model Python's legacy text-file defaults without requiring that OS locale."""
+
+ def wrap(real_open):
+ def legacy_open(file, mode="r", buffering=-1, encoding=None, *args, **kwargs):
+ if "b" not in mode and encoding in (None, "locale"):
+ encoding = request.param
+ return real_open(file, mode, buffering, encoding, *args, **kwargs)
+
+ return legacy_open
+
+ monkeypatch.setattr(builtins, "open", wrap(builtins.open))
+ monkeypatch.setattr(io, "open", wrap(io.open))
+
+
[email protected]("language", OUTPUT_LANGUAGE_EXTENSIONS)
+def test_manual_prompts_under_legacy_locale(tmp_path, legacy_locale, language):
+ engineer = OpenCodeEngineer(
+ run_id="locale-test",
+ har_path=tmp_path / "recording.har",
+ prompt=UNICODE_TEXT,
+ output_dir=str(tmp_path),
+ output_language=language,
+ interactive=False,
+ verbose=False,
+ )
+ system, user = engineer._build_prompts()
+ assert UNICODE_TEXT in user
+ assert "{include:" not in system
+ assert engineer._get_language_name() in system
+
+
+def test_nested_prompt_includes_under_legacy_locale(tmp_path, legacy_locale, monkeypatch):
+ import reverse_api.prompts as prompts
+
+ monkeypatch.setattr(prompts, "_PROMPTS_DIR", tmp_path)
+ monkeypatch.setattr(prompts, "_PARTIALS_DIR", tmp_path)
+ (tmp_path / "main.md").write_text("{include:first} {value}", encoding="utf-8")
+ (tmp_path / "first.md").write_text("{include:second}", encoding="utf-8")
+ (tmp_path / "second.md").write_text(UNICODE_TEXT, encoding="utf-8")
+ assert load("main", value="done") == f"{UNICODE_TEXT} done"
+
+
+def test_unicode_persistence_under_legacy_locale(tmp_path, legacy_locale):
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps({"agent_browser_notes": UNICODE_TEXT}, ensure_ascii=False), encoding="utf-8")
+ config = ConfigManager(config_path)
+ assert config.get("agent_browser_notes") == UNICODE_TEXT
+ config.save()
+ assert ConfigManager(config_path).get("agent_browser_notes") == UNICODE_TEXT
+
+ history_path = tmp_path / "history.json"
+ history_path.write_text(json.dumps([{"run_id": "test", "prompt": UNICODE_TEXT}], ensure_ascii=False), encoding="utf-8")
+ session = SessionManager(history_path)
+ assert session.get_run("test")["prompt"] == UNICODE_TEXT
+ session.save()
+ assert SessionManager(history_path).get_run("test")["prompt"] == UNICODE_TEXT
+
+ store = MessageStore("test", str(tmp_path))
+ store.messages_path.write_text(json.dumps({"type": "prompt", "content": UNICODE_TEXT}, ensure_ascii=False) + "\n", encoding="utf-8")
+ store.save_thinking(UNICODE_TEXT)
+ assert [m["content"] for m in store.load()] == [UNICODE_TEXT, UNICODE_TEXT]
+
+
[email protected]("encoding", ["utf-8", "utf-8-sig"])
+def test_har_unicode_and_windows_bom(tmp_path, legacy_locale, encoding):
+ har = tmp_path / "recording.har"
+ har.write_text(
+ json.dumps(
+ {"log": {"entries": [{"request": {"url": "https://example.com/中文"}, "response": {"content": {"text": UNICODE_TEXT}}}]}},
+ ensure_ascii=False,
+ ),
+ encoding=encoding,
+ )
+ assert extract_domain_from_har(har) == "example.com"
+
+
+def test_invalid_utf8_config_and_history_recover(tmp_path):
+ path = tmp_path / "broken.json"
+ path.write_bytes(b"\xff")
+ assert ConfigManager(path).get("sdk") == "claude"
+ assert SessionManager(path).history == []
+
+
+ ("platform", "env", "relative"),
+ [
+ ("win32", "LOCALAPPDATA", "Google/Chrome/User Data"),
+ ("linux", "XDG_CONFIG_HOME", "google-chrome"),
+ ("linux", "CHROME_CONFIG_HOME", "google-chrome"),
+ ("darwin", None, "Library/Application Support/Google/Chrome"),
+ ],
+)
+def test_chrome_profile_discovery(tmp_path, monkeypatch, platform, env, relative):
+ pytest.importorskip("playwright")
+ from reverse_api import browser
+
+ for key in ("LOCALAPPDATA", "XDG_CONFIG_HOME", "CHROME_CONFIG_HOME"):
+ monkeypatch.delenv(key, raising=False)
+ root = tmp_path / "User Name 中文"
+ profile = root / relative
+ profile.mkdir(parents=True)
+ if env:
+ monkeypatch.setenv(env, str(root))
+ with patch.object(Path, "home", return_value=root), patch.object(browser.sys, "platform", platform):
+ assert browser.get_chrome_profile_dir() == profile
+ profile.rmdir()
+ assert browser.get_chrome_profile_dir() is None
+
+
+def test_node_diagnostic_probe_decodes_utf8_under_gbk(monkeypatch):
+ from reverse_api.agent_browser import _probe_help_argv
+
+ monkeypatch.setattr(subprocess, "_text_encoding", lambda: "gbk")
+ error = _probe_help_argv([sys.executable, "-c", "import sys; sys.stderr.buffer.write('中文 — 🐍'.encode('utf-8')); sys.exit(1)"])
+ assert "中文 — 🐍" in error
+
+
+def test_run_json_real_python_unicode_output(tmp_path, monkeypatch):
+ """Exercise actual child pipes under a legacy locale, including a spaced path."""
+ import venv
+
+ from click.testing import CliRunner
+
+ from reverse_api import cli
+
+ output_dir = tmp_path / "User Name 中文"
+ scripts = output_dir / "scripts" / "unicode-run"
+ scripts.mkdir(parents=True)
+ script = scripts / "api_client.py"
+ script.write_text("import sys\nprint('中文 — café 🐍')\nprint('erreur — 中文', file=sys.stderr)\n", encoding="utf-8")
+ venv.EnvBuilder(with_pip=False).create(output_dir / ".venv")
+ config = ConfigManager(tmp_path / "config.json")
+ config.set("output_dir", str(output_dir))
+ session = SessionManager(tmp_path / "history.json")
+ session.add_run("unicode-run", "unicode output", paths={"script_path": str(script)})
+ monkeypatch.setattr(cli, "config_manager", config)
+ monkeypatch.setattr(cli, "session_manager", session)
+ monkeypatch.setattr(subprocess, "_text_encoding", lambda: "gbk")
+ # Configuring the parent decoder alone would still leave the child using GBK.
+ monkeypatch.setenv("PYTHONIOENCODING", "gbk")
+
+ result = CliRunner().invoke(cli.main, ["run", "unicode-run", "--json"])
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)
+ assert payload["stdout"] == "中文 — café 🐍\n"
+ assert payload["stderr"] == "erreur — 中文\n"
+
+
+def test_windows_probe_resolves_cmd_launcher(monkeypatch):
+ from reverse_api import agent_browser
+
+ launcher = r"C:\Program Files\nodejs\npx.cmd"
+ monkeypatch.setattr(agent_browser.shutil, "which", lambda _: launcher)
+ with patch.object(sys, "platform", "win32"), patch.object(subprocess, "run") as run:
+ run.return_value.returncode = 0
+ assert agent_browser._probe_help_argv(["npx", "-y", "agent-browser@0"]) is None
+ assert run.call_args.args[0] == [launcher, "-y", "agent-browser@0", "--help"]
+ assert not run.call_args.kwargs.get("shell", False)
+
+
[email protected]("machine", [False, True])
+def test_windows_script_run_resolves_cmd_launcher(tmp_path, monkeypatch, machine):
+ from reverse_api import cli
+
+ launcher = r"C:\Program Files\nodejs\npx.cmd"
+ script = tmp_path / "api_client.ts"
+ script.touch()
+ monkeypatch.setattr("shutil.which", lambda _: launcher)
+ monkeypatch.setattr(cli, "resolve_run", lambda *args, **kwargs: {"run_id": "test"})
+ monkeypatch.setattr(cli, "discover_scripts", lambda *args, **kwargs: [script])
+ with patch.object(sys, "platform", "win32"), patch.object(subprocess, "run") as run:
+ run.return_value = subprocess.CompletedProcess([], 0, stdout="ok", stderr="")
+ if machine:
+ payload = cli._run_script_machine_payload(
+ identifier="test",
+ script_args=(),
+ file_name=None,
+ list_scripts=False,
+ auto_install=False,
+ emit_event=lambda *args, **kwargs: None,
+ )
+ assert payload["status"] == "ok"
+ else:
+ with pytest.raises(SystemExit) as exit_info:
+ cli._run_non_python_script(script, ())
+ assert exit_info.value.code == 0
+ assert run.call_args.args[0][0] == launcher
+ assert not run.call_args.kwargs.get("shell", False)
+
+
[email protected](sys.platform != "win32", reason="requires Windows CreateProcess and PATHEXT")
+def test_native_windows_cmd_probe(tmp_path, monkeypatch):
+ from reverse_api.agent_browser import _probe_help_argv
+
+ launcher = tmp_path / "probe.cmd"
+ launcher.write_bytes(b"@echo off\r\necho help\r\nexit /b 0\r\n")
+ monkeypatch.setenv("PATH", str(tmp_path))
+ assert _probe_help_argv(["probe"]) is None