Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/desktop/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/desktop/docs/CHROME_PROFILE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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. |

Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/openadapt_desktop/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@
+-- backends/ Storage backend plugins
"""

__version__ = "0.33.0"
__version__ = "0.33.1"
231 changes: 219 additions & 12 deletions packages/desktop/openadapt_desktop/chrome_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
import hashlib
import json
import os
import re
import secrets
import shutil
import socket
Expand All @@ -53,7 +54,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

Expand Down Expand Up @@ -85,6 +86,7 @@
_DEVTOOLS_FILE = "DevToolsActivePort"
_START_TIMEOUT_S = 30.0
_CLOSE_TIMEOUT_S = 10.0
_PAGE_GRACE_S = 3.0
_MAX_NAME = 60


Expand Down Expand Up @@ -271,6 +273,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?<url>``: 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."""

Expand All @@ -294,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:
Expand All @@ -316,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))
Expand All @@ -332,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


Expand Down Expand Up @@ -361,6 +487,9 @@ 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,
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,
Expand All @@ -374,6 +503,9 @@ 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._page_state = page_state
self._clock = clock
self._sleep = sleep
self._start_timeout = start_timeout
Expand Down Expand Up @@ -553,6 +685,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)
Expand Down Expand Up @@ -588,6 +722,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
Expand Down Expand Up @@ -649,6 +785,77 @@ 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 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), 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:
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 "")
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:
raise ChromeProfileError(
"page_not_loaded",
"Chrome opened, but the page didn't load. Check the address and try again.",
)
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(
Expand Down
4 changes: 2 additions & 2 deletions packages/desktop/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/desktop/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading