Skip to content

The agent that grows with you

fix(cli): accept BOM-prefixed catalog and runtime metadata

ethernet3a707117c59d
diff --git a/hermes_cli/auth_oauth_grants.py b/hermes_cli/auth_oauth_grants.py
index 56ff576bd41..497ae08ce5e 100644
--- a/hermes_cli/auth_oauth_grants.py
+++ b/hermes_cli/auth_oauth_grants.py
@@ -171,7 +171,7 @@ def _persisted_oauth_heal_fingerprint(provider_id: str) -> Optional[list]:
if path is None:
return None
try:
- data = json.loads(path.read_text(encoding="utf-8"))
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
return None
if not isinstance(data, dict):
@@ -193,7 +193,7 @@ def _persist_oauth_heal_clean_mark(provider_id: str, fingerprint: tuple) -> None
from utils import atomic_json_write
try:
- existing = json.loads(path.read_text(encoding="utf-8"))
+ existing = json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
existing = {}
if not isinstance(existing, dict):
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py
index b00f02672c8..365a0fbd9dc 100644
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@ -389,7 +389,7 @@ def banner_snapshot_fingerprint() -> Optional[str]:
def load_banner_snapshot(enabled_toolsets: List[str] = None) -> Optional[Dict[str, Any]]:
"""Return the stored banner snapshot when its fingerprint is current."""
- blob = _quiet(lambda: json.loads(_banner_snapshot_path().read_text(encoding="utf-8")))
+ blob = _quiet(lambda: json.loads(_banner_snapshot_path().read_text(encoding="utf-8-sig")))
if not isinstance(blob, dict):
return None
fp = banner_snapshot_fingerprint()
diff --git a/hermes_cli/desktop_update_verify.py b/hermes_cli/desktop_update_verify.py
index d1f7a3f8a10..5bd252bf40c 100644
--- a/hermes_cli/desktop_update_verify.py
+++ b/hermes_cli/desktop_update_verify.py
@@ -59,7 +59,7 @@ def _verify_packaged_entry(resources: Path) -> None:
index = resources / "app.asar.unpacked" / "dist" / "index.html"
try:
- html = index.read_text(encoding="utf-8")
+ html = index.read_text(encoding="utf-8-sig")
if not any(_MODULE_TAG.search(match.group(0))
and match.group(0).lower().startswith("<script")
and not re.match(r"^[a-z]+:|^//", match.group(1), re.IGNORECASE)
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index a2a127d113e..44d00fe065e 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -473,7 +473,7 @@ def _read_manifest(default_home: Path) -> Optional[dict]:
if not path.exists():
return None
try:
- data = json.loads(path.read_text(encoding="utf-8"))
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.py
index f10dca7c32a..a3f151734dd 100644
--- a/hermes_cli/local_runtime/presets.py
+++ b/hermes_cli/local_runtime/presets.py
@@ -182,7 +182,7 @@ def read_preset_decisions(preset_path: Path | None = None) -> dict[str, PresetEn
out: dict[str, PresetEntry] = {}
try:
parser = configparser.ConfigParser(interpolation=None)
- text = preset_path.read_text(encoding="utf-8")
+ text = preset_path.read_text(encoding="utf-8-sig")
parser.read_string(text)
recorded = {}
for line in text.splitlines():
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index 548c55c12d3..0b64793e96a 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -1277,7 +1277,7 @@ def cmd_gui(args: argparse.Namespace):
# Electron package, including when --skip-build was requested.
electron = _electron_dir(PROJECT_ROOT)
try:
- executable = electron / "dist" / (electron / "path.txt").read_text(encoding="utf-8").strip()
+ executable = electron / "dist" / (electron / "path.txt").read_text(encoding="utf-8-sig").strip()
if not executable.is_file():
raise FileNotFoundError(executable)
except OSError as exc:
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.py
index 41f41fbeb1d..4437cff393c 100644
--- a/hermes_cli/plugin_catalog.py
+++ b/hermes_cli/plugin_catalog.py
@@ -131,7 +131,7 @@ def entry_from_mapping(data: Any, label: str) -> Optional[PluginCatalogEntry]:
def _read_yaml(path: Path) -> Any:
try:
- return yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ return yaml.safe_load(path.read_text(encoding="utf-8-sig")) or {}
except Exception as exc:
logger.warning("Plugin catalog: failed to read %s: %s", path, exc)
return None
@@ -225,7 +225,7 @@ def fetch_live_catalog(*, force: bool = False) -> Optional[Dict[str, Any]]:
cache = _live_cache_path()
try:
if not force and cache.is_file() and time.time() - cache.stat().st_mtime < LIVE_CATALOG_TTL_SECONDS:
- return json.loads(cache.read_text(encoding="utf-8"))
+ return json.loads(cache.read_text(encoding="utf-8-sig"))
except Exception as exc:
logger.debug("Plugin catalog: unreadable live cache %s: %s", cache, exc)
try:
@@ -243,7 +243,7 @@ def fetch_live_catalog(*, force: bool = False) -> Optional[Dict[str, Any]]:
except Exception as exc:
logger.debug("Plugin catalog: live fetch failed: %s", exc)
try: # stale cache still beats the in-tree copy when the network is down
- return json.loads(cache.read_text(encoding="utf-8")) if cache.is_file() else None
+ return json.loads(cache.read_text(encoding="utf-8-sig")) if cache.is_file() else None
except Exception:
return None
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.py
index 922d13fa52d..e5412c64a0c 100644
--- a/hermes_cli/plugin_validate.py
+++ b/hermes_cli/plugin_validate.py
@@ -436,7 +436,7 @@ def validate_plugin_dir(plugin_dir: Path) -> ValidationReport:
try:
manifest = yaml.safe_load(
- manifest_file.read_text(encoding="utf-8")
+ manifest_file.read_text(encoding="utf-8-sig")
)
except Exception as exc:
report.add("manifest", False, f"plugin.yaml failed to parse: {exc}")
diff --git a/hermes_cli/source_check.py b/hermes_cli/source_check.py
index b7c484d4f03..ed8f39758f2 100644
--- a/hermes_cli/source_check.py
+++ b/hermes_cli/source_check.py
@@ -102,7 +102,7 @@ def _github_compare_behind(current_rev: str, target_rev: str, repository: str =
def _request(url: str, accept: str = "application/vnd.github+json") -> str:
req = urllib.request.Request(url, headers={"Accept": accept, "User-Agent": "hermes-update-check"})
with urllib.request.urlopen(req, timeout=10) as response:
- return response.read(2 * 1024 * 1024).decode("utf-8").strip()
+ return response.read(2 * 1024 * 1024).decode("utf-8-sig").strip()
def _branch_tip(repository: str | None, branch: str, root: Path, git: str, remote: str = "origin") -> tuple[str | None, bool]:
@@ -177,7 +177,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = N
raise ValueError(f"Invalid update channel: {channel}")
head = embedded or _git_stdout(["rev-parse", "HEAD"], cwd=root, git=git)
current_branch = None if embedded else _git_stdout(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root, git=git)
- desktop_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8"))) if branch_config_path else None
+ desktop_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8-sig"))) if branch_config_path else None
configured_branch = desktop_config.get("branch") if isinstance(desktop_config, dict) else None
if isinstance(configured_branch, str):
configured_branch = configured_branch.strip() or None
@@ -196,7 +196,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = N
identity = {"root": str(root), "home": str(home), "head": head, "origin": origin, "branch": selected_branch,
"channel": channel, "embedded": embedded}
cache_file = Path(cache_path) if cache_path is not None else home / "source-checks" / f"{install_id(root)}.json"
- cached = _quiet(lambda: json.loads(cache_file.read_text(encoding="utf-8")))
+ cached = _quiet(lambda: json.loads(cache_file.read_text(encoding="utf-8-sig")))
now = time.time()
if (not force and isinstance(cached, dict) and cached.get("identity") == identity
and isinstance(cached.get("status"), dict) and cached["status"].get("supported") is True):
@@ -228,7 +228,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = N
result["branch"] = "main"
if branch_config_path and not branch and configured_branch == selected_branch:
# Do not overwrite a concurrent choice made while the network probe ran.
- current_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8")))
+ current_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8-sig")))
if current_config == desktop_config:
from utils import atomic_json_write
atomic_json_write(branch_config_path, {**desktop_config, "branch": "main"})
diff --git a/hermes_cli/source_releases.py b/hermes_cli/source_releases.py
index a4ee449df6d..ccb889ea5ec 100644
--- a/hermes_cli/source_releases.py
+++ b/hermes_cli/source_releases.py
@@ -45,7 +45,7 @@ def _read(url: str, *, missing_ok: bool = False) -> str | None:
})
try:
with urllib.request.urlopen(request, timeout=30) as response:
- return response.read(2 * 1024 * 1024).decode("utf-8")
+ return response.read(2 * 1024 * 1024).decode("utf-8-sig")
except urllib.error.HTTPError as exc:
if missing_ok and exc.code == 404:
return None
diff --git a/tests/agent/test_credential_pool_profile_oauth_fork.py b/tests/agent/test_credential_pool_profile_oauth_fork.py
index 667a3eadb65..2454ecd5159 100644
--- a/tests/agent/test_credential_pool_profile_oauth_fork.py
+++ b/tests/agent/test_credential_pool_profile_oauth_fork.py
@@ -775,13 +775,24 @@ def test_clean_mark_persists_so_a_fresh_process_takes_no_auth_lock(fleet, monkey
first = _count_locks(monkeypatch)
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None
assert len(first) == 2, "cold heal should take the profile and root locks"
- assert grants._oauth_heal_clean_mark_path().exists(), "clean mark not written"
+ mark = grants._oauth_heal_clean_mark_path()
+ assert mark is not None
+ raw = mark.read_bytes()
+ assert not raw.startswith(b"\xef\xbb\xbf")
+ recorded = json.loads(raw)
+ mark.write_bytes(b"\xef\xbb\xbf" + raw)
_new_process(auth_mod)
second = _count_locks(monkeypatch)
assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None
assert second == [], "a fresh process re-locked the auth store to redo a clean heal"
+ grants._persist_oauth_heal_clean_mark("openai-codex", ("café", 1))
+ assert json.loads(mark.read_bytes()) == {**recorded, "openai-codex": ["café", 1]}
+ assert not mark.read_bytes().startswith(b"\xef\xbb\xbf")
+ mark.write_bytes(b"\xef\xbb\xbf{")
+ assert grants._persisted_oauth_heal_fingerprint("anthropic") is None
+
def test_persisted_mark_still_re_heals_when_the_root_store_gains_a_grant(fleet):
"""The mark may not outlive the facts. Root acquiring a counterpart turns
diff --git a/tests/hermes_cli/test_banner.py b/tests/hermes_cli/test_banner.py
index 70f3b4b1ccd..e166d5227e6 100644
--- a/tests/hermes_cli/test_banner.py
+++ b/tests/hermes_cli/test_banner.py
@@ -9,6 +9,25 @@ import model_tools
import tools.mcp_tool_discovery
+def test_banner_snapshot_accepts_bom_without_weakening_freshness(tmp_path, monkeypatch):
+ import json
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(banner, "get_git_banner_state", lambda: None)
+ monkeypatch.setattr(banner, "get_available_skills", lambda: {"notes": ["café"]})
+ tools = [{"function": {"name": "read_file"}}]
+ banner.save_banner_snapshot(tools, ["file"], {}, {"read_file": "file"})
+ path = banner._banner_snapshot_path()
+ raw = path.read_bytes()
+ assert not raw.startswith(b"\xef\xbb\xbf")
+ expected = json.loads(raw)
+ path.write_text(json.dumps(expected, ensure_ascii=False), encoding="utf-8-sig")
+ assert banner.load_banner_snapshot(["file"]) == expected
+ assert banner.load_banner_snapshot(["web"]) is None
+ (tmp_path / "config.yaml").write_text("display: {skin: mono}", encoding="utf-8")
+ assert banner.load_banner_snapshot(["file"]) is None
+
+
def test_cprint_falls_back_to_plain_print_when_prompt_toolkit_has_no_console(capsys):
with patch(
"prompt_toolkit.print_formatted_text",
diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py
index 520f34cadd5..ad832abe74d 100644
--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py
+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py
@@ -110,6 +110,10 @@ def test_apply_records_manifest_flips_flag_and_rollback_restores(fleet, capsys):
again = gm.build_migration_plan()
assert again.already_multiplexed and gm.apply_migration(again) is True
+ manifest_path = fleet.root / gm.MANIFEST_NAME
+ raw = manifest_path.read_bytes()
+ assert not raw.startswith(b"\xef\xbb\xbf")
+ manifest_path.write_bytes(b"\xef\xbb\xbf" + raw)
fleet.ops.clear()
assert gm.rollback_migration(fleet.root) is True
assert _config_flag(fleet.root) is False
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index 2f161b99248..f2c04b9e991 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -144,6 +144,66 @@ def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):
return _run
[email protected]("local", [False, True])
+def test_source_launch_reads_bom_electron_path_without_provisioning(tmp_path, monkeypatch, local):
+ root = _make_desktop_tree(tmp_path)
+ desktop = root / "apps" / "desktop"
+ (desktop / "dist").mkdir()
+ (desktop / "dist" / "index.html").write_text("prepared renderer", encoding="utf-8")
+ electron = root / "node_modules" / "electron"
+ (electron / "dist").mkdir(parents=True)
+ (electron / "package.json").write_text("{}", encoding="utf-8")
+ executable = electron / "dist" / "électron"
+ executable.touch()
+ (electron / "path.txt").write_text(executable.name + "\n", encoding="utf-8-sig")
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
+ monkeypatch.setattr(main_desktop, "_desktop_launch_env", lambda args: ({}, []))
+ monkeypatch.setattr(main_desktop, "_register_linux_desktop_entry", lambda: None)
+ calls = []
+ monkeypatch.setattr(main_desktop.subprocess, "run",
+ lambda cmd, **kw: calls.append(cmd) or subprocess.CompletedProcess(cmd, 0))
+ args = _ns(source=True, skip_build=True, local=local)
+ with pytest.raises(SystemExit) as exit_info:
+ main_desktop.cmd_gui(args)
+ assert exit_info.value.code == 0
+ assert calls == [[str(executable), ".", *(["--local"] if local else [])]]
+ executable.unlink()
+ with pytest.raises(SystemExit) as exit_info:
+ main_desktop.cmd_gui(args)
+ assert exit_info.value.code == 1
+ assert len(calls) == 1
+
+
+def test_packaged_renderer_bom_does_not_bypass_entry_validation(tmp_path):
+ import json
+ import struct
+ from hermes_cli.desktop_update_verify import _verify_packaged_entry
+
+ resources = tmp_path / "resources"
+ dist = resources / "app.asar.unpacked" / "dist"
+ dist.mkdir(parents=True)
+ entry = b"export {};"
+ (dist / "main.mjs").write_bytes(entry)
+ package = json.dumps({"main": "dist/main.mjs"}).encode("utf-8")
+ header = json.dumps({"files": {
+ "package.json": {"size": len(package), "offset": "0"},
+ "dist": {"files": {"main.mjs": {"size": len(entry), "unpacked": True}}},
+ }}).encode("utf-8")
+ padded = header + b"\0" * (-len(header) % 4)
+ (resources / "app.asar").write_bytes(
+ struct.pack("<4I", 4, 8 + len(padded), 4 + len(padded), len(header)) + padded + package)
+ index = dist / "index.html"
+ index.write_text('<title>café</title><script type="module" src="./main.mjs"></script>',
+ encoding="utf-8-sig")
+ _verify_packaged_entry(resources)
+ index.write_text("<title>café</title>", encoding="utf-8-sig")
+ with pytest.raises(RuntimeError, match="renderer has no local module entry"):
+ _verify_packaged_entry(resources)
+ index.write_bytes(b"\xef\xbb\xbf\xff")
+ with pytest.raises(RuntimeError, match="renderer entry is invalid"):
+ _verify_packaged_entry(resources)
+
+
# Dependency admission and staging are exercised by test_desktop_source_build.py.
diff --git a/tests/hermes_cli/test_local_preset_admission.py b/tests/hermes_cli/test_local_preset_admission.py
index 31b05f5c427..599c194f9f1 100644
--- a/tests/hermes_cli/test_local_preset_admission.py
+++ b/tests/hermes_cli/test_local_preset_admission.py
@@ -1,5 +1,4 @@
"""The router must serve only admitted presets, retaining refusal and spill facts on read-back."""
-from pathlib import Path
from types import SimpleNamespace
from hermes_cli.local_runtime import presets, supervisor
@@ -8,7 +7,7 @@ from hermes_cli.local_runtime.estimator import HardwareBudget, ModelProfile
def test_preset_roundtrip_keeps_refusals_and_dense_spill(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- mdir = tmp_path / "models"
+ mdir = tmp_path / "modèles"
mdir.mkdir()
for name in ("allowed", "refused"):
(mdir / f"{name}.gguf").touch()
@@ -18,12 +17,17 @@ def test_preset_roundtrip_keeps_refusals_and_dense_spill(tmp_path, monkeypatch):
embd_table_bytes=0, n_ctx_train=65536, layers=[]))
ini = tmp_path / "presets.ini"
generated = presets.generate_presets(mdir, HardwareBudget(2 << 30, 2 << 30, 8 << 30), ini)
+ raw = ini.read_bytes()
+ assert not raw.startswith(b"\xef\xbb\xbf")
+ ini.write_bytes(b"\xef\xbb\xbf" + raw)
reread = presets.read_preset_decisions(ini)
assert set(reread) == {p.model_id for p in generated}
assert reread["refused"].refusal
assert reread["allowed"].spilled
assert reread["allowed"].keys["model"] == str(mdir / "allowed.gguf")
assert "override-tensor" not in reread["allowed"].keys # Dense spill has no tensor-pattern override.
+ ini.write_text("not an INI section", encoding="utf-8-sig")
+ assert presets.read_preset_decisions(ini) == {}
def test_optional_draft_is_enabled_only_with_room_at_the_selected_window(tmp_path, monkeypatch):
@@ -75,12 +79,13 @@ def test_supervisor_with_presets_does_not_scan_unadmitted_files(tmp_path, monkey
ini = tmp_path / "presets.ini"
ini.write_text("[allowed]\nmodel = allowed.gguf\nctx-size = 65536\n")
calls = []
- monkeypatch.setattr(supervisor, "server_binary", lambda p: Path("llama-server"))
+ binary = tmp_path / "llama-server"
monkeypatch.setattr(supervisor.subprocess, "Popen", lambda cmd, **kw: calls.append(cmd) or SimpleNamespace(pid=123))
- sup = supervisor.LlamaServerSupervisor(tmp_path, tmp_path, port=1234, preset_path=ini)
+ sup = supervisor.LlamaServerSupervisor(binary, tmp_path, port=1234, preset_path=ini)
try:
sup._spawn()
finally:
sup._log_handle.close()
+ assert calls[0][0] == str(binary)
assert "--models-preset" in calls[0]
assert "--models-dir" not in calls[0]
diff --git a/tests/hermes_cli/test_plugin_catalog.py b/tests/hermes_cli/test_plugin_catalog.py
index 6bb7cdcc6bd..e5bd8dd1e58 100644
--- a/tests/hermes_cli/test_plugin_catalog.py
+++ b/tests/hermes_cli/test_plugin_catalog.py
@@ -4,6 +4,9 @@ skipped not raised, kill-list matching is name-or-repo, and the live catalog deg
from __future__ import annotations
import json
+import os
+
+import pytest
import hermes_yaml as yaml
@@ -31,12 +34,14 @@ def test_shipped_catalog_entries_are_all_valid_and_pinned():
def test_invalid_entries_are_skipped_not_raised(tmp_path):
- (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok")))
+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok", description="café")), encoding="utf-8-sig")
(tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("short-sha", sha="abc123")))
(tmp_path / "c.yaml").write_text(yaml.safe_dump(_entry("http-repo", repo="http://x/y")))
(tmp_path / "d.yaml").write_text(yaml.safe_dump(_entry("Bad Name")))
(tmp_path / "e.yaml").write_text("- not\n- a mapping\n")
- assert [e.name for e in pc.load_catalog(tmp_path)] == ["ok"]
+ entries = pc.load_catalog(tmp_path)
+ assert [e.name for e in entries] == ["ok"]
+ assert entries[0].description == "café"
def test_find_removed_matches_name_or_normalized_repo(tmp_path):
@@ -47,15 +52,35 @@ def test_find_removed_matches_name_or_normalized_repo(tmp_path):
assert pc.find_removed("https://github.com/x/fine", tmp_path) is None
-def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkeypatch):
[email protected]("stale", [False, True])
+def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkeypatch, stale):
"""Network failure → in-tree entries; a cached live doc contributes entries AND removals."""
+ import httpx
+
+ requests = []
+ get = httpx.get
+
+ def record_get(*args, **kwargs):
+ requests.append(args)
+ return get(*args, **kwargs)
+
+ monkeypatch.setattr(httpx, "get", record_get)
cache = tmp_path / "cache" / "plugin-catalog.json"
monkeypatch.setattr(pc, "_live_cache_path", lambda: cache)
monkeypatch.setattr(pc, "LIVE_CATALOG_URL", "http://127.0.0.1:9/nope") # unreachable
assert [e.name for e in pc.load_catalog_live()] == [e.name for e in pc.load_catalog()]
cache.parent.mkdir(parents=True)
- cache.write_text(json.dumps({"entries": [_entry("live-only")],
- "removed": [{"name": "pulled-live", "reason": "cve"}]}))
- assert [e.name for e in pc.load_catalog_live()] == ["live-only"]
+ cache.write_text(json.dumps({"entries": [_entry("live-only", description="café")],
+ "removed": [{"name": "pulled-live", "reason": "cve"}]},
+ ensure_ascii=False), encoding="utf-8-sig")
+ if stale:
+ os.utime(cache, (1, 1))
+ requests.clear()
+ entries = pc.load_catalog_live()
+ assert [e.name for e in entries] == ["live-only"]
+ assert entries[0].description == "café"
+ assert bool(requests) is stale
assert pc.find_removed("pulled-live").reason == "cve"
+ cache.write_text("{", encoding="utf-8-sig")
+ assert [e.name for e in pc.load_catalog_live()] == [e.name for e in pc.load_catalog()]
diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.py
index e639912d064..457b2ea49fd 100644
--- a/tests/hermes_cli/test_plugin_validate.py
+++ b/tests/hermes_cli/test_plugin_validate.py
@@ -34,8 +34,9 @@ BASE_MANIFEST = {
def test_requires_hermes_spec_is_validated(tmp_path):
- manifest = dict(BASE_MANIFEST, requires_hermes=">=0.21")
+ manifest = dict(BASE_MANIFEST, description="café", requires_hermes=">=0.21")
d = _make_plugin(tmp_path, manifest=manifest)
+ (d / "plugin.yaml").write_text(yaml.safe_dump(manifest), encoding="utf-8-sig")
report = validate_plugin_dir(d)
diff --git a/tests/hermes_cli/test_source_check.py b/tests/hermes_cli/test_source_check.py
index 85dfe55cbc9..ea7544bbc76 100644
--- a/tests/hermes_cli/test_source_check.py
+++ b/tests/hermes_cli/test_source_check.py
@@ -104,9 +104,9 @@ def test_counts_are_honest_without_fetch(installation, tip_kind, compare, expect
from hermes_cli.source_check import check_for_updates
root, linked, home, base, head, responses, requests, git = installation
target = {"head": head, "base": base, "unknown": "a" * 40}[tip_kind]
- responses["/repos/fixture/fork/commits/main"] = (200, target)
+ responses["/repos/fixture/fork/commits/main"] = (200, "\ufeff" + target)
if compare is not None:
- responses[f"/repos/fixture/fork/compare/{head}...{target}"] = (200, compare)
+ responses[f"/repos/fixture/fork/compare/{head}...{target}"] = (200, "\ufeff" + json.dumps(compare))
status = check_for_updates(install_root=root, home=home)
assert status["behind"] == expected
assert status["updateAvailable"] is (expected != 0)
@@ -123,6 +123,10 @@ def test_cache_force_expiry_and_passive_opt_out(installation, monkeypatch):
responses[url] = (200, head)
check = lambda **kw: source_check.check_for_updates(install_root=root, home=home, **kw)
assert check()["behind"] == 0
+ cache = next((home / "source-checks").glob("*.json"))
+ raw = cache.read_bytes()
+ assert not raw.startswith(b"\xef\xbb\xbf")
+ cache.write_bytes(b"\xef\xbb\xbf" + raw)
responses[url] = (503, {})
(root / "dirty.txt").write_text("carried work")
assert check()["dirty"] is True
@@ -181,15 +185,17 @@ def test_deleted_desktop_branch_is_persisted_only_after_definitive_probe(install
from hermes_cli.source_check import check_for_updates
root, linked, home, base, head, responses, requests, git = installation
branch_file = home / "desktop-update.json"
- branch_file.write_text(json.dumps({"branch": "deleted", "other": "preserved"}))
+ branch_file.write_text(json.dumps({"branch": "deleted", "other": "café"}, ensure_ascii=False),
+ encoding="utf-8-sig")
git("remote", "set-url", "origin", str(home / "unreachable"))
status = check_for_updates(install_root=linked, home=home, branch_config_path=branch_file)
assert status["branch"] == "deleted"
- assert json.loads(branch_file.read_text())["branch"] == "deleted"
+ assert json.loads(branch_file.read_bytes())["branch"] == "deleted"
git("remote", "set-url", "origin", str(root))
status = check_for_updates(install_root=linked, home=home, branch_config_path=branch_file)
assert status["branch"] == "main"
- assert json.loads(branch_file.read_text()) == {"branch": "main", "other": "preserved"}
+ assert json.loads(branch_file.read_text(encoding="utf-8")) == {"branch": "main", "other": "café"}
+ assert not branch_file.read_bytes().startswith(b"\xef\xbb\xbf")
def test_inherited_git_target_cannot_redirect_an_explicit_install(installation, monkeypatch):
diff --git a/tests/hermes_cli/test_source_release_channels.py b/tests/hermes_cli/test_source_release_channels.py
index 430beaa7ae5..dfb57fda4c5 100644
--- a/tests/hermes_cli/test_source_release_channels.py
+++ b/tests/hermes_cli/test_source_release_channels.py
@@ -20,8 +20,8 @@ def git(root, *args):
).stdout.strip()
-def releases(tmp_path, monkeypatch):
[email protected](params=["utf-8", "utf-8-sig"])
+def releases(tmp_path, monkeypatch, request):
origin = tmp_path / "origin"
origin.mkdir()
git(origin, "init", "-b", "main")
@@ -73,7 +73,7 @@ def releases(tmp_path, monkeypatch):
self.send_response(404 if data is None else 200)
self.end_headers()
if data is not None:
- self.wfile.write((data if isinstance(data, str) else json.dumps(data)).encode())
+ self.wfile.write((data if isinstance(data, str) else json.dumps(data)).encode(request.param))
def log_message(self, format, *args):
pass