Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat: ship the macOS menu bar item as an LSUIElement app bundle

Peach local maintenancebf6ab28ab661
diff --git a/.claude/skills/peach-cross-platform/SKILL.md b/.claude/skills/peach-cross-platform/SKILL.md
index 83fd6585e..43ce9c2e8 100644
--- a/.claude/skills/peach-cross-platform/SKILL.md
+++ b/.claude/skills/peach-cross-platform/SKILL.md
@@ -63,6 +63,11 @@ macOS 的 FFmpeg 走 PATH(`brew install ffmpeg`)。`peach-data/tools/ffmpeg`
Windows 的 `.exe`/`.dll`,`FFmpegResolver` 按平台找不带后缀的 `ffmpeg`,会自动跳过它
——这套目录可以两台机器共用,不需要分叉。
+macOS 的菜单栏项必须打成 `.app`(`scripts/build_macos_app.py`):裸控制台进程启动时
+AppKit 运行循环没有应用上下文会立刻返回,服务起来了但托盘父进程安静退出、零输出。
+bundle 声明 `LSUIElement`,输出重定向到 `logs/macos-tray.log`。图标要 template image
+才会跟着浅色/深色菜单栏反色;服务用非特权端口 8900。
+
测试入口:Windows `scripts/test.ps1`,macOS/Linux `scripts/test.sh`。两者契约相同。
**两边都必须绿**;只在一台上通过的改动不算完成。Windows 托盘专属的 DPI 声明和单实例
锁在非 Windows 上按 `skipUnless` 跳过,不要改成在 macOS 上伪造通过。
diff --git a/README.md b/README.md
index ec1ba1e6e..c9c80bbe4 100644
--- a/README.md
+++ b/README.md
@@ -124,6 +124,23 @@ macOS/Linux 是 `scripts/test.sh`,两者契约相同:从 Git common director
`.venv`,强制加载当前 worktree 的 `src` 并核对 `peach.__file__`,因此 worktree 不需要
也不应复制 `.venv`。仓库不使用 pytest。
+macOS 日常运行同样可以走菜单栏项,而不是留一个终端窗口:
+
+```bash
+./.venv/bin/python scripts/build_macos_app.py
+open -a dist/Peach.app
+```
+
+菜单栏项复用 `peach.tray`(pystray 自带 darwin 后端),但有三处必须按平台分开:图标要
+是 template image,否则不会跟着浅色/深色菜单栏反色;服务起在非特权的 `8900`,因为
+80/443 在 macOS 上要 root,而本机 CA 的 TLS 材料是给 Windows 生产实例签的;单实例锁
+用 `fcntl.flock`。
+
+必须打成 `.app` 才拿得稳:裸控制台进程启动时 AppKit 的运行循环没有应用上下文会立刻
+返回——服务起来了、托盘父进程却安静退出,退出码 0、零输出。bundle 的 `Info.plist` 声明
+`LSUIElement`(只在菜单栏出现,不占 Dock、不进 ⌘Tab),启动脚本把输出重定向到
+`peach-data/logs/macos-tray.log`。开机自启:系统设置 → 通用 → 登录项 → 加入这个 .app。
+
跨两台机器开发时换行口径由 `.gitattributes` 的 `* text=auto eol=lf` 固定。不要依赖各自的
`core.autocrlf`:2026-08 之前 Windows 侧把 105 个文件整体改写成 CRLF,`git status` 长期显示
117 个文件被修改、16000 行增删,而真正有实质改动的只有 1 个。
diff --git a/scripts/build_macos_app.py b/scripts/build_macos_app.py
new file mode 100644
index 000000000..7142a3b2d
--- /dev/null
+++ b/scripts/build_macos_app.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""生成 macOS 菜单栏项的 .app 外壳。
+
+裸控制台进程拿不稳菜单栏项:`peach-tray` 直接后台启动时会拉起服务、然后自己安静
+退出——AppKit 的运行循环在没有应用上下文时立刻返回,退出码 0、没有任何输出。
+实测就是这样:服务进程还在,托盘父进程没了。
+
+macOS 的标准做法是打成 bundle 并在 `Info.plist` 里声明 `LSUIElement`:只在菜单栏
+出现,不占 Dock、不进 ⌘Tab。外壳本身只有一个 plist 和一个 exec 到项目 venv 的脚本
+——和 Windows 那边一样,托盘不是可移动的独立发行版,服务进程仍由 venv 承担。
+"""
+from __future__ import annotations
+
+import argparse
+import plistlib
+import shutil
+import stat
+from pathlib import Path
+
+from peach import __version__
+from peach.config import LOG_DIR, PROJECT_ROOT
+
+
+BUNDLE_ID = "gg.lmd.peach.tray"
+# `open -a` 启动的进程没有终端,stdout/stderr 直接进虚空。菜单栏项本来就没有窗口,
+# 不落盘的话它为什么没起来完全看不出来——上一版就是这样:进程活着、服务没起、零输出。
+LAUNCHER = """#!/bin/sh
+# 由 scripts/build_macos_app.py 生成,勿手改。
+LOG="{log_dir}/macos-tray.log"
+mkdir -p "{log_dir}"
+exec "{tray}" "$@" >>"$LOG" 2>&1
+"""
+
+
+def build(destination: Path, tray: Path) -> Path:
+ app = destination / "Peach.app"
+ macos, resources = app / "Contents" / "MacOS", app / "Contents" / "Resources"
+ if app.exists():
+ shutil.rmtree(app)
+ macos.mkdir(parents=True)
+ resources.mkdir(parents=True)
+
+ info = {
+ "CFBundleName": "Peach",
+ "CFBundleDisplayName": "Peach 蜜桃",
+ "CFBundleIdentifier": BUNDLE_ID,
+ "CFBundleVersion": __version__,
+ "CFBundleShortVersionString": __version__,
+ "CFBundlePackageType": "APPL",
+ "CFBundleExecutable": "Peach",
+ # 只在菜单栏出现:不占 Dock、不进 ⌘Tab。菜单栏项的标准声明。
+ "LSUIElement": True,
+ "NSHighResolutionCapable": True,
+ }
+ (app / "Contents" / "Info.plist").write_bytes(plistlib.dumps(info))
+
+ launcher = macos / "Peach"
+ launcher.write_text(
+ LAUNCHER.format(tray=tray, log_dir=LOG_DIR), encoding="utf-8")
+ launcher.chmod(launcher.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+
+ logo = PROJECT_ROOT / "resources" / "peach-logo.png"
+ if logo.is_file():
+ shutil.copy2(logo, resources / "peach-logo.png")
+ return app
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="生成 macOS 菜单栏项的 .app 外壳")
+ parser.add_argument("--destination", type=Path, default=PROJECT_ROOT / "dist")
+ parser.add_argument("--tray", type=Path, default=PROJECT_ROOT / ".venv" / "bin" / "peach-tray")
+ return parser
+
+
+def run(args: argparse.Namespace) -> int:
+ if not args.tray.is_file():
+ raise SystemExit(f"找不到 peach-tray:{args.tray}(先 pip install -e .)")
+ args.destination.mkdir(parents=True, exist_ok=True)
+ app = build(args.destination, args.tray)
+ print(f"已生成 {app}")
+ print(f" 启动:open -a '{app}'")
+ print(" 开机自启:系统设置 → 通用 → 登录项 → 加入这个 .app")
+ return 0
+
+
+def main() -> int:
+ return run(build_parser().parse_args())
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_tray.py b/tests/test_tray.py
index 3749ff064..cf2d96f64 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -1,4 +1,6 @@
+import importlib.util
import os
+import plistlib
import sys
import tempfile
import threading
@@ -7,6 +9,17 @@ import unittest
from pathlib import Path
from unittest.mock import Mock, patch
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def load_script(name: str):
+ """按路径加载 `scripts/` 下的脚本;它们不是包的一部分。"""
+ spec = importlib.util.spec_from_file_location(f"test_{name}", ROOT / "scripts" / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
from peach.tray import (
AlreadyRunning, PeachTray, ServiceManager, ServiceSpec, SingleInstance,
apply_macos_template, build_service_specs, create_icon, enable_hidpi,
@@ -128,5 +141,44 @@ class TemplateHookTests(unittest.TestCase):
self.assertFalse(apply_macos_template(Mock(spec=[])))
+class MacAppBundleTests(unittest.TestCase):
+ """菜单栏项必须打成 bundle 才拿得稳。
+
+ 裸控制台进程启动 `peach-tray` 时,AppKit 的运行循环没有应用上下文会立刻返回:
+ 服务起来了、托盘父进程却安静退出,退出码 0、零输出。实测就是这样。
+ """
+
+ def setUp(self):
+ self.module = load_script("build_macos_app")
+ self._tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self._tmp.name)
+ self.addCleanup(self._tmp.cleanup)
+ self.tray = self.root / "peach-tray"
+ self.tray.write_text("#!/bin/sh\n", encoding="utf-8")
+
+ def test_bundle_declares_itself_as_a_menu_bar_agent(self):
+ app = self.module.build(self.root, self.tray)
+ info = plistlib.loads((app / "Contents" / "Info.plist").read_bytes())
+ # LSUIElement:只在菜单栏出现,不占 Dock、不进 ⌘Tab。
+ self.assertIs(info["LSUIElement"], True)
+ self.assertEqual(info["CFBundleExecutable"], "Peach")
+ self.assertTrue(info["CFBundleIdentifier"])
+
+ def test_launcher_is_executable_and_keeps_a_log(self):
+ """`open -a` 起的进程没有终端,不落盘就完全看不出它为什么没起来。"""
+ app = self.module.build(self.root, self.tray)
+ launcher = app / "Contents" / "MacOS" / "Peach"
+ self.assertTrue(os.access(launcher, os.X_OK))
+ body = launcher.read_text(encoding="utf-8")
+ self.assertIn(str(self.tray), body)
+ self.assertIn("macos-tray.log", body)
+
+ def test_rebuild_replaces_a_stale_bundle(self):
+ app = self.module.build(self.root, self.tray)
+ (app / "Contents" / "MacOS" / "stale").write_text("x", encoding="utf-8")
+ self.module.build(self.root, self.tray)
+ self.assertFalse((app / "Contents" / "MacOS" / "stale").exists())
+
+
if __name__ == "__main__":
unittest.main()