From aa4004eaf80233894c331cfc98488f3ed1cb5ee7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 11:18:36 -0500 Subject: [PATCH 1/2] fix(desktop): open() lands on the requested URL; skip real-Chrome test without Chrome (fix-forward #2358) ChromeProfileService.open(profile_id, url) now makes a page target land on the URL itself: it waits briefly for the launch tab, otherwise opens a tab at the URL over PUT /json/new, and requires /json/list to report it on an http(s) page. A page that never lands refuses with page_not_loaded; a window Desktop just started is closed again, an already-open one is kept. The same check runs when an already-open profile is opened with a URL. The real-Chrome test no longer navigates the tab itself when open() loads nothing, so it asserts what open() did, and it skips when Google Chrome isn't installed instead of failing with chrome_not_installed. --- packages/desktop/CHANGELOG.md | 8 ++ packages/desktop/docs/CHROME_PROFILE.md | 1 + .../desktop/openadapt_desktop/__init__.py | 2 +- .../openadapt_desktop/chrome_profile.py | 96 ++++++++++++- packages/desktop/package-lock.json | 4 +- packages/desktop/package.json | 2 +- packages/desktop/pyproject.toml | 2 +- packages/desktop/src-tauri/Cargo.lock | 2 +- packages/desktop/src-tauri/Cargo.toml | 2 +- packages/desktop/src-tauri/tauri.conf.json | 2 +- .../test_e2e/test_chrome_profile_real.py | 32 ++--- .../tests/test_engine/test_chrome_profile.py | 131 ++++++++++++++++++ packages/desktop/uv.lock | 2 +- 13 files changed, 258 insertions(+), 28 deletions(-) diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 4bbec60643..cc531565e8 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,14 @@ # CHANGELOG +## v0.33.1 (2026-11-24) + +### Bug Fixes + +- **desktop**: open() lands on the requested URL; skip real-Chrome test without Chrome (fix-forward #2358) + + + ## v0.33.0 (2026-11-23) ### Features diff --git a/packages/desktop/docs/CHROME_PROFILE.md b/packages/desktop/docs/CHROME_PROFILE.md index 6513b8e90e..dd53fe8730 100644 --- a/packages/desktop/docs/CHROME_PROFILE.md +++ b/packages/desktop/docs/CHROME_PROFILE.md @@ -49,6 +49,7 @@ that it can't verify, in these cases: | `consent_required` | You haven't agreed to the notice, or the notice changed since you agreed. | | `profile_in_use` | The profile is already open in a Chrome window Desktop didn't open (`SingletonLock` on macOS, `lockfile` on Windows), or Chrome passed the window to a Chrome that was already running and exited. | | `attach_unverified` | Chrome didn't report a debugging address, or `/json/version` on that address doesn't name the browser Desktop started (another port, another browser ID, not loopback, or not Google Chrome). | +| `page_not_loaded` | Chrome opened and was verified, but no tab reached the requested address. Desktop waits briefly for the launch tab, then opens a tab at the address itself, and requires Chrome to report that tab on an http(s) page. A window Desktop just started is closed again; an already-open window is left as it was. | | `default_profile_refused` | The folder is one of Chrome's own profile folders. | | `chrome_not_installed` | Google Chrome isn't in its usual install location. | diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index 772f1903a3..cc09ba4cae 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.33.0" +__version__ = "0.33.1" diff --git a/packages/desktop/openadapt_desktop/chrome_profile.py b/packages/desktop/openadapt_desktop/chrome_profile.py index 885c4a685d..666bf921a3 100644 --- a/packages/desktop/openadapt_desktop/chrome_profile.py +++ b/packages/desktop/openadapt_desktop/chrome_profile.py @@ -53,7 +53,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Any -from urllib.parse import urlsplit +from urllib.parse import quote, urlsplit from loguru import logger @@ -85,6 +85,7 @@ _DEVTOOLS_FILE = "DevToolsActivePort" _START_TIMEOUT_S = 30.0 _CLOSE_TIMEOUT_S = 10.0 +_PAGE_GRACE_S = 3.0 _MAX_NAME = 60 @@ -271,6 +272,49 @@ def http_json_version(port: int, timeout: float = 5.0) -> dict[str, Any]: return data +def http_json_list(port: int, timeout: float = 5.0) -> list[dict[str, Any]]: + """GET ``/json/list`` (the browser's targets) from loopback, with no proxy.""" + + import httpx + + with httpx.Client(trust_env=False, timeout=timeout) as client: + response = client.get(f"http://127.0.0.1:{port}/json/list") + response.raise_for_status() + data = response.json() + if not isinstance(data, list): + raise ValueError("unexpected /json/list body") + return [t for t in data if isinstance(t, dict)] + + +def http_json_new(port: int, url: str, timeout: float = 5.0) -> dict[str, Any]: + """PUT ``/json/new?``: open a new page target at ``url``.""" + + import httpx + + with httpx.Client(trust_env=False, timeout=timeout) as client: + response = client.put(f"http://127.0.0.1:{port}/json/new?{quote(url, safe='')}") + response.raise_for_status() + data = response.json() + if not isinstance(data, dict): + raise ValueError("unexpected /json/new body") + return data + + +def _origin(url: str) -> tuple[str, str, int | None]: + parts = urlsplit(url) + return parts.scheme, (parts.hostname or ""), parts.port + + +def page_at(target: dict[str, Any], url: str, *, same_origin: bool = False) -> bool: + """Whether a page target is at ``url`` (or, if allowed, on its origin).""" + + current = str(target.get("url") or "") + return target.get("type") == "page" and ( + current.split("#", 1)[0] == url.split("#", 1)[0] + or (same_origin and _origin(current) == _origin(url)) + ) + + def verify_endpoint(version: dict[str, Any], port: int, browser_path: str) -> None: """Require ``/json/version`` to name the browser Desktop started.""" @@ -361,6 +405,8 @@ def __init__( spawn: Callable[..., Any] = child_process.popen, json_version: Callable[[int], dict[str, Any]] = http_json_version, browser_close: Callable[[int, str], None] = send_browser_close, + json_list: Callable[[int], list[dict[str, Any]]] = http_json_list, + json_new: Callable[[int, str], dict[str, Any]] = http_json_new, clock: Callable[[], float] = time.time, sleep: Callable[[float], None] = time.sleep, start_timeout: float = _START_TIMEOUT_S, @@ -374,6 +420,8 @@ def __init__( self._spawn = spawn self._json_version = json_version self._browser_close = browser_close + self._json_list = json_list + self._json_new = json_new self._clock = clock self._sleep = sleep self._start_timeout = start_timeout @@ -553,6 +601,8 @@ def open(self, profile_id: str, url: str | None = None) -> dict[str, Any]: owned = self._alive(profile_id) if owned is not None: self._verify(owned) + if url: + self._ensure_page(owned, str(url), launched=False) return self._opened(profile_id, owned) user_data = self._user_data_dir(profile_id) self._refuse_default_dir(user_data) @@ -588,6 +638,8 @@ def open(self, profile_id: str, url: str | None = None) -> dict[str, Any]: try: owned = self._await_endpoint(process, user_data) self._verify_when_ready(owned) + if url: + self._ensure_page(owned, str(url), launched=True) except BaseException: self._stop_process(process, None) raise @@ -649,6 +701,48 @@ def _verify_when_ready(self, owned: _Owned) -> None: raise self._sleep(0.25) + def _ensure_page(self, owned: _Owned, url: str, *, launched: bool) -> None: + """Make a page target land on ``url`` and confirm Chrome reports it there. + + Chrome usually loads the launch URL in its first tab. It can open that + tab blank instead (seen on macOS when another Chrome is running). So + after a short wait for the launch tab, Desktop opens a tab at the URL + itself, then requires Chrome to report that tab on an http(s) page (a + redirect, such as sign-in, may move it). Only the launch tab of a window + Desktop just started may count by origin (its own redirect); in a window + that was already open, only a tab at the exact URL counts. A page that + never lands refuses with ``page_not_loaded``. + """ + + now = self._clock() + deadline = now + self._start_timeout + grace = now + min(_PAGE_GRACE_S, self._start_timeout / 2) # leaves time to open a tab + created: str | None = None + while True: + try: + targets = self._json_list(owned.port) + if created is None and any(page_at(t, url, same_origin=launched) for t in targets): + return + if created is None and self._clock() >= grace: + created = str(self._json_new(owned.port, url).get("id") or "") + targets = self._json_list(owned.port) + if created is not None and any( + created + and t.get("id") == created + and t.get("type") == "page" + and urlsplit(str(t.get("url") or "")).scheme in {"http", "https"} + for t in targets + ): + return + except Exception as exc: # noqa: BLE001 - any failure is unconfirmed + logger.info("Chrome page check failed: {}", type(exc).__name__) + if owned.process.poll() is not None or self._clock() >= deadline: + raise ChromeProfileError( + "page_not_loaded", + "Chrome opened, but the page didn't load. Check the address and try again.", + ) + self._sleep(0.2) + def _verify(self, owned: _Owned) -> None: if owned.process.poll() is not None: raise ChromeProfileError( diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index f613070ff1..f3c234e160 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.33.0", + "version": "0.33.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.33.0", + "version": "0.33.1", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index aa7e9a5c8a..2c783d85d2 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.33.0", + "version": "0.33.1", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index 63f5f002e6..3fe6a23eca 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.33.0" +version = "0.33.1" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index d1cc434ca1..bd382c33a4 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.33.0" +version = "0.33.1" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 70f06e3f30..1f01c3e9fc 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.33.0" +version = "0.33.1" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index 25fc43c8e5..72fee416c1 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.33.0", + "version": "0.33.1", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/tests/test_e2e/test_chrome_profile_real.py b/packages/desktop/tests/test_e2e/test_chrome_profile_real.py index dbabf4daae..6e4f972857 100644 --- a/packages/desktop/tests/test_e2e/test_chrome_profile_real.py +++ b/packages/desktop/tests/test_e2e/test_chrome_profile_real.py @@ -99,16 +99,15 @@ def _page_text(endpoint: str, origin: str) -> str: browser.close() -def _navigate_open_page(endpoint: str, target_url: str) -> None: - playwright = pytest.importorskip("playwright.sync_api") - with playwright.sync_playwright() as pw: - browser = pw.chromium.connect_over_cdp(endpoint) - try: - pages = [p for c in browser.contexts for p in c.pages] - page = pages[0] if pages else browser.contexts[0].new_page() - page.goto(target_url, wait_until="domcontentloaded") - finally: - browser.close() +def _require_chrome() -> Path: + """Return the installed Google Chrome, or skip when there is none.""" + + try: + return find_chrome() + except ChromeProfileError as exc: + if exc.code != "chrome_not_installed": + raise + pytest.skip("Google Chrome isn't installed on this machine") def _cookies_db_exists(user_data: Path) -> bool: @@ -119,7 +118,7 @@ def _cookies_db_exists(user_data: Path) -> bool: @pytest.mark.skipif(not ELEVATED, reason="only an elevated Windows process is refused") def test_an_elevated_windows_desktop_refuses_real_chrome(tmp_path: Path) -> None: - find_chrome() + _require_chrome() service = ChromeProfileService(tmp_path / "data") profile_id = service.create("Synthetic", notice()["sha256"], True)["profile_id"] with pytest.raises(ChromeProfileError) as err: @@ -134,7 +133,7 @@ def test_an_elevated_windows_desktop_refuses_real_chrome(tmp_path: Path) -> None "the Windows lab runs this without administrator rights", ) def test_sign_in_persists_and_desktop_closes_only_its_window(tmp_path: Path, portal: str) -> None: - find_chrome() # the job installs nothing; Chrome must already be there + chrome = _require_chrome() # the job installs nothing; Chrome must already be there service = ChromeProfileService(tmp_path / "data") n = notice() profile_id = service.create("Synthetic portal", n["sha256"], True)["profile_id"] @@ -159,7 +158,7 @@ def test_sign_in_persists_and_desktop_closes_only_its_window(tmp_path: Path, por own_dir = Path(tempfile.mkdtemp(prefix="own-chrome-")) own = subprocess.Popen( [ - str(find_chrome()), + str(chrome), f"--user-data-dir={own_dir}", "--no-first-run", "--no-default-browser-check", @@ -179,12 +178,9 @@ def test_sign_in_persists_and_desktop_closes_only_its_window(tmp_path: Path, por # Reopen: Chrome sends the cookie it kept; nothing was typed again. _Portal.seen.clear() + # open() itself makes a tab land on the URL (macOS can open the launch + # tab blank while another Chrome runs); the test doesn't navigate. reopened = service.open(profile_id, f"{portal}/home") - if not _wait_for(lambda: ("/home", True) in _Portal.seen, 10.0) and not _Portal.seen: - # On macOS, launching a second Chrome instance while another Chrome - # process is active can occasionally open without loading the CLI - # URL; navigate the already-open tab to /home without re-logging in. - _navigate_open_page(reopened["browser_cdp_endpoint"], f"{portal}/home") assert _wait_for(lambda: ("/home", True) in _Portal.seen, 20.0), ( f"expected ('/home', True) in {_Portal.seen!r}" ) diff --git a/packages/desktop/tests/test_engine/test_chrome_profile.py b/packages/desktop/tests/test_engine/test_chrome_profile.py index 9c233eb5cd..e6dd4f7b8d 100644 --- a/packages/desktop/tests/test_engine/test_chrome_profile.py +++ b/packages/desktop/tests/test_engine/test_chrome_profile.py @@ -62,6 +62,12 @@ def __init__(self, tmp_path: Path, **overrides: Any) -> None: self.write_port = True self.exit_now = False self.close_exits = True + # Page targets Chrome reports on /json/list; the launch tab takes the + # launch URL unless a test says otherwise. + self.launch_tab_url: str | None = None + self.targets: list[dict[str, Any]] = [] + self.created: list[str] = [] + self.new_tab_url: str | None = None chrome = tmp_path / "Google Chrome" chrome.write_text("") self.chrome = chrome @@ -72,6 +78,8 @@ def __init__(self, tmp_path: Path, **overrides: Any) -> None: "spawn": self._spawn, "json_version": self._json_version, "browser_close": self._browser_close, + "json_list": self._json_list, + "json_new": self._json_new, "sleep": lambda _s: None, "start_timeout": 0.5, } @@ -85,8 +93,25 @@ def _spawn(self, args: list[str], **kwargs: Any) -> FakeProcess: user_data = Path(next(a for a in args if a.startswith("--user-data-dir=")).split("=", 1)[1]) if self.write_port and not self.exit_now: (user_data / "DevToolsActivePort").write_text(f"{self.port}\n{GUID}\n") + launch = args[-1] if self.launch_tab_url is None else self.launch_tab_url + self.targets.append({"id": f"T{len(self.targets)}", "type": "page", "url": launch}) return process + def _json_list(self, port: int) -> list[dict[str, Any]]: + assert port == self.port + return [dict(t) for t in self.targets] + + def _json_new(self, port: int, url: str) -> dict[str, Any]: + assert port == self.port + self.created.append(url) + target = { + "id": f"N{len(self.created)}", + "type": "page", + "url": url if self.new_tab_url is None else self.new_tab_url, + } + self.targets.append(target) + return dict(target) + def _json_version(self, port: int) -> dict[str, Any]: assert port == self.port return dict(self.version) @@ -187,6 +212,112 @@ def test_open_launches_official_chrome_on_the_owned_directory(h: Harness) -> Non assert h.service.list()["profiles"][0]["browser_cdp_endpoint"] == result["browser_cdp_endpoint"] +def test_open_keeps_the_launch_tab_when_it_is_at_the_url(h: Harness) -> None: + h.service.open(h.create(), "https://portal.example/start") + assert h.created == [] + + +def test_open_keeps_a_launch_tab_that_redirected_within_the_origin(h: Harness) -> None: + h.launch_tab_url = "https://portal.example/home" + h.service.open(h.create(), "https://portal.example/login") + assert h.created == [] + + +def test_open_opens_a_tab_at_the_url_when_the_launch_tab_stayed_blank(h: Harness) -> None: + h.launch_tab_url = "about:blank" + result = h.service.open(h.create(), "https://portal.example/start?next=%2Fhome") + assert result["open"] is True + assert h.created == ["https://portal.example/start?next=%2Fhome"] + + +def test_a_new_tab_redirected_to_another_origin_counts_as_landed(h: Harness) -> None: + h.launch_tab_url = "chrome://newtab/" + h.new_tab_url = "https://sso.example/authorize" + assert h.service.open(h.create(), "https://portal.example/start")["open"] is True + assert h.created == ["https://portal.example/start"] + + +def test_a_page_that_never_loads_is_refused_and_the_window_closed(h: Harness) -> None: + h.launch_tab_url = "about:blank" + h.new_tab_url = "about:blank" + profile_id = h.create() + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id, "https://portal.example/start") + assert err.value.code == "page_not_loaded" + assert h.created == ["https://portal.example/start"] # one tab, not one per poll + assert h.spawned[0].log == ["terminate"] + assert h.service.list()["profiles"][0]["open"] is False + + +def test_an_unreachable_target_list_is_refused(tmp_path: Path) -> None: + def boom(_port: int) -> list: + raise ConnectionRefusedError + + h = Harness(tmp_path, json_list=boom) + with pytest.raises(ChromeProfileError) as err: + h.service.open(h.create(), "https://portal.example/start") + assert err.value.code == "page_not_loaded" + + +def test_open_without_a_url_checks_no_page(tmp_path: Path) -> None: + def never(*_a: Any) -> Any: + raise AssertionError("no page check without a URL") + + h = Harness(tmp_path, json_list=never, json_new=never) + assert h.service.open(h.create())["open"] is True + + +def test_reopening_an_open_window_with_a_url_lands_on_it(h: Harness) -> None: + profile_id = h.create() + first = h.service.open(profile_id) + assert h.service.open(profile_id, "https://portal.example/next") == first + assert len(h.spawned) == 1 + assert h.created == ["https://portal.example/next"] + + +def test_reopening_an_open_window_on_another_page_of_the_origin_opens_it(h: Harness) -> None: + profile_id = h.create() + h.service.open(profile_id, "https://portal.example/a") + assert h.created == [] + h.service.open(profile_id, "https://portal.example/b") + assert h.created == ["https://portal.example/b"] + h.service.open(profile_id, "https://portal.example/b#top") + assert h.created == ["https://portal.example/b"] # already there + + +def test_an_open_window_is_left_open_when_its_page_does_not_load(h: Harness) -> None: + profile_id = h.create() + h.service.open(profile_id) + h.new_tab_url = "about:blank" + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id, "https://portal.example/next") + assert err.value.code == "page_not_loaded" + assert h.closed == [] + assert h.service.list()["profiles"][0]["open"] is True + + +def test_json_new_puts_the_percent_encoded_url(monkeypatch) -> None: + import httpx + + seen: list[tuple[str, str]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append((request.method, str(request.url))) + return httpx.Response(200, json={"id": "N1", "type": "page", "url": "x"}) + + real = httpx.Client + + def client(**kwargs: Any) -> httpx.Client: + assert kwargs.get("trust_env") is False + return real(transport=httpx.MockTransport(handler), **kwargs) + + monkeypatch.setattr(httpx, "Client", client) + assert cp.http_json_new(9222, "https://p.example/a?b=1&c=%2F")["id"] == "N1" + assert seen == [ + ("PUT", "http://127.0.0.1:9222/json/new?https%3A%2F%2Fp.example%2Fa%3Fb%3D1%26c%3D%252F") + ] + + def test_open_twice_reuses_the_owned_window(h: Harness) -> None: profile_id = h.create() first = h.service.open(profile_id) diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 904e1ceb74..4dd0436cce 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.33.0" +version = "0.33.1" source = { editable = "." } dependencies = [ { name = "cryptography" }, From ce590d4e4e317d244ed77d4286302d7071d1c669 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 12:21:03 -0500 Subject: [PATCH 2/2] fix(desktop): confirm the page loaded over CDP and count only the launch tab by origin open(profile_id, url) now asks each candidate tab, over its own debugging socket, for location.href and document.readyState, and requires an http(s) document that isn't Chrome's error page, interactive or complete. Chrome keeps the requested address on a target that shows its error page, so the target URL alone never caught an address that doesn't load. An error page refuses at once with page_not_loaded. Only the launch tab (the single page on the first listing of a window Desktop just started) may count by origin. A restored or other tab on the same origin no longer stands in for the requested URL. --- packages/desktop/docs/CHROME_PROFILE.md | 2 +- .../openadapt_desktop/chrome_profile.py | 177 ++++++++++++++---- .../tests/test_engine/test_chrome_profile.py | 159 +++++++++++++++- 3 files changed, 304 insertions(+), 34 deletions(-) diff --git a/packages/desktop/docs/CHROME_PROFILE.md b/packages/desktop/docs/CHROME_PROFILE.md index dd53fe8730..b538a22d92 100644 --- a/packages/desktop/docs/CHROME_PROFILE.md +++ b/packages/desktop/docs/CHROME_PROFILE.md @@ -49,7 +49,7 @@ that it can't verify, in these cases: | `consent_required` | You haven't agreed to the notice, or the notice changed since you agreed. | | `profile_in_use` | The profile is already open in a Chrome window Desktop didn't open (`SingletonLock` on macOS, `lockfile` on Windows), or Chrome passed the window to a Chrome that was already running and exited. | | `attach_unverified` | Chrome didn't report a debugging address, or `/json/version` on that address doesn't name the browser Desktop started (another port, another browser ID, not loopback, or not Google Chrome). | -| `page_not_loaded` | Chrome opened and was verified, but no tab reached the requested address. Desktop waits briefly for the launch tab, then opens a tab at the address itself, and requires Chrome to report that tab on an http(s) page. A window Desktop just started is closed again; an already-open window is left as it was. | +| `page_not_loaded` | Chrome opened and was verified, but no tab loaded the requested address. Desktop accepts a tab Chrome reports at the exact address, or, in a window it just started, the launch tab on that address's origin (its own redirect). Otherwise it opens a tab at the address, which may then redirect anywhere, such as to sign-in. It then asks that tab, over its own debugging connection, for its document address and `readyState`, and requires an http(s) document that isn't Chrome's error page, interactive or complete. An error page refuses at once; a tab that hasn't loaded within the launch timeout refuses then. A window Desktop just started is closed again; an already-open window is left as it was. | | `default_profile_refused` | The folder is one of Chrome's own profile folders. | | `chrome_not_installed` | Google Chrome isn't in its usual install location. | diff --git a/packages/desktop/openadapt_desktop/chrome_profile.py b/packages/desktop/openadapt_desktop/chrome_profile.py index 666bf921a3..056c7ea12c 100644 --- a/packages/desktop/openadapt_desktop/chrome_profile.py +++ b/packages/desktop/openadapt_desktop/chrome_profile.py @@ -42,6 +42,7 @@ import hashlib import json import os +import re import secrets import shutil import socket @@ -338,19 +339,20 @@ def verify_endpoint(version: dict[str, Any], port: int, browser_path: str) -> No ) -def send_browser_close(port: int, browser_path: str, timeout: float = 3.0) -> None: - """Send ``Browser.close`` over the browser WebSocket (no Origin header).""" +def _ws_connect(port: int, path: str, timeout: float) -> socket.socket: + """Open a loopback WebSocket to ``path`` (no Origin header).""" key = base64.b64encode(secrets.token_bytes(16)).decode("ascii") request = ( - f"GET {browser_path} HTTP/1.1\r\n" + f"GET {path} HTTP/1.1\r\n" f"Host: 127.0.0.1:{port}\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" f"Sec-WebSocket-Key: {key}\r\n" "Sec-WebSocket-Version: 13\r\n\r\n" ).encode("ascii") - with socket.create_connection(("127.0.0.1", port), timeout=timeout) as sock: + sock = socket.create_connection(("127.0.0.1", port), timeout=timeout) + try: sock.sendall(request) reply = b"" while b"\r\n\r\n" not in reply: @@ -360,13 +362,65 @@ def send_browser_close(port: int, browser_path: str, timeout: float = 3.0) -> No reply += chunk if not reply.startswith(b"HTTP/1.1 101"): raise ConnectionError("Chrome refused the WebSocket upgrade") - payload = json.dumps({"id": 1, "method": "Browser.close"}).encode("utf-8") - mask = secrets.token_bytes(4) - header = bytes([0x81, 0x80 | len(payload)]) if len(payload) < 126 else b"" - if not header: - header = bytes([0x81, 0x80 | 126]) + len(payload).to_bytes(2, "big") - masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) - sock.sendall(header + mask + masked) + except BaseException: + sock.close() + raise + return sock + + +def _ws_send(sock: socket.socket, message: dict[str, Any]) -> None: + """Send one masked text frame.""" + + payload = json.dumps(message).encode("utf-8") + mask = secrets.token_bytes(4) + if len(payload) < 126: + header = bytes([0x81, 0x80 | len(payload)]) + elif len(payload) < 65536: + header = bytes([0x81, 0x80 | 126]) + len(payload).to_bytes(2, "big") + else: + header = bytes([0x81, 0x80 | 127]) + len(payload).to_bytes(8, "big") + masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) + sock.sendall(header + mask + masked) + + +def _recv_exact(sock: socket.socket, n: int) -> bytes: + data = b"" + while len(data) < n: + chunk = sock.recv(n - len(data)) + if not chunk: + raise ConnectionError("Chrome closed the WebSocket") + data += chunk + return data + + +def _ws_recv(sock: socket.socket, limit: int = 1 << 20) -> dict[str, Any]: + """Read one complete, unmasked text message from Chrome (pings skipped).""" + + while True: + first, second = _recv_exact(sock, 2) + opcode, length = first & 0x0F, second & 0x7F + if length == 126: + length = int.from_bytes(_recv_exact(sock, 2), "big") + elif length == 127: + length = int.from_bytes(_recv_exact(sock, 8), "big") + if second & 0x80 or length > limit: + raise ConnectionError("unexpected WebSocket frame from Chrome") + body = _recv_exact(sock, length) + if opcode in (0x9, 0xA): # ping, pong + continue + if opcode != 0x1 or not first & 0x80: + raise ConnectionError("unexpected WebSocket frame from Chrome") + data = json.loads(body) + if not isinstance(data, dict): + raise ValueError("unexpected CDP message") + return data + + +def send_browser_close(port: int, browser_path: str, timeout: float = 3.0) -> None: + """Send ``Browser.close`` over the browser WebSocket (no Origin header).""" + + with _ws_connect(port, browser_path, timeout) as sock: + _ws_send(sock, {"id": 1, "method": "Browser.close"}) # Wait briefly for Chrome to acknowledge or close the WebSocket so the # socket does not send an abrupt TCP reset before Browser.close is read. sock.settimeout(min(timeout, 1.0)) @@ -376,6 +430,34 @@ def send_browser_close(port: int, browser_path: str, timeout: float = 3.0) -> No pass +_TARGET_ID = re.compile(r"[0-9A-Za-z]{1,64}") +_PAGE_STATE = "JSON.stringify([String(location.href), String(document.readyState)])" + + +def cdp_page_state(port: int, target_id: str, timeout: float = 3.0) -> tuple[str, str]: + """Return a page target's document URL and ``readyState`` over its own CDP socket. + + One read-only ``Runtime.evaluate`` of ``location.href`` and + ``document.readyState``. Chrome's error page reports a ``chrome-error://`` + document URL even when the target keeps the requested address. + """ + + if not _TARGET_ID.fullmatch(target_id): + raise ValueError("unexpected target id") + with _ws_connect(port, f"/devtools/page/{target_id}", timeout) as sock: + params = {"expression": _PAGE_STATE, "returnByValue": True} + _ws_send(sock, {"id": 1, "method": "Runtime.evaluate", "params": params}) + while True: + message = _ws_recv(sock) + if message.get("id") == 1: + break + value = ((message.get("result") or {}).get("result") or {}).get("value") + state = json.loads(value) if isinstance(value, str) else None + if not (isinstance(state, list) and len(state) == 2 and all(isinstance(v, str) for v in state)): + raise ValueError("unexpected page state") + return state[0], state[1] + + # ------------------------------------------------------------------ service @@ -407,6 +489,7 @@ def __init__( browser_close: Callable[[int, str], None] = send_browser_close, json_list: Callable[[int], list[dict[str, Any]]] = http_json_list, json_new: Callable[[int, str], dict[str, Any]] = http_json_new, + page_state: Callable[[int, str], tuple[str, str]] = cdp_page_state, clock: Callable[[], float] = time.time, sleep: Callable[[float], None] = time.sleep, start_timeout: float = _START_TIMEOUT_S, @@ -422,6 +505,7 @@ def __init__( self._browser_close = browser_close self._json_list = json_list self._json_new = json_new + self._page_state = page_state self._clock = clock self._sleep = sleep self._start_timeout = start_timeout @@ -702,38 +786,54 @@ def _verify_when_ready(self, owned: _Owned) -> None: self._sleep(0.25) def _ensure_page(self, owned: _Owned, url: str, *, launched: bool) -> None: - """Make a page target land on ``url`` and confirm Chrome reports it there. + """Make a tab load ``url`` and confirm over CDP that it loaded. Chrome usually loads the launch URL in its first tab. It can open that - tab blank instead (seen on macOS when another Chrome is running). So - after a short wait for the launch tab, Desktop opens a tab at the URL - itself, then requires Chrome to report that tab on an http(s) page (a - redirect, such as sign-in, may move it). Only the launch tab of a window - Desktop just started may count by origin (its own redirect); in a window - that was already open, only a tab at the exact URL counts. A page that - never lands refuses with ``page_not_loaded``. + tab blank instead (seen on macOS when another Chrome is running), and a + window can hold other tabs (restored, or already open). A tab counts + when Chrome reports it at the exact URL, or, for a window Desktop just + started, when it is the launch tab (the only page Chrome lists first) + and is on the URL's origin (its own redirect). If no tab counts after a + short wait, Desktop opens one at the URL; that tab may then redirect + anywhere (sign-in). Each candidate must then show a loaded document: + an http(s) ``location.href`` that isn't Chrome's error page, with + ``readyState`` interactive or complete. An error page, or no loaded tab + by the deadline, refuses with ``page_not_loaded``. """ now = self._clock() deadline = now + self._start_timeout grace = now + min(_PAGE_GRACE_S, self._start_timeout / 2) # leaves time to open a tab + launch_id: str | None = None if launched else "" created: str | None = None + matched = False while True: try: - targets = self._json_list(owned.port) - if created is None and any(page_at(t, url, same_origin=launched) for t in targets): - return - if created is None and self._clock() >= grace: + pages = [t for t in self._json_list(owned.port) if t.get("type") == "page"] + if launch_id is None and pages: + launch_id = str(pages[0].get("id") or "") if len(pages) == 1 else "" + if created is None: + candidates = [ + t + for t in pages + if page_at(t, url) + or ( + launch_id + and t.get("id") == launch_id + and page_at(t, url, same_origin=True) + ) + ] + else: + candidates = [t for t in pages if created and t.get("id") == created] + matched = matched or bool(candidates) + for target in candidates: + if self._page_loaded(owned, str(target.get("id") or "")): + return + if created is None and not matched and self._clock() >= grace: created = str(self._json_new(owned.port, url).get("id") or "") - targets = self._json_list(owned.port) - if created is not None and any( - created - and t.get("id") == created - and t.get("type") == "page" - and urlsplit(str(t.get("url") or "")).scheme in {"http", "https"} - for t in targets - ): - return + continue + except ChromeProfileError: + raise except Exception as exc: # noqa: BLE001 - any failure is unconfirmed logger.info("Chrome page check failed: {}", type(exc).__name__) if owned.process.poll() is not None or self._clock() >= deadline: @@ -743,6 +843,19 @@ def _ensure_page(self, owned: _Owned, url: str, *, launched: bool) -> None: ) self._sleep(0.2) + def _page_loaded(self, owned: _Owned, target_id: str) -> bool: + """Whether the tab shows a loaded http(s) document; refuse Chrome's error page.""" + + href, ready = self._page_state(owned.port, target_id) + scheme = urlsplit(href).scheme + if scheme == "chrome-error": + raise ChromeProfileError( + "page_not_loaded", + "Chrome opened, but the page didn't load (Chrome showed its error page). " + "Check the address and try again.", + ) + return scheme in {"http", "https"} and ready in {"interactive", "complete"} + def _verify(self, owned: _Owned) -> None: if owned.process.poll() is not None: raise ChromeProfileError( diff --git a/packages/desktop/tests/test_engine/test_chrome_profile.py b/packages/desktop/tests/test_engine/test_chrome_profile.py index e6dd4f7b8d..9c8adec6b0 100644 --- a/packages/desktop/tests/test_engine/test_chrome_profile.py +++ b/packages/desktop/tests/test_engine/test_chrome_profile.py @@ -68,6 +68,12 @@ def __init__(self, tmp_path: Path, **overrides: Any) -> None: self.targets: list[dict[str, Any]] = [] self.created: list[str] = [] self.new_tab_url: str | None = None + # Tabs Chrome restores next to the launch tab, and per-target + # (location.href, readyState) overrides; by default a tab's document + # is at its target URL and complete. + self.restored: list[str] = [] + self.states: dict[str, list[tuple[str, str]]] = {} + self.state_calls: list[str] = [] chrome = tmp_path / "Google Chrome" chrome.write_text("") self.chrome = chrome @@ -80,6 +86,7 @@ def __init__(self, tmp_path: Path, **overrides: Any) -> None: "browser_close": self._browser_close, "json_list": self._json_list, "json_new": self._json_new, + "page_state": self._page_state, "sleep": lambda _s: None, "start_timeout": 0.5, } @@ -95,8 +102,19 @@ def _spawn(self, args: list[str], **kwargs: Any) -> FakeProcess: (user_data / "DevToolsActivePort").write_text(f"{self.port}\n{GUID}\n") launch = args[-1] if self.launch_tab_url is None else self.launch_tab_url self.targets.append({"id": f"T{len(self.targets)}", "type": "page", "url": launch}) + for restored in self.restored: + self.targets.append({"id": f"R{len(self.targets)}", "type": "page", "url": restored}) return process + def _page_state(self, port: int, target_id: str) -> tuple[str, str]: + assert port == self.port + self.state_calls.append(target_id) + queued = self.states.get(target_id) + if queued: + return queued.pop(0) if len(queued) > 1 else queued[0] + url = next(t["url"] for t in self.targets if t["id"] == target_id) + return url, "complete" + def _json_list(self, port: int) -> list[dict[str, Any]]: assert port == self.port return [dict(t) for t in self.targets] @@ -259,11 +277,78 @@ def boom(_port: int) -> list: assert err.value.code == "page_not_loaded" +def test_a_restored_tab_on_the_origin_does_not_stand_in_for_the_url(h: Harness) -> None: + h.launch_tab_url = "about:blank" + h.restored = ["https://portal.example/settings"] + h.service.open(h.create(), "https://portal.example/start") + assert h.created == ["https://portal.example/start"] + + +def test_only_the_launch_tab_counts_by_origin(h: Harness) -> None: + h.launch_tab_url = "https://portal.example/home" + h.restored = ["https://portal.example/settings"] + h.service.open(h.create(), "https://portal.example/login") + # Two pages on the first listing: neither is known to be the launch tab. + assert h.created == ["https://portal.example/login"] + + +def test_an_error_page_at_the_requested_address_is_refused(h: Harness) -> None: + h.states["T0"] = [("chrome-error://chromewebdata/", "complete")] + profile_id = h.create() + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id, "http://127.0.0.1:9/never") + assert err.value.code == "page_not_loaded" + assert h.created == [] # a second tab would only show the same error + assert h.spawned[0].log == ["terminate"] + + +def test_a_new_tab_that_shows_an_error_page_is_refused(h: Harness) -> None: + h.launch_tab_url = "about:blank" + h.states["N1"] = [("chrome-error://chromewebdata/", "complete")] + with pytest.raises(ChromeProfileError) as err: + h.service.open(h.create(), "https://portal.example/start") + assert err.value.code == "page_not_loaded" + + +def test_open_waits_for_the_document_to_load(tmp_path: Path) -> None: + h = Harness(tmp_path, start_timeout=5) + h.states["T0"] = [ + ("about:blank", "loading"), + ("https://portal.example/start", "loading"), + ("https://portal.example/start", "interactive"), + ] + h.service.open(h.create(), "https://portal.example/start") + assert h.state_calls == ["T0", "T0", "T0"] + assert h.created == [] # a tab at the URL that is still loading is waited for + + +def test_a_page_that_stays_loading_is_refused(h: Harness) -> None: + h.states["T0"] = [("https://portal.example/start", "loading")] + with pytest.raises(ChromeProfileError) as err: + h.service.open(h.create(), "https://portal.example/start") + assert err.value.code == "page_not_loaded" + assert h.created == [] + + +def test_an_unreachable_page_socket_is_retried(tmp_path: Path) -> None: + calls: list[str] = [] + + def flaky(port: int, target_id: str) -> tuple[str, str]: + calls.append(target_id) + if len(calls) < 3: + raise ConnectionRefusedError + return "https://portal.example/start", "complete" + + h = Harness(tmp_path, page_state=flaky, start_timeout=5) + assert h.service.open(h.create(), "https://portal.example/start")["open"] is True + assert len(calls) == 3 + + def test_open_without_a_url_checks_no_page(tmp_path: Path) -> None: def never(*_a: Any) -> Any: raise AssertionError("no page check without a URL") - h = Harness(tmp_path, json_list=never, json_new=never) + h = Harness(tmp_path, json_list=never, json_new=never, page_state=never) assert h.service.open(h.create())["open"] is True @@ -581,6 +666,78 @@ def test_devtools_file_parsing(tmp_path: Path) -> None: assert cp.read_devtools_active_port(tmp_path) == (51234, GUID) +def _serve_cdp(reply_frames: list[bytes]) -> tuple[int, dict[str, Any], Any]: + import threading + + server = socket.socket() + server.bind(("127.0.0.1", 0)) + server.listen(1) + got: dict[str, Any] = {} + + def serve() -> None: + conn, _ = server.accept() + data = b"" + while b"\r\n\r\n" not in data: + data += conn.recv(4096) + got["request"] = data + conn.sendall(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n\r\n") + got["frame"] = conn.recv(4096) + for frame in reply_frames: + conn.sendall(frame) + conn.close() + server.close() + + thread = threading.Thread(target=serve) + thread.start() + return server.getsockname()[1], got, thread + + +def _server_frame(message: dict[str, Any], opcode: int = 0x1) -> bytes: + import json + + body = json.dumps(message).encode() + if len(body) < 126: + return bytes([0x80 | opcode, len(body)]) + body + return bytes([0x80 | opcode, 126]) + len(body).to_bytes(2, "big") + body + + +def test_page_state_evaluates_href_and_ready_state_on_the_page_socket() -> None: + import json + + value = json.dumps(["chrome-error://chromewebdata/", "complete"]) + frames = [ + bytes([0x89, 0]), # a ping is skipped + _server_frame({"method": "Runtime.executionContextCreated", "params": {"x": "y" * 200}}), + _server_frame({"id": 1, "result": {"result": {"type": "string", "value": value}}}), + ] + port, got, thread = _serve_cdp(frames) + state = cp.cdp_page_state(port, "ABCDEF0123") + thread.join(5) + assert state == ("chrome-error://chromewebdata/", "complete") + request = got["request"].decode() + assert request.startswith("GET /devtools/page/ABCDEF0123 HTTP/1.1") + assert "origin:" not in request.lower() + frame = got["frame"] + assert frame[0] == 0x81 and frame[1] & 0x80 + length, start = frame[1] & 0x7F, 2 + if length == 126: + length, start = int.from_bytes(frame[2:4], "big"), 4 + mask, body = frame[start : start + 4], frame[start + 4 : start + 4 + length] + sent = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(body))) + assert sent["method"] == "Runtime.evaluate" + assert "location.href" in sent["params"]["expression"] + assert "document.readyState" in sent["params"]["expression"] + + +def test_page_state_refuses_a_bad_target_id_and_a_bad_reply() -> None: + with pytest.raises(ValueError): + cp.cdp_page_state(1, "../browser/x") + port, _got, thread = _serve_cdp([_server_frame({"id": 1, "result": {"result": {}}})]) + with pytest.raises(ValueError): + cp.cdp_page_state(port, "ABC") + thread.join(5) + + def test_browser_close_frame_is_a_masked_cdp_message_without_origin() -> None: import json import threading