Skip to content

The agent that grows with you

fix(gateway): write the Windows .vbs launchers as UTF-16 with a BOM

unsupportedpastelsff567310301c
diff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.py
index fb628abed91..79554b3e82c 100644
--- a/hermes_cli/gateway_runtime_service_identity.py
+++ b/hermes_cli/gateway_runtime_service_identity.py
@@ -306,6 +306,20 @@ def read_definition(path: Path) -> bytes:
return value
+def _launcher_text(raw: bytes) -> str:
+ """Current .vbs launchers are UTF-16 with a BOM (wscript.exe reads a BOM-less script in the ANSI
+ code page); launchers written by older versions are UTF-8. Both must verify."""
+ if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
+ try:
+ return raw.decode("utf-16")
+ except UnicodeDecodeError:
+ _unverified()
+ try:
+ return raw.decode("utf-8-sig")
+ except UnicodeDecodeError:
+ _unverified()
+
+
def _vbs_identity(script: str) -> tuple[str, list[str]]:
# Recognize the vendor's complete template, not a HERMES_HOME substring
# inside an arbitrary executable script. Doubled quotes are VB literals.
@@ -379,6 +393,6 @@ def verify_windows_task(xml: str | bytes, home: Path, account: str, sid: str) ->
script = _absolute(match[1])
if script.suffix.lower() != '.vbs':
_unverified()
- configured, argv = _vbs_identity(read_definition(script).decode("utf-8"))
+ configured, argv = _vbs_identity(_launcher_text(read_definition(script)))
verify_home(home, configured)
verify_gateway_argv(argv, home)
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index fcbd9470f9f..f8b7c07b63a 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -476,19 +476,24 @@ def _write_task_script() -> Path:
# Also render the console-less .vbs launcher used by Scheduled Task and the Startup-folder fallback via
# wscript.exe (issue #45599 fix A). The .cmd wrapper stays as a generated helper/compatibility artifact.
vbs_path = script_path.with_suffix(".vbs")
- _atomic_write(vbs_path, _build_gateway_vbs_script(*settings), vbs_path.with_name(vbs_path.name + ".tmp"))
+ _atomic_write(vbs_path, _build_gateway_vbs_script(*settings), vbs_path.with_name(vbs_path.name + ".tmp"),
+ encoding="utf-16")
return script_path
-def _atomic_write(path: Path, content: str, tmp: Path) -> None:
+def _atomic_write(path: Path, content: str, tmp: Path, *, encoding: str = "utf-8") -> None:
"""Write ``content`` verbatim (no newline translation) via ``tmp`` then rename over ``path``.
The staging file is removed even when the rename fails: the Startup-folder caller stages
inside the Startup folder itself, and Windows opens every file there at login — a leftover
``Hermes_Gateway.tmp`` pops up in Notepad after every sign-in (#114093).
+
+ ``.vbs`` launchers pass ``utf-16`` (BOM included): Windows Script Host decodes a BOM-less script
+ with the ANSI code page, so a non-ASCII install path reached python as mojibake, ``PYTHONPATH``
+ no longer imported ``hermes_cli`` and every task or Startup start died before logging a line.
"""
try:
- tmp.write_text(content, encoding="utf-8", newline="")
+ tmp.write_text(content, encoding=encoding, newline="")
tmp.replace(path)
finally:
try:
@@ -605,7 +610,7 @@ def _install_startup_entry(script_path: Path) -> Path:
"""Write the Startup-folder fallback launcher. Returns its path."""
entry = get_startup_entry_path()
entry.parent.mkdir(parents=True, exist_ok=True)
- _atomic_write(entry, _build_startup_launcher(script_path), _startup_staging_path())
+ _atomic_write(entry, _build_startup_launcher(script_path), _startup_staging_path(), encoding="utf-16")
legacy_entry = _legacy_startup_entry_path()
try:
if legacy_entry.exists():
@@ -660,6 +665,9 @@ def reconcile_autostart_launchers() -> tuple[list[str], list[str]]:
if legacy.exists(): # _install_startup_entry swallows the unlink failure; both would fire at logon
return [], [f"Could not remove legacy Windows login item: {legacy} (locked or access denied; it still fires at logon beside {entry})"]
return [f"Migrated legacy Windows login item to: {entry}"], []
+ if get_startup_entry_path().exists():
+ # An entry from before the UTF-16 launchers is read in the ANSI code page at logon: rewrite it.
+ _install_startup_entry(get_task_script_path())
return [], []
diff --git a/tests/hermes_cli/test_gateway_runtime_service.py b/tests/hermes_cli/test_gateway_runtime_service.py
index 25f4ac0d151..d9f5354b1ab 100644
--- a/tests/hermes_cli/test_gateway_runtime_service.py
+++ b/tests/hermes_cli/test_gateway_runtime_service.py
@@ -295,6 +295,30 @@ def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):
verify_windows_task(xml, home, user, 'S-1-5-21-123')
+def test_task_launcher_for_a_non_ascii_home_is_utf16_and_still_verifies(tmp_path, monkeypatch):
+ """wscript.exe reads a BOM-less .vbs in the ANSI code page, so a non-ASCII HERMES_HOME (any CJK or
+ accented Windows username) reached python garbled and the gateway died before logging. The installed
+ launcher is UTF-16 with a BOM; ensure must verify it, and a UTF-8 one an older version wrote."""
+ import codecs
+ from hermes_cli import gateway_windows
+ from hermes_cli.gateway_runtime_service_identity import verify_windows_task
+
+ home = tmp_path / 'Usuário 方舟'
+ script = home / 'gateway-service' / 'Hermes_Gateway.cmd'
+ script.parent.mkdir(parents=True)
+ monkeypatch.setattr(gateway_windows, '_assert_windows', lambda: None)
+ monkeypatch.setattr(gateway_windows, 'get_task_script_path', lambda: script)
+ monkeypatch.setattr(gateway_windows, '_launcher_settings', lambda: (sys.executable, str(home), str(home), ''))
+ launcher = gateway_windows._write_task_script().with_suffix('.vbs')
+ raw = launcher.read_bytes()
+ assert raw.startswith(codecs.BOM_UTF16_LE) and str(home) in raw.decode('utf-16')
+ user = 'DOMAIN\\owner'
+ xml = gateway_windows._build_scheduled_task_xml('Hermes_Gateway', launcher, user)
+ verify_windows_task(xml, home, user, 'S-1-5-21-123')
+ launcher.write_bytes(raw.decode('utf-16').encode('utf-8'))
+ verify_windows_task(xml, home, user, 'S-1-5-21-123')
+
+
@pytest.mark.parametrize("installed", [True, False])
def test_task_discovery_skips_listing_lines_that_are_not_task_rows(tmp_path, monkeypatch, installed):
"""An orphaned TaskCache entry (OEM leftovers) makes ``schtasks /Query /FO CSV`` print a localized
diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.py
index 7db666ffe9f..a5c3f89fd35 100644
--- a/tests/hermes_cli/test_gateway_windows.py
+++ b/tests/hermes_cli/test_gateway_windows.py
@@ -492,6 +492,23 @@ def test_reconcile_leaves_one_autostart_mechanism(monkeypatch, tmp_path):
assert [p.name for p in (tmp_path / "no-task" / "Startup").iterdir()] == ["Hermes_Gateway_alice.vbs"]
+def test_reconcile_rewrites_an_older_startup_entry_as_utf16(monkeypatch, tmp_path):
+ """wscript.exe reads a BOM-less .vbs in the ANSI code page: an older UTF-8 Startup entry chaining a
+ non-ASCII path quits silently at logon (FileExists on the garbled target is false). The update
+ reconcile rewrites it as UTF-16 with a BOM."""
+ import codecs
+ startup, script = _startup_with_fallback_and_legacy_entries(monkeypatch, tmp_path / "Usuário 方舟")
+ (startup / "Hermes_Gateway_alice.cmd").unlink()
+ monkeypatch.setattr(gateway_windows, "is_task_registered", lambda: False)
+ monkeypatch.setattr(gateway_windows, "get_task_script_path", lambda: script)
+
+ assert gateway_windows.reconcile_autostart_launchers() == ([], [])
+ raw = (startup / "Hermes_Gateway_alice.vbs").read_bytes()
+ assert raw.startswith(codecs.BOM_UTF16_LE)
+ assert raw.decode("utf-16") == gateway_windows._build_startup_launcher(script)
+ assert sorted(p.name for p in startup.iterdir()) == ["Hermes_Gateway_alice.vbs"]
+
+
def test_reconcile_warns_when_legacy_entry_cannot_be_removed(monkeypatch, tmp_path):
"""#80569: no task, legacy .cmd locked. The .vbs gets written but the .cmd survives, so both fire
at logon; reconcile must warn instead of reporting a migration, and doctor --fix must not count it."""