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
10 changes: 10 additions & 0 deletions packages/desktop/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
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.30.4"
__version__ = "0.30.5"
4 changes: 2 additions & 2 deletions packages/desktop/openadapt_desktop/approver_anchor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
61 changes: 61 additions & 0 deletions packages/desktop/openadapt_desktop/child_process.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 4 additions & 2 deletions packages/desktop/openadapt_desktop/flow_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions packages/desktop/openadapt_desktop/portal/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
12 changes: 7 additions & 5 deletions packages/desktop/openadapt_desktop/presentation_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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",
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.30.4",
"version": "0.30.5",
"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.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"
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.

2 changes: 1 addition & 1 deletion packages/desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
119 changes: 119 additions & 0 deletions packages/desktop/tests/test_engine/test_child_process.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion packages/desktop/tests/test_portal/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/uv.lock

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

Loading