Skip to content

fix(codex): recover detached GUI processes on macOS launch - #10246

Open
loopx-agent wants to merge 1 commit into
mainfrom
codex/native-app-headless-recovery-20261206
Open

loopx-agent wants to merge 1 commit into
mainfrom
codex/native-app-headless-recovery-20261206

Conversation

@loopx-agent

Copy link
Copy Markdown
Collaborator

Problem

When macOS restarts WindowServer (or resets a GUI login session), Codex App instances launched by open_codex() with start_new_session=True can stay alive in ps as detached headless processes with no Launch Services / NSRunningApplication registration.

Previously:

  1. FOCUS checked if (!app || app.isTerminated), which does not catch JXA's truthy [id nil] wrapper returned by NSRunningApplication.runningApplicationWithProcessIdentifier(...) for an unregistered PID.
  2. FOCUS then fell through to sending an AppleEvent / calling app.activateWithOptions(3) on [id nil], causing osascript to error or crash and callers (such as personal-apps) to surface an opaque failure while leaving the app unlaunchable.
  3. Even after killing a detached process or after a crash/hostname change, stale Chromium SingletonLock / SingletonSocket / SingletonCookie symlinks in the frontend profile directory could block clean relaunch.

Solution

  • FOCUS JXA nil detection: Check app.isNil() explicitly before sending AppleEvents and return "detached" when no Launch Services registration exists (or the app is terminated), avoiding crashes on dead-session PIDs.
  • Fail-closed live focus errors: Convert non-zero osascript exit codes on live GUI instances into an actionable ValueError without terminating live apps.
  • Safe detached process recovery (_recover_detached):
    • Inspects uid, elapsed time (etime), and exact executable via /bin/ps before taking action.
    • Waits through a 10s startup grace window (DETACHED_GRACE_SECONDS) for freshly started processes that have not yet finished checking into Launch Services.
    • Re-verifies frontend ownership, current UID, and executable match before sending graceful SIGTERM (never SIGKILL).
    • Tolerates transient dying helper children during the 5s post-SIGTERM shutdown wait and fails closed if the detached process refuses to exit.
    • Records recovered_detached_pid in the returned launch payload when recovery occurred.
  • Stale Chromium Singleton* symlink cleanup (_clear_stale_singleton_locks): Under the exclusive launch.lock, after confirming running(exe, spec) is None, removes only symlinked SingletonLock / SingletonSocket / SingletonCookie entries inside spec['frontend'] while preserving all regular files.
  • Version alignment: Bump loopx-codex-provider-routing manifests (pyproject.toml, extension.toml, native-extension.toml, __init__.py) from 0.15.10 to 0.15.11.

Verification

  • uv run --extra test python -m pytest -v tests/presentation/test_native_app.py tests/presentation/test_native_account_store.py tests/presentation/test_native_accounts_install.py packages/loopx-codex-provider-routing/tests/ — 120 passed, 1 skipped, 30 subtests passed (including real macOS JXA absent-PID check and built wheel install check).
  • uv run --extra test ruff check on changed Python files — All checks passed.
  • Manifest version alignment check across all 4 files — 0.15.11 aligned.
  • loopx check --scan-path ... — public boundary scan clean.
  • loopx canary premerge --from-git-diff --git-diff-base origin/main — passed.

After a macOS WindowServer restart or login session reset, Codex processes launched with start_new_session=True can remain alive in ps without a Launch Services / NSRunningApplication registration. Previously, FOCUS only checked !app || app.isTerminated (which misses JXA's truthy [id nil] wrapper), causing osascript to fail or crash and blocking launcher recovery.

Detect nil/terminated NSRunningApplication cleanly in FOCUS, distinguish freshly starting processes via an elapsed-time grace window, verify current-user and executable ownership before sending graceful SIGTERM, tolerate transient dying helper children while waiting for exit, clear stale Chromium Singleton* symlinks only after confirming zero frontend owners, and fail closed with actionable ValueError diagnostics when focusing a live GUI app fails or a detached process does not exit.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer: model_agent · Gemini · Google · self_reported

Approval conclusion (author-owned PR; GitHub blocks formal self-approval)

动机 / Motivation

受影响对象为macOS 上通过 personal-apps 或 native_app.open_codex() 启动本地 Codex 应用的用户。改造前,macOS WindowServer 重启后旧进程虽留在 ps 中但已脱离 Launch Services,点击快捷方式会因 JXA 未拦截 [id nil] 导致 osascript 失败/崩溃并弹出不透明错误,同时残留 SingletonLock 符号链接阻碍冷启动;改造后,FOCUS 稳定返回 detached,启动器在核验归属后发送温和 SIGTERM、清理残留 Singleton* 符号链接并拉起新前台窗口。

可观测改进:失联旧进程在校验归属后被温和回收并重新拉起(返回字段附带 recovered_detached_pid),活窗口聚焦失败则直接返回可读 ValueError 且绝不误杀活应用。

本 PR 明确边界:不修改账号切换时 account_idle 的禁杀边界,不自动升级到 SIGKILL,也不改变 dry_run 只读预览语义。

改动思路 / Approach

入口保持在 open_codex() 的独占 launch.lock 内,避免并发双击竞态。将 JXA 状态探测、/bin/ps 归属校验、失联进程温和回收与残留 Singleton* 符号链接清理全部收口在现有 native_app.py 的独占 launch.lock 生命周期内,不引入循环依赖或新增持久化状态。

当前 PR 边界:单模块 macOS 启动恢复边界(packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_app.py 及 4 处 0.15.11 清单版本对齐)。

控制流在检测到已有进程后分为四条路径:

  1. 活窗口正常聚焦:_focus_running() 运行 FOCUS 脚本,校验 NSRunningApplication 存在且未终止后发送 rapp 并激活窗口,返回 focused。
  2. 活窗口聚焦失败(fail-closed):osascript 非零退出统一转成明确 ValueError,绝不向活窗口发信号。
  3. 失联无 GUI 进程温和回收:当 FOCUS 返回 detached 时,_recover_detached() 通过 /bin/ps -o uid=,etime=,command= 校验当前用户 UID、运行时间与精确可执行文件路径;若进程年龄不足 10 秒(DETACHED_GRACE_SECONDS),先轮询等待 Launch Services 完成注册并在注册后直接聚焦;超过宽限期仍失联则复核归属后仅发 SIGTERM,在 5 秒窗口内等待退出并容忍临终子进程瞬态残留,超时则 fail-closed。
  4. 零持有者冷启动前清锁:在独占锁下确认 running(exe, spec) is None 后,_clear_stale_singleton_locks() 仅解除 SingletonLock、SingletonSocket、SingletonCookie 三个符号链接,完整保留普通文件。

在复用决策上,检索了 native_host.py 的 process_identity 与 native_app.py 现有 /bin/ps 逻辑:native_app.py 是被 native_host.py 和外部 personal-apps 导入的底层模块,避免反向导入产生环依赖,复用同一 /bin/ps 风格是合理切分。

具体改动 / Changes

本次 PR 修改 6 个文件(+372 / -10 行):生产代码为 packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/native_app.py(+146 / -6)及 4 处清单版本对齐至 0.15.11(pyproject.toml、extension.toml、native-extension.toml、__init__.py),配套单测在 tests/presentation/test_native_app.py(+222 / -0)。

关键代码讲解

  • FOCUS 与 _focus_running(native_app.py:140, native_app.py:196):在发送 AppleEvent 前显式检查 app.isNil() 与 app.isTerminated,失联时直接返回 detached 避免 JXA 空对象异常与 osascript 崩溃;活窗口激活失败则转为可读 ValueError。
  • _inspect_owner_process 与 _parse_etime(native_app.py:177, native_app.py:157):核验 uid == os.getuid()、命令行前缀精确匹配 exe(兼容路径空格)并解析 MM:SS / HH:MM:SS / D-HH:MM:SS 运行时长,格式异常返回 None 触发 fail-closed。
  • _recover_detached(native_app.py:221):实现 10 秒新启动宽限轮询、发送 SIGTERM 前双重归属复核、5 秒退出等待(容忍根进程已退后的临终辅助子进程瞬态 ValueError)以及超时 fail-closed。
  • _clear_stale_singleton_locks 与 open_codex(native_app.py:208, native_app.py:366):在零持有者条件下仅删除三个 Singleton* 符号链接(用 is_symlink() 覆盖悬空链接),恢复拉起时附加 recovered_detached_pid 保持原有 action: "launch-requested" 兼容。

对主干的风险 / Risks

  • 误杀边界:仅当无 Launch Services 注册、超过 10 秒宽限期且 UID/可执行路径/--user-data-dir 全部匹配时才发 SIGTERM;活窗口聚焦失败、归属变更与权限不足均严格 fail-closed。
  • 残留风险:若失联进程卡死在不可中断状态或忽略 SIGTERM,本实现有意不升级到 SIGKILL,5 秒后会抛出可读 ValueError 交由用户本地处理;自动化单测通过 mock 验证多分支并在 macOS 上实测了真实 osascript 缺省 PID 返回 detached,真实 WindowServer 崩溃无法在单测内触发重启。
  • 兼容性:正常聚焦、冷启动返回结构与 dry_run 只读语义完全向后兼容,4 个包清单版本已同步对齐为 0.15.11。

我的整体评价 / Verdict

本 PR 对长期运行稳定性(long_horizon)与桌面启动体验(user_experience)均有明确正向改善,改动体量与风险相称;视觉评审说明:本次改动仅涉及 native_app.py 后端进程启动恢复与单元测试,未修改任何渲染页面或视觉呈现界面。 语义上保持 local_only,未引入新全局词表或持久化状态,仅复用既有 4 处清单对齐约束。

已在精确 head 820cec36b2e3792e17499a2be93d249ac4dd81d9 完成本地验证:pytest 120 passed / 1 skipped / 30 subtests passed(含 wheel 独立安装与 macOS 真实 osascript 检查)PASS,ruff check PASS,4 处 0.15.11 版本对齐 PASS,loopx check 公开边界扫描 PASS,loopx canary premerge PASS(远程 CI 按 Goal 配置 wait_for_ci=false 不等待)。无阻塞项,结论为通过。

English verdict: APPROVE — exact head 820cec36b2e3792e17499a2be93d249ac4dd81d9 cleanly fixes macOS detached GUI process recovery and stale Singleton symlink cleanup with strict fail-closed ownership checks, aligned 0.15.11 manifests, and passing local validation (120 pytest tests + 30 subtests, ruff, boundary scan, and canary premerge); no blocking findings.

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

[P2] 回收前复查老进程是否恢复 GUI。进程已经运行超过 10 秒时,初次 detached 后直接走所有权复核与 SIGTERM。若同 PID 在此期间重新注册到 GUI,归属复核仍会成功。受控入口给定第一次 detached、随后可 focused,旧进程路径只读取一次 GUI 并请求 SIGTERM、启动新进程。可用会话有被中断的风险。 最后一次复查归属后,在请求 SIGTERM 前重新确认 GUI 状态,注册恢复则聚焦并返回。补上进程年龄已超宽限且登记在复查期间恢复的入口用例。 受审位置

动机 / Motivation

在 macOS 从本机启动器重新聚焦或启动 Codex App 的用户。 WindowServer 重置或 GUI 重新登记时,进程仍在 ps 中,首个焦点请求可能看到短暂的 detached。 确实失联的进程可恢复。已经重新注册的可用窗口应继续聚焦并保留原会话工作。 本轮验证真实 macOS 的缺 PID 焦点脚本及本地打包相关测试,竞态用合成进程状态复现。 本机执行实际 JXA 缺 PID 用例。晚注册竞态来自合成进程表和焦点返回,真实 WindowServer 重置未实测。 验收依据

改动思路 / Approach

利用既有 App 启动入口和 launch.lock,在焦点、进程归属及重启路径上明确交接。GUI 登记和 PID 持有关系分别观测。 改动覆盖原生焦点探测、收回同 profile 的进程、Chromium 残留链接处理、回归用例及四份发布版本声明。 当前 PR · 当前提交既有评审

具体改动 / Changes

  • detached_recovery。系统登记缺失后可识别失联并恢复。

  • normal_focus。可用 GUI 应聚焦本实例。

  • late_registration。回收前已经重新登记的进程仍能保留。

  • FOCUS。在真实 JXA 探测中识别没有 GUI 注册的 PID。 受审实现

  • _inspect_owner_process。复查当前 PID 所属用户、可执行文件和存活时间。 受审实现

  • _recover_detached。新进程继续等待 GUI 注册。老进程路径排队退出并允许重新启动。 受审实现

  • _clear_stale_singleton_locks。当路径可用时清理旧 Chromium 符号链接。 受审实现

  • open_codex。保留预检和 launch.lock,聚焦或回收后确认子进程。 受审实现

  • test_focus_script_reports_detached_for_absent_pid_on_macos。在 macOS 用实际 osascript 验证缺少 GUI 登记的返回。 受审实现

  • 0.15.11。同包代码、扩展和原生扩展元数据显示同一版本。 受审实现

对主干的风险 / Risks

以相同合成旧进程状态调用基线入口,首次 JXA 登记缺失时返回焦点异常,signal 与新启动均无。 原生 App、account store、安装和 provider routing 套件共 120 项与 30 个子测试通过,1 项跳过。受控入口进程年龄一秒时会重读 GUI,确认恢复后聚焦原 PID,无 signal 或新启动。 现有测试保持普通焦点错误、UID 不符、路径不符以及进程拒绝退出时的失败出口。正常符号链接清理保留普通文件。 git diff --check 无输出。实际 WindowServer 重置及已有 App 会话未重启。

我的整体评价 / Verdict

要求修改精确提交 820cec3。最后一次复查归属后,在请求 SIGTERM 前重新确认 GUI 状态,注册恢复则聚焦并返回。补上进程年龄已超宽限且登记在复查期间恢复的入口用例。 新提交应重跑本轮入口反例。

English verdict: REQUEST_CHANGES at 820cec3. A long-lived process can register with the GUI after the first detached response. The candidate only rechecks GUI registration for fresh processes and can signal the now-focusable session. Recheck registration immediately before termination.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant