diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index b40c7d4748..73a073e780 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,16 @@ # CHANGELOG +## v0.30.5 (2026-11-19) + +### Bug Fixes + +- **desktop**: On macOS 26, a step that starts a helper process (a replay, an + export, saving an approval key) could on rare occasions wait forever. The + engine now starts its helper processes in a way that cannot stall like that. + + + ## v0.30.4 (2026-11-19) ### Bug Fixes diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index 921fd950e7..c54484ed72 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.30.4" +__version__ = "0.30.5" diff --git a/packages/desktop/openadapt_desktop/approver_anchor.py b/packages/desktop/openadapt_desktop/approver_anchor.py index 6bed529add..7f3ec25bca 100644 --- a/packages/desktop/openadapt_desktop/approver_anchor.py +++ b/packages/desktop/openadapt_desktop/approver_anchor.py @@ -315,9 +315,9 @@ def _strip_mac_acl(path: Path) -> None: ``/Library/Application Support``.""" if sys.platform == "darwin": - import subprocess + from openadapt_desktop import child_process - subprocess.run(["/bin/chmod", "-h", "-N", str(path)], check=True, capture_output=True) + child_process.run(["/bin/chmod", "-h", "-N", str(path)], check=True, capture_output=True) def _write_posix(path: Path, payload: bytes, trusted_uids: frozenset[int]) -> None: diff --git a/packages/desktop/openadapt_desktop/child_process.py b/packages/desktop/openadapt_desktop/child_process.py new file mode 100644 index 0000000000..25448138bb --- /dev/null +++ b/packages/desktop/openadapt_desktop/child_process.py @@ -0,0 +1,61 @@ +"""Start the engine's child processes without forking the engine. + +On macOS, Python normally starts a child by forking and then, in the forked +copy, closing every inherited descriptor before it runs the program. If Tcl is +loaded in the engine (tkinter, which a dependency can import), Tcl starts a +thread in each forked copy, and on macOS 26 that copy can then stop for good +inside ``close()``. The engine would wait for it inside ``Popen`` with no +timeout that applies. + +Python starts the child with ``posix_spawn`` instead, with no forked copy at +all, when the program path is absolute and ``close_fds`` is false. Python opens +its own descriptors close-on-exec, so the child still inherits only its +standard streams. ``run`` and ``popen`` set that up and otherwise behave like +``subprocess.run`` and ``subprocess.Popen``. Windows has no fork and is left +alone. + +Do not pass ``cwd``, ``start_new_session``, ``preexec_fn`` or ``pass_fds`` +through these functions: each one makes Python fork again. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +from collections.abc import Mapping, Sequence +from typing import Any + +_FORKING_OPTIONS = ("cwd", "start_new_session", "preexec_fn", "pass_fds") + + +def _prepare(command: Sequence[Any], options: dict[str, Any]) -> list[Any]: + arguments = list(command) + if os.name != "posix": + return arguments + for name in _FORKING_OPTIONS: + if options.get(name): + raise ValueError(f"{name} would make Python fork to start {arguments[0]!r}") + options.setdefault("close_fds", False) + program = os.fspath(arguments[0]) + if not os.path.dirname(program): + environment: Mapping[str, str] | None = options.get("env") + search = environment.get("PATH") if environment is not None else None + found = shutil.which(program, path=search) + if found is None: + # Python would fork to find out the same thing. + raise FileNotFoundError(2, "No such file or directory", program) + arguments[0] = os.path.abspath(found) + return arguments + + +def run(command: Sequence[Any], **options: Any) -> subprocess.CompletedProcess: + """``subprocess.run`` for a command list, started without a fork on POSIX.""" + + return subprocess.run(_prepare(command, options), **options) + + +def popen(command: Sequence[Any], **options: Any) -> subprocess.Popen: + """``subprocess.Popen`` for a command list, started without a fork on POSIX.""" + + return subprocess.Popen(_prepare(command, options), **options) diff --git a/packages/desktop/openadapt_desktop/flow_bridge.py b/packages/desktop/openadapt_desktop/flow_bridge.py index c2ceab8dd9..7e15406f68 100644 --- a/packages/desktop/openadapt_desktop/flow_bridge.py +++ b/packages/desktop/openadapt_desktop/flow_bridge.py @@ -40,6 +40,8 @@ from loguru import logger +from openadapt_desktop import child_process + FLOW_BIN = "openadapt-flow" #: The exact Flow release Desktop is built and tested against. It equals the #: ``openadapt-flow`` pin in the ``build`` extra of pyproject.toml, which the @@ -608,8 +610,8 @@ class FlowBridge: def __init__( self, flow_bin: str = FLOW_BIN, - runner=subprocess.run, - popen=subprocess.Popen, + runner=child_process.run, + popen=child_process.popen, approver_keychain=None, ) -> None: self.flow_bin = flow_bin diff --git a/packages/desktop/openadapt_desktop/portal/service.py b/packages/desktop/openadapt_desktop/portal/service.py index 708676899b..63ae1ff515 100644 --- a/packages/desktop/openadapt_desktop/portal/service.py +++ b/packages/desktop/openadapt_desktop/portal/service.py @@ -72,6 +72,7 @@ from loguru import logger from packaging.version import InvalidVersion, Version +from openadapt_desktop import child_process from openadapt_desktop.auth.store import load_runner_credential from openadapt_desktop.flow_bridge import FLOW_BIN, _flow_command, _subprocess_env from openadapt_desktop.portal.flow_client import FlowConsoleClient, FlowConsoleUnavailable @@ -147,7 +148,7 @@ def _kill_tree(process: Any) -> None: """ pid = getattr(process, "pid", None) if _WINDOWS and isinstance(pid, int): - subprocess.run( + child_process.run( ["taskkill", "/F", "/T", "/PID", str(pid)], capture_output=True, check=False, @@ -267,7 +268,7 @@ def __init__( self, config: Any, *, - popen: Callable[..., Any] = subprocess.Popen, + popen: Callable[..., Any] = child_process.popen, clock: Callable[[], float] = time.monotonic, stops: Any = None, ) -> None: diff --git a/packages/desktop/openadapt_desktop/presentation_export.py b/packages/desktop/openadapt_desktop/presentation_export.py index c58a6aaf6e..8ad332532f 100644 --- a/packages/desktop/openadapt_desktop/presentation_export.py +++ b/packages/desktop/openadapt_desktop/presentation_export.py @@ -30,6 +30,8 @@ ) from PIL import Image, ImageDraw, ImageFont +from openadapt_desktop import child_process + TIMELINE_SCHEMA = "openadapt.control-overlay-timeline/v2" MAX_TIMELINE_BYTES = 8 * 1024 * 1024 MAX_FRAME_PIXELS = 33_177_600 # 8K UHD @@ -129,7 +131,7 @@ def presentation_export_status(capture_dir: Path) -> dict[str, object]: def _probe_video(ffprobe: Path, media: Path) -> tuple[int, int]: - completed = subprocess.run( + completed = child_process.run( [ str(ffprobe), "-v", @@ -161,7 +163,7 @@ def _probe_video(ffprobe: Path, media: Path) -> tuple[int, int]: def _runtime_supports_rawvideo(ffmpeg: Path) -> bool: - completed = subprocess.run( + completed = child_process.run( [str(ffmpeg), "-hide_banner", "-encoders"], check=False, capture_output=True, @@ -561,7 +563,7 @@ def export_presentation_video(capture_dir: Path) -> dict[str, object]: remuxed = presentation_dir / f".{token}.complete.mp4" output = presentation_dir / f"{plan.media_path.stem}-openadapt-{token[:8]}.mp4" - decoder = subprocess.Popen( + decoder = child_process.popen( [ str(ffmpeg), "-hide_banner", @@ -585,7 +587,7 @@ def export_presentation_video(capture_dir: Path) -> dict[str, object]: stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) - encoder = subprocess.Popen( + encoder = child_process.popen( [ str(ffmpeg), "-hide_banner", @@ -657,7 +659,7 @@ def export_presentation_video(capture_dir: Path) -> dict[str, object]: # Preserve a compatible source audio stream without decoding it. The # optional map also succeeds for silent recordings. - completed = subprocess.run( + completed = child_process.run( [ str(ffmpeg), "-hide_banner", diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 7780706f28..973325039e 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.30.4", + "version": "0.30.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.30.4", + "version": "0.30.5", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 85e457571d..e745cf456a 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.30.4", + "version": "0.30.5", "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 ae0d8710ad..1e3c998e14 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.30.4" +version = "0.30.5" 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 f2f1131668..8b6e23533a 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2504,7 +2504,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.30.4" +version = "0.30.5" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 35e0768139..ea3c689b65 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.30.4" +version = "0.30.5" 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 544eaae288..2a0c316a00 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.30.4", + "version": "0.30.5", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/tests/test_engine/test_child_process.py b/packages/desktop/tests/test_engine/test_child_process.py new file mode 100644 index 0000000000..61ccb8e436 --- /dev/null +++ b/packages/desktop/tests/test_engine/test_child_process.py @@ -0,0 +1,119 @@ +"""The engine starts its child processes without forking itself.""" + +from __future__ import annotations + +import ast +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from openadapt_desktop import child_process + +ENGINE = Path(child_process.__file__).resolve().parent +STARTERS = {"run", "Popen", "call", "check_call", "check_output", "getoutput", "getstatusoutput"} +OS_STARTERS = {"system", "popen", "fork", "forkpty", "posix_spawn", "posix_spawnp"} + + +def _direct_starts(path: Path) -> list[str]: + found = [] + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + # A type such as ``subprocess.Popen[str]`` in an annotation starts nothing. + annotations = [ + getattr(node, name) + for node in ast.walk(tree) + for name in ("annotation", "returns") + if getattr(node, name, None) is not None + ] + in_annotation = {id(inner) for outer in annotations for inner in ast.walk(outer)} + for node in ast.walk(tree): + if not isinstance(node, ast.Attribute) or not isinstance(node.value, ast.Name): + continue + if id(node) in in_annotation: + continue + if (node.value.id == "subprocess" and node.attr in STARTERS) or ( + node.value.id == "os" and (node.attr in OS_STARTERS or node.attr.startswith("spawn")) + ): + found.append(f"{path.relative_to(ENGINE)}:{node.lineno} {node.value.id}.{node.attr}") + return found + + +def test_engine_modules_start_processes_only_through_child_process() -> None: + """A direct subprocess.run or Popen in the engine would fork it on macOS.""" + + offenders = [ + entry + for path in sorted(ENGINE.rglob("*.py")) + if path.name != "child_process.py" + for entry in _direct_starts(path) + ] + assert offenders == [], "start these through openadapt_desktop.child_process: " + ", ".join( + offenders + ) + + +@pytest.fixture +def fork_refused(monkeypatch: pytest.MonkeyPatch) -> None: + if sys.platform == "win32" or not getattr(subprocess, "_USE_POSIX_SPAWN", False): + pytest.skip("this platform does not choose between fork and posix_spawn") + + def refuse(args, *_rest, **_named): + raise AssertionError(f"{args!r} would fork the engine") + + monkeypatch.setattr(subprocess, "_fork_exec", refuse) + + +def test_python_can_spawn_without_forking_on_macos() -> None: + if sys.platform == "darwin": + assert subprocess._USE_POSIX_SPAWN + + +def test_run_starts_a_child_without_forking(fork_refused: None) -> None: + done = child_process.run( + [sys.executable, "-c", "print('ready')"], capture_output=True, text=True, timeout=60 + ) + assert done.returncode == 0 and done.stdout.strip() == "ready" + with pytest.raises(AssertionError, match="would fork the engine"): + subprocess.run([sys.executable, "-c", "pass"]) + + +def test_popen_with_pipes_starts_a_child_without_forking(fork_refused: None) -> None: + process = child_process.popen( + [sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + out, _err = process.communicate("signed", timeout=60) + assert process.returncode == 0 and out.strip() == "SIGNED" + + +def test_a_program_named_without_a_directory_is_found_on_path(fork_refused: None) -> None: + done = child_process.run(["sh", "-c", "echo found"], capture_output=True, text=True, timeout=60) + assert done.stdout.strip() == "found" + environment = {**os.environ, "PATH": "/bin:/usr/bin"} + done = child_process.run( + ["sh", "-c", "echo found"], capture_output=True, text=True, timeout=60, env=environment + ) + assert done.stdout.strip() == "found" + + +@pytest.mark.skipif(sys.platform == "win32", reason="Windows has no fork") +@pytest.mark.parametrize("option", ["cwd", "start_new_session", "preexec_fn", "pass_fds"]) +def test_an_option_that_forces_a_fork_is_refused(option: str, tmp_path: Path) -> None: + value = { + "cwd": tmp_path, + "start_new_session": True, + "preexec_fn": lambda: None, + "pass_fds": (0,), + }[option] + with pytest.raises(ValueError, match=option): + child_process.run([sys.executable, "-c", "pass"], **{option: value}) + + +def test_a_missing_program_still_raises_file_not_found(fork_refused: None) -> None: + with pytest.raises(FileNotFoundError): + child_process.run(["openadapt-no-such-program"], capture_output=True) diff --git a/packages/desktop/tests/test_portal/test_service.py b/packages/desktop/tests/test_portal/test_service.py index 00a72dcc88..394ad663bd 100644 --- a/packages/desktop/tests/test_portal/test_service.py +++ b/packages/desktop/tests/test_portal/test_service.py @@ -484,7 +484,7 @@ def test_stopping_the_console_kills_the_whole_process_tree_on_windows( calls: list = [] monkeypatch.setattr(service_mod, "_WINDOWS", True) monkeypatch.setattr( - service_mod.subprocess, + service_mod.child_process, "run", lambda command, **kwargs: calls.append(command), ) diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 662c681c1f..b93d155de5 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.30.4" +version = "0.30.5" source = { editable = "." } dependencies = [ { name = "cryptography" },