The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): read the macOS https handler per entry and drop the installed-browser fallback
Jan-Stefan Janetzkyf5e60284177f
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 25e4a5d91b6..12b4565d1db 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -7,6 +7,7 @@ import ntpathimport osimport platformimport posixpath+import reimport shleximport shutilimport subprocess@@ -244,29 +245,74 @@ def _detect_default_windows() -> str | None:return None+_LS_HANDLERS_READER = (+ "defaults",+ "read",+ "com.apple.LaunchServices/com.apple.launchservices.secure",+ "LSHandlers",+)+++def _launchservices_https_handler(dump: str) -> str | None:+ """Return the bundle id registered for the ``https`` URL scheme.++ ``dump`` is the ``defaults read … LSHandlers`` output: an array of+ ``{ … }`` dictionaries, one per handler. Only the entry whose+ ``LSHandlerURLScheme`` is ``https`` counts — a browser registered for+ another scheme or a file type must not be mistaken for the default.+ Returns None when no https handler is recorded, which is what macOS+ stores while Safari (the implicit default) has never been replaced.+ """+ entries: list[str] = []+ depth = 0+ buf: list[str] = []+ for ch in dump:+ if ch == "{":+ depth += 1+ if depth == 1:+ buf = []+ continue+ elif ch == "}":+ depth -= 1+ if depth == 0:+ entries.append("".join(buf))+ continue+ if depth >= 1:+ buf.append(ch)+ for entry in entries:+ low = entry.lower()+ if not re.search(r'lshandlerurlscheme\s*=\s*"?https"?\s*;', low):+ continue+ # The nested LSHandlerPreferredVersions block carries "-" placeholders+ # under the same key names; the real bundle id is the first non-"-".+ for role in re.findall(r'lshandlerrole(?:all|viewer)\s*=\s*"?([a-z0-9.\-]+)"?\s*;', low):+ if role != "-":+ return role+ return None+ return None++def _detect_default_darwin() -> str | None:- # LaunchServices handler for the https scheme.- for reader in (- ["defaults", "read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"],- ):- try:- out = subprocess.run(- reader,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=5,- ).stdout.lower()- except Exception:- out = ""- for frag, browser in _DARWIN_BUNDLE_MAP:- if frag in out and "https" in out:- return browser- # Fallback: first installed Chromium app wins.- for browser in _CHROMIUM_BROWSERS:- if chromium_executable(browser, "Darwin"):+ try:+ out = subprocess.run(+ list(_LS_HANDLERS_READER),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=5,+ ).stdout+ except Exception:+ return None+ bundle = _launchservices_https_handler(out)+ if not bundle:+ return None+ for frag, browser in _DARWIN_BUNDLE_MAP:+ if bundle.startswith(frag):return browser+ # A non-Chromium https handler (Safari, Firefox, Arc, …): fail closed.+ # No "first installed Chromium wins" fallback — that would drive a+ # browser the user never made their default.return Nonediff --git a/tests/hermes_cli/test_browser_connect_default_chromium.py b/tests/hermes_cli/test_browser_connect_default_chromium.pynew file mode 100644index 00000000000..a47f248b314--- /dev/null+++ b/tests/hermes_cli/test_browser_connect_default_chromium.py@@ -0,0 +1,106 @@+"""Default-Chromium detection and profile-dir resolution (hermes_cli.browser_connect).++These exercise the parsers with real command output shapes instead of+patching the detectors themselves, so a change in what macOS / xdg report is+caught here rather than in a user's browser session.+"""+from unittest.mock import patch++import pytest++import hermes_cli.browser_connect as bc+++def _ls_dump(*entries: str) -> str:+ return "(\n" + ",\n".join(entries) + "\n)\n"+++def _handler(scheme: str, bundle: str) -> str:+ return (+ " {\n"+ " LSHandlerPreferredVersions = {\n"+ ' LSHandlerRoleAll = "-";\n'+ " };\n"+ f' LSHandlerRoleAll = "{bundle}";\n'+ f" LSHandlerURLScheme = {scheme};\n"+ " }"+ )+++def _content_type_handler(uti: str, bundle: str) -> str:+ return (+ " {\n"+ f' LSHandlerContentType = "{uti}";\n'+ f' LSHandlerRoleViewer = "{bundle}";\n'+ " }"+ )+++class TestLaunchServicesHttpsHandler:+ def test_https_entry_wins_over_other_schemes(self):+ dump = _ls_dump(+ _handler("ftp", "com.google.chrome"),+ _handler("https", "com.apple.safari"),+ )+ assert bc._launchservices_https_handler(dump) == "com.apple.safari"++ def test_content_type_registration_is_not_an_https_handler(self):+ dump = _ls_dump(_content_type_handler("public.html", "com.google.chrome"))+ assert bc._launchservices_https_handler(dump) is None++ def test_no_entries_means_no_recorded_handler(self):+ assert bc._launchservices_https_handler("(\n)\n") is None+ assert bc._launchservices_https_handler("") is None++ def test_nested_dictionary_does_not_split_the_entry(self):+ dump = _ls_dump(_handler("https", "com.microsoft.edgemac"))+ assert bc._launchservices_https_handler(dump) == "com.microsoft.edgemac"+++class TestDetectDefaultDarwin:+ def _run_with(self, dump: str):+ class _Proc:+ stdout = dump++ return patch.object(bc.subprocess, "run", return_value=_Proc())++ def test_chrome_as_https_handler(self):+ with self._run_with(_ls_dump(_handler("https", "com.google.chrome"))):+ assert bc._detect_default_darwin() == "chrome"++ def test_safari_default_with_chrome_installed_fails_closed(self):+ """The old fallback returned the first installed Chromium app; a+ non-Chromium default must resolve to None even when Chrome exists."""+ dump = _ls_dump(+ _handler("https", "com.apple.safari"),+ _handler("ftp", "com.google.chrome"),+ )+ with self._run_with(dump), \+ patch.object(bc, "chromium_executable", return_value="/Applications/Google Chrome.app/x"):+ assert bc._detect_default_darwin() is None++ def test_no_handler_recorded_fails_closed(self):+ with self._run_with("(\n)\n"), \+ patch.object(bc, "chromium_executable", return_value="/Applications/Google Chrome.app/x"):+ assert bc._detect_default_darwin() is None++ def test_firefox_default_fails_closed(self):+ with self._run_with(_ls_dump(_handler("https", "org.mozilla.firefox"))):+ assert bc._detect_default_darwin() is None++ def test_reader_failure_fails_closed(self):+ with patch.object(bc.subprocess, "run", side_effect=OSError("no defaults")):+ assert bc._detect_default_darwin() is None++ @pytest.mark.parametrize(+ "bundle,expected",+ [+ ("com.google.Chrome", "chrome"),+ ("com.brave.Browser", "brave"),+ ("com.microsoft.edgemac", "edge"),+ ("org.chromium.Chromium", "chromium"),+ ],+ )+ def test_bundle_map(self, bundle, expected):+ with self._run_with(_ls_dump(_handler("https", bundle))):+ assert bc._detect_default_darwin() == expected