Peach: Local-first video metadata scraper and media manager.
feat(tray): macOS 菜单栏由 launchd 在异常退出后拉起
longmeidao908a286664d9
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex be749ac45..606261aa3 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -71,6 +71,36 @@ sudo /usr/bin/xattr -rd com.apple.quarantine "/Applications/Peach.app"版本提交触发 Release 演练,在 Apple Silicon 与 Intel 原生 runner 分别构建,再由干净 runner 下载并挂载 DMG,验证签名、架构和独立运行。标签核对同一提交的成功演练与摘要,发布已验收的相同文件。两种 DMG 与 Windows 安装包全部通过后,才一同上传到 GitHub 预发布,统一生成 SHA-256 清单。手动运行工作流只验收候选制品,不创建 Release;推送普通提交不会触发安装包构建。发版从只读审阅和依赖检查开始,重型验证前完成复核并冻结输入;集成、运行核验与定版按[发版检查](TESTING.md#每次发版检查)执行,打标签统一使用 `scripts/release_tag.py`。+### macOS 异常退出恢复++菜单栏的异常退出恢复交给 launchd,不移植 Windows 的监视器。配置页打开「开机自启」后,`~/Library/LaunchAgents/io.github.longmeidao.peach.tray.plist` 写入 `KeepAlive = {SuccessfulExit = false}` 与 `ThrottleInterval = 30`;源码部署的 `install_macos_agent.py install` 写同一份设置,来源是 `src/peach/desktop_startup.py`。++| 退出方式 | 退出结果 | launchd |+| --- | --- | --- |+| 菜单「退出 Peach」 | 退出码 0 | 不拉起 |+| 注销、关机 | 会话结束 | 不拉起 |+| 已有一个 Peach 在运行 | 退出码 0 | 不拉起 |+| 设置文件无效、迁移失败等启动失败 | 由 launchd 启动时按 0 退出,原因写进 `logs/tray.log` | 不拉起 |+| 崩溃(`SIGSEGV`、`SIGBUS`、`SIGABRT` 等) | 信号终止 | 拉起 |+| 强制退出、`kill` | 信号终止 | 拉起 |++首次设置未完成时菜单栏照常运行,退出方式同上。启动失败重来结果相同,按非 0 退出会让 launchd 反复重试,所以托盘先核对 launchd 报的 pid 是自己,再按 0 退出;终端里手动运行仍返回 1。菜单回调里的 Python 异常由 PyObjC 事件循环弹出错误面板:选「继续」照常运行,选「退出」按 0 退出,都不触发拉起。++运行满 30 秒后崩溃会立即拉起;启动后 30 秒内反复崩溃时,每 30 秒最多拉起一次,launchd 不限次数。拉起后的菜单栏沿用启动项的 `--silent` 或 `--show`,后者会再打开一次浏览器。子服务与托盘同属一个进程组,按 launchd 默认行为在托盘退出时一并结束,新托盘重新启动服务。要彻底停止,用菜单退出,或运行 `launchctl bootout gui/$(id -u)/io.github.longmeidao.peach.tray`。++恢复只覆盖 launchd 启动的进程:++- 开机自启关闭时写 `KeepAlive = false`。`SuccessfulExit` 隐含 `RunAtLoad`,保留它会让关掉的自启在登录时照样启动,所以此时没有恢复。+- 独立包双击 `Peach.app` 由 LaunchServices 启动,不归 launchd 管理,崩溃后需要手动重开。登录时由启动项拉起的那一次有恢复;从菜单退出后再双击打开,到下次登录前都没有恢复。Peach 不为双击启动另设监视进程。+- 源码外壳双击执行 `launchctl kickstart`,进程归 launchd,开机自启开着时同样恢复。++launchd 使用登录时载入的 plist。升级后托盘第一次启动时,已开启的旧启动项会就地补上这两项,其余键不变;在配置页保存开机自启也会重写。两种方式都在下次登录生效。要立即生效,先从菜单退出,再运行:++```sh+launchctl bootout gui/$(id -u)/io.github.longmeidao.peach.tray+launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/io.github.longmeidao.peach.tray.plist+```+### GitLab 发布与下载后端GitLab 兼容平台使用 `.gitlab-ci.yml`。唯一版本入口支持 `--gitlab-host` 指定主机,默认入口使用 GitHub。主线发布判据要求同一提交最新的 push 流水线成功,且 Linux、Windows、macOS 和 wheel 验收任务全部成功;缺少原生系统任务时拒绝打标签。主线上的三个平台验收只跑改动域与平台敏感用例([ADR-0119](adr/0119-mainline-changed-scope-release-full-suite.md))。版本提交 `chore(release): 版本 X` 的主线流水线同时是发布演练:三平台全量、媒体工具、Windows 与 macOS 构建、Windows 冒烟和 Docker 镜像都跑一遍,只是不发布。`--ship` 等演练全部成功才打标签;标签流水线核对同一提交的演练已通过,只重新构建并发布([ADR-0121](adr/0121-release-rehearsal-and-atomic-publication.md))。GitHub 的 `release.yml` 用同一套判据,迁回 GitHub 时不用改流程。CLI 传输复用官方 glab,不在仓库或命令参数里存访问令牌。@@ -679,7 +709,7 @@ Windows 托盘在取得单实例锁后启动独立监视器。监视器用 Win32菜单退出、更新、卸载、外部停止消息和系统会话结束都会登记退出意图并停止监视器。正常重启由重启脚本负责拉起,监视器不参与依赖同步与换包。`tray-lifecycle.log` 每行是一条 JSON,包含 UTC 时间、实例标识、托盘及监视器 PID、启动父进程、退出意图、外部消息发送者 PID、异常退出码和恢复结果。强制结束进程时,记录的操作者为 `unknown`,不能从退出码判断是谁关闭了它。-监视器与托盘共用当前用户权限,不注册计划任务或 Windows 服务。监视器自身被结束、整棵进程树被结束或系统关机时不能自动恢复。监视器启动失败写入 `tray.log`;日志不可写时保留退出和服务清理行为。macOS 沿用 LaunchAgent 的启动行为。+监视器与托盘共用当前用户权限,不注册计划任务或 Windows 服务。监视器自身被结束、整棵进程树被结束或系统关机时不能自动恢复。监视器启动失败写入 `tray.log`;日志不可写时保留退出和服务清理行为。macOS 由 launchd 负责,见 [macOS 异常退出恢复](#macos-异常退出恢复)。适用于代码已经在检出里、只需要让运行中的托盘重新加载、不换二进制的情况。diff --git a/scripts/install_macos_agent.py b/scripts/install_macos_agent.pyindex 3fb8dd6ef..919b3f3e9 100644--- a/scripts/install_macos_agent.py+++ b/scripts/install_macos_agent.py@@ -36,6 +36,7 @@ if str(SRC_DIR) not in sys.path:from peach.appid import LEGACY_MACOS_LAUNCH_AGENT_LABELS, MACOS_LAUNCH_AGENT_LABELfrom peach.config import LOG_DIR, PROJECT_ROOT+from peach.desktop_startup import launch_agent_supervisionLABEL = MACOS_LAUNCH_AGENT_LABEL@@ -57,8 +58,8 @@ def build_plist(tray: Path) -> dict:# 直接跑目标程序,中间不能有 exec 跳板,否则菜单栏项注册不上。"ProgramArguments": [str(tray)],"RunAtLoad": True,- # 菜单栏项是用户主动退出的,不要自动拉回来。- "KeepAlive": False,+ # 从菜单退出不拉回来,崩溃才拉回来;与设置页写的登录启动项同一份设置。+ **launch_agent_supervision(True),"ProcessType": "Interactive",# launchd 给的 PATH 只有 /usr/bin:/bin:/usr/sbin:/sbin,找不到 Homebrew 的# ffmpeg/ffprobe,转码和抽帧会静默变成「不可用」。diff --git a/src/peach/desktop_startup.py b/src/peach/desktop_startup.pyindex da027b0b9..6a2baab0c 100644--- a/src/peach/desktop_startup.py+++ b/src/peach/desktop_startup.py@@ -247,6 +247,54 @@ def desktop_snapshot(config) -> dict:return {"desktop": False, "desktop_message": "桌面快捷方式状态未取得"}+#: launchd 只在菜单栏项异常结束时把它拉回来。从菜单「退出 Peach」退出码是 0,不拉起;+#: 崩溃和被信号结束(含强制退出)都算异常。不该重试的启动失败由托盘自己按 0 退出,见+#: `peach.tray.failure_exit_code`。+MACOS_KEEP_ALIVE = {"SuccessfulExit": False}+#: 两次拉起之间的最短秒数。跑满这段时间之后崩溃会立即拉起;它只拉开循环的间隔,不封顶次数。+MACOS_THROTTLE_INTERVAL = 30+++def launch_agent_path() -> Path:+ return Path.home() / "Library/LaunchAgents" / f"{MACOS_LAUNCH_AGENT_LABEL}.plist"+++def launch_agent_supervision(enabled: bool) -> dict:+ """LaunchAgent 的异常退出恢复设置。++ `SuccessfulExit` 隐含 `RunAtLoad`:launchd 要先跑一次才有退出码可判。开机自启关着时+ 写成 `False`,否则关了自启照样登录即起。+ """+ return {"KeepAlive": dict(MACOS_KEEP_ALIVE) if enabled else False,+ "ThrottleInterval": MACOS_THROTTLE_INTERVAL}+++def _launch_agent(program: Path) -> tuple[Path, dict]:+ path = launch_agent_path()+ entry = plistlib.loads(path.read_bytes()) if path.is_file() else {}+ if entry.get("ProgramArguments") and Path(entry["ProgramArguments"][0]).resolve() != program.resolve():+ raise ValueError("启动项属于另一份 Peach 安装")+ return path, entry+++def refresh_launch_agent(config) -> bool:+ """已开启的 LaunchAgent 缺当前的恢复设置时就地补上,返回是否改写。++ 托盘每次启动调一次,升级后的第一次启动就把旧版留下的 `KeepAlive=False` 换掉;其余键+ 原样保留。launchd 用的仍是登录时载入的那份,改动下次登录生效。+ """+ if sys.platform != "darwin":+ return False+ program, _, _ = target(config)+ path, entry = _launch_agent(program)+ wanted = launch_agent_supervision(True)+ if not entry.get("RunAtLoad") or all(entry.get(key) == value for key, value in wanted.items()):+ return False+ entry.update(wanted)+ atomic_write_text(path, plistlib.dumps(entry).decode("utf-8"))+ return True++def snapshot(config=None) -> dict:config = config or settings_file.load_config()if sys.platform not in {"win32", "darwin"}:@@ -263,10 +311,7 @@ def snapshot(config=None) -> dict:enabled = entry["enabled"]silent = "--show" not in entry.get("arguments", "") if enabled else bool(preference.get("silent", True))else:- path = Path.home() / "Library/LaunchAgents" / f"{MACOS_LAUNCH_AGENT_LABEL}.plist"- entry = plistlib.loads(path.read_bytes()) if path.is_file() else {}- if entry.get("ProgramArguments") and Path(entry["ProgramArguments"][0]).resolve() != program.resolve():- raise ValueError("启动项属于另一份 Peach 安装")+ _, entry = _launch_agent(program)enabled = bool(entry.get("RunAtLoad", False))silent = "--show" not in entry.get("ProgramArguments", []) if enabled else bool(preference.get("silent", True))return {"available": program.is_file(), "enabled": enabled, "silent": silent,@@ -305,12 +350,9 @@ def save(config, *, enabled: bool, silent: bool, desktop: bool, executable: Pathdirectory=str(directory), expected=existing.get("target", ""))elif sys.platform == "darwin":args = [*args, "--silent" if silent else "--show"]- path = Path.home() / "Library/LaunchAgents" / f"{MACOS_LAUNCH_AGENT_LABEL}.plist"- entry = plistlib.loads(path.read_bytes()) if path.is_file() else {}- if entry.get("ProgramArguments") and Path(entry["ProgramArguments"][0]).resolve() != program.resolve():- raise ValueError("启动项属于另一份 Peach 安装")+ path, entry = _launch_agent(program)entry.update(Label=MACOS_LAUNCH_AGENT_LABEL, ProgramArguments=[str(program), *args], RunAtLoad=enabled,- KeepAlive=False, ProcessType="Interactive", WorkingDirectory=str(directory))+ ProcessType="Interactive", WorkingDirectory=str(directory), **launch_agent_supervision(enabled))entry["EnvironmentVariables"] = {**entry.get("EnvironmentVariables", {}), "PEACH_DATA_ROOT": str(config.data_root),"PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"}atomic_write_text(path, plistlib.dumps(entry).decode("utf-8"))diff --git a/src/peach/tray.py b/src/peach/tray.pyindex a557df124..918b9f80b 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -24,7 +24,7 @@ import httpximport pystrayfrom PIL import Image-from . import error_reporting, ledger_backups, log_retention, onboarding, runtime_prepare, settings_file+from . import desktop_startup, error_reporting, ledger_backups, log_retention, onboarding, runtime_prepare, settings_filefrom .appid import MACOS_LAUNCH_AGENT_LABELfrom .certs import ensure_certificatefrom .distribution import standalone@@ -1865,12 +1865,29 @@ def log_to_file(path: Path) -> logging.Handler | None:return handler+def failure_exit_code() -> int:+ """托盘自己判定失败时的退出码;launchd 名下的 macOS 菜单栏项按 0 退出。++ LaunchAgent 写的是 `KeepAlive = {SuccessfulExit: false}`(见+ `desktop_startup.MACOS_KEEP_ALIVE`),非 0 退出会被重新拉起。走到这里的是配置、迁移、+ 建菜单这类失败,原因已经记下,重来结果相同,拉起只会每隔 ThrottleInterval 再失败一次。+ PyObjC 的事件循环自己接住菜单回调里的异常,所以要 launchd 恢复的是崩溃和信号终止,+ 不经过这里。终端里手跑和 Windows 仍得到 1。+ """+ if sys.platform != "darwin":+ return 1+ try:+ return 0 if launchd_owns_this_process() else 1+ except OSError:+ return 1++def main(argv: list[str] | None = None) -> int:try:return _main(argv)except Exception as exc:show_message("Peach 启动失败", error_reporting.failure_details("tray-startup", exc), error=True)- return 1+ return failure_exit_code()def _main(argv: list[str] | None = None) -> int:@@ -1919,6 +1936,11 @@ def _main(argv: list[str] | None = None) -> int:remember_installation_data_root(config)except (OSError, RuntimeError):logging.getLogger(__name__).warning("更新后的数据目录位置未能保存", exc_info=True)+ try:+ if desktop_startup.refresh_launch_agent(config):+ LOGGER.info("登录启动项已补上异常退出恢复,下次登录生效")+ except (OSError, ValueError):+ LOGGER.warning("登录启动项的异常退出恢复未能更新", exc_info=True)if sys.platform == "win32":lifecycle = Lifecycle(config.directory("state"), config.directory("logs"),config.data_root, PROJECT_ROOT)@@ -1950,7 +1972,7 @@ def _main(argv: list[str] | None = None) -> int:LOGGER.exception("托盘运行失败")if not os.environ.get("PEACH_TRAY_RECOVERIES"):show_message("Peach 启动失败", error_reporting.failure_details("tray-runtime", exc), error=True)- return 1+ return failure_exit_code()finally:if lifecycle is not None:lifecycle.exited(exit_code)diff --git a/tests/test_desktop_settings.py b/tests/test_desktop_settings.pyindex 16176f261..3a5e7ea70 100644--- a/tests/test_desktop_settings.py+++ b/tests/test_desktop_settings.py@@ -8,6 +8,7 @@ import subprocessimport sysimport threadingfrom pathlib import Path+import plistlibimport tempfilefrom types import SimpleNamespaceimport unittest@@ -115,6 +116,51 @@ class DesktopSettingsTests(unittest.TestCase):with self.assertRaises(ValueError):desktop_startup.save(self.config, enabled=False, silent=True, desktop=None)+ def _macos_agent(self):+ agent = self.root / 'LaunchAgents/agent.plist'+ agent.parent.mkdir()+ (self.data / 'state').mkdir(exist_ok=True)+ for patcher in (patch.object(desktop_startup, 'sys', SimpleNamespace(platform='darwin', executable=sys.executable)),+ patch.object(desktop_startup, 'launch_agent_path', return_value=agent)):+ patcher.start()+ self.addCleanup(patcher.stop)+ return agent++ def test_macos_launch_agent_relaunches_only_after_abnormal_exit(self):+ agent = self._macos_agent()+ program = self.program / 'Peach.exe'+ desktop_startup.save(self.config, enabled=True, silent=True, desktop=False, executable=program)+ entry = plistlib.loads(agent.read_bytes())+ self.assertIs(entry['RunAtLoad'], True)+ self.assertEqual(entry['KeepAlive'], {'SuccessfulExit': False}, '菜单「退出 Peach」退出码 0,不该被拉回来')+ self.assertGreaterEqual(entry['ThrottleInterval'], 10)++ desktop_startup.save(self.config, enabled=False, silent=True, desktop=False, executable=program)+ entry = plistlib.loads(agent.read_bytes())+ self.assertIs(entry['RunAtLoad'], False)+ self.assertIs(entry['KeepAlive'], False, 'SuccessfulExit 隐含 RunAtLoad,关了自启还写它就会登录即起')++ def test_macos_upgrade_refreshes_an_enabled_launch_agent_in_place(self):+ agent = self._macos_agent()+ program = (self.program / 'Peach.exe').resolve()+ old = {'Label': 'old', 'ProgramArguments': [str(program), '--silent'], 'RunAtLoad': True,+ 'KeepAlive': False, 'StandardOutPath': '/tmp/peach.log'}+ agent.write_bytes(plistlib.dumps(old))+ with patch.object(desktop_startup, 'target', return_value=(program, [], self.program)):+ self.assertTrue(desktop_startup.refresh_launch_agent(self.config))+ entry = plistlib.loads(agent.read_bytes())+ self.assertEqual(entry, {**old, **desktop_startup.launch_agent_supervision(True)}, '其余键原样保留')+ self.assertFalse(desktop_startup.refresh_launch_agent(self.config), '已是当前写法就不再改写')++ disabled = {**old, 'RunAtLoad': False}+ agent.write_bytes(plistlib.dumps(disabled))+ self.assertFalse(desktop_startup.refresh_launch_agent(self.config))+ self.assertEqual(plistlib.loads(agent.read_bytes()), disabled, '自启关着时不碰')++ agent.write_bytes(plistlib.dumps({**old, 'ProgramArguments': [str(self.root / 'Other/Peach')]}))+ with self.assertRaisesRegex(ValueError, '另一份'):+ desktop_startup.refresh_launch_agent(self.config)+def test_configuration_actions_require_local_origin_and_uninstall_confirmation(self):from fastapi import FastAPIfrom fastapi.testclient import TestClientdiff --git a/tests/test_tray.py b/tests/test_tray.pyindex 655b875b8..2b0a4ba06 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -722,6 +722,67 @@ class LogRetentionAtStartupTests(unittest.TestCase):icon.run.assert_called_once_with()+class LaunchdRelaunchExitCodeTests(unittest.TestCase):+ """macOS LaunchAgent 写 `KeepAlive = {SuccessfulExit: false}`,非 0 退出就会被拉起。++ 配置、迁移这类失败重来结果相同;按非 0 退出,launchd 每隔 ThrottleInterval 就再试一次、+ 再失败一次。所以 launchd 名下的菜单栏项判定失败时按 0 退出,留给 launchd 的只剩崩溃。+ """++ def test_failures_exit_zero_only_for_the_launchd_owned_menu_bar(self):+ for platform, owned, expected in (("darwin", True, 0), ("darwin", False, 1), ("win32", True, 1)):+ with self.subTest(platform=platform, owned=owned), \+ mock.patch.object(tray_module.sys, "platform", platform), \+ mock.patch.object(tray_module, "launchd_owns_this_process", return_value=owned), \+ mock.patch.object(tray_module.settings_file, "load_config",+ side_effect=RuntimeError("config.toml 无效")), \+ mock.patch.object(tray_module, "show_message"):+ self.assertEqual(tray_main(["--silent"]), expected)++ def test_a_failed_migration_does_not_become_a_relaunch_loop(self):+ preparation = Mock()+ preparation.migrations.apply.return_value = Mock(failed=True, message="迁移失败")+ with tempfile.TemporaryDirectory() as directory, \+ mock.patch.object(tray_module.sys, "platform", "darwin"), \+ mock.patch.object(tray_module, "launchd_owns_this_process", return_value=True), \+ mock.patch.object(tray_module.settings_file, "load_config",+ return_value=settings_file.PeachConfig(Path(directory), Path(directory) / "config.toml")), \+ mock.patch.object(tray_module.error_reporting, "install"), \+ mock.patch.object(tray_module, "needs_setup", return_value=False), \+ mock.patch.object(tray_module, "SingleInstance") as instance, \+ mock.patch.object(tray_module, "handoff_tray", return_value=False), \+ mock.patch.object(tray_module, "enable_hidpi"), \+ mock.patch.object(tray_module.log_retention, "sweep", return_value=()), \+ mock.patch.object(tray_module, "log_to_file"), \+ mock.patch.object(tray_module.desktop_startup, "refresh_launch_agent",+ side_effect=ValueError("启动项属于另一份 Peach 安装")), \+ mock.patch.object(tray_module, "configured_service_specs", return_value=()), \+ mock.patch.object(tray_module, "ServiceManager") as manager, \+ mock.patch.object(tray_module, "tray_preparation", return_value=preparation), \+ mock.patch.object(tray_module, "run_macos_menu_bar") as menu, \+ mock.patch.object(tray_module, "show_message"), \+ self.assertLogs(level="WARNING") as logs:+ instance.return_value.is_running.return_value = False+ self.assertEqual(tray_main(["--silent"]), 0)+ menu.assert_not_called()+ manager.return_value.stop_owned.assert_called_once_with()+ instance.return_value.close.assert_called_once_with()+ self.assertTrue(any("异常退出恢复未能更新" in line for line in logs.output),+ "旧启动项刷新失败只记日志,不拦启动")++ def test_a_second_instance_exits_zero_without_asking_launchd(self):+ with tempfile.TemporaryDirectory() as directory, \+ mock.patch.object(tray_module.sys, "platform", "darwin"), \+ mock.patch.object(tray_module, "launchd_owns_this_process") as owned, \+ mock.patch.object(tray_module.settings_file, "load_config",+ return_value=settings_file.PeachConfig(Path(directory), Path(directory) / "config.toml")), \+ mock.patch.object(tray_module.error_reporting, "install"), \+ mock.patch.object(tray_module, "SingleInstance") as instance:+ instance.return_value.is_running.return_value = True+ self.assertEqual(tray_main(["--silent"]), 0)+ owned.assert_not_called()++class SourceSyncTests(unittest.TestCase):"""「同步开发进度」这条路径:拉到的代码要真的跑起来,托盘不能自己骗自己。"""@@ -1252,6 +1313,13 @@ class MacIdentityTests(unittest.TestCase):self.assertEqual(load_script("install_macos_agent").LABEL,appid.MACOS_LAUNCH_AGENT_LABEL)+ def test_source_agent_and_settings_page_share_one_relaunch_policy(self):+ """同一个标签有两个写 plist 的入口,两边的恢复设置不能各写各的。"""+ plist = load_script("install_macos_agent").build_plist(Path("/opt/peach/.venv/bin/peach-tray"))+ self.assertIs(plist["RunAtLoad"], True)+ self.assertEqual(plist["KeepAlive"], tray_module.desktop_startup.MACOS_KEEP_ALIVE)+ self.assertEqual(plist["ThrottleInterval"], tray_module.desktop_startup.MACOS_THROTTLE_INTERVAL)+def test_the_identifier_is_the_repository_owner_not_a_private_domain(self):"""下载者装上的东西不该带着维护者的私有域名(ADR-0023 第 4 阶段)。"""for value in (appid.MACOS_BUNDLE_ID, appid.MACOS_LAUNCH_AGENT_LABEL,