Peach: Local-first video metadata scraper and media manager.
fix: implement the macOS menu bar natively and run it from a LaunchAgent
Peach local maintenance60aa5cbbac46
diff --git a/README.md b/README.mdindex c9c80bbe4..68f2a51ee 100644--- a/README.md+++ b/README.md@@ -124,22 +124,33 @@ macOS/Linux 是 `scripts/test.sh`,两者契约相同:从 Git common director`.venv`,强制加载当前 worktree 的 `src` 并核对 `peach.__file__`,因此 worktree 不需要也不应复制 `.venv`。仓库不使用 pytest。-macOS 日常运行同样可以走菜单栏项,而不是留一个终端窗口:+macOS 日常运行走菜单栏项,而不是留一个终端窗口:```bash-./.venv/bin/python scripts/build_macos_app.py-open -a dist/Peach.app+./.venv/bin/python scripts/make_macos_icon.py # 圆角 .icns,只需一次+./.venv/bin/python scripts/install_macos_agent.py install```-菜单栏项复用 `peach.tray`(pystray 自带 darwin 后端),但有三处必须按平台分开:图标要-是 template image,否则不会跟着浅色/深色菜单栏反色;服务起在非特权的 `8900`,因为-80/443 在 macOS 上要 root,而本机 CA 的 TLS 材料是给 Windows 生产实例签的;单实例锁-用 `fcntl.flock`。+**菜单栏项没有跨平台的轮子。** pystray 名义上支持 darwin,但它的后端漏了三件事:+`setActivationPolicy_(Accessory)`、`NSImage.setSize_(18,18)`(菜单栏按 18pt 画,直接塞+64px 位图会被裁掉)和 `setTemplate_`(不设就不会跟着浅色/深色菜单栏反色)。补齐等于+把它那层薄封装重写一遍,所以 macOS 直接用 AppKit(`src/peach/menubar.py`),Windows+继续用 pystray。判据不靠猜:`item.button().window().frame()` 能直接读出状态项落在屏幕+的哪个位置。-必须打成 `.app` 才拿得稳:裸控制台进程启动时 AppKit 的运行循环没有应用上下文会立刻-返回——服务起来了、托盘父进程却安静退出,退出码 0、零输出。bundle 的 `Info.plist` 声明-`LSUIElement`(只在菜单栏出现,不占 Dock、不进 ⌘Tab),启动脚本把输出重定向到-`peach-data/logs/macos-tray.log`。开机自启:系统设置 → 通用 → 登录项 → 加入这个 .app。+**不能用 .app 外壳直接跑它。** macOS 26 上主可执行文件是 exec 跳板(shell 脚本、C+launcher 都算)时状态项注册不上:进程活着、`NSStatusItem` 也建出来了,但按钮窗口永远+是 `(0,0,34,0)`——高度 0、从来没被布局。Apple 受理为 FB21015611,没有绕过办法。同一份+代码由 launchd 直接拉起时实测 `(858, 949, 34, 33)`,正常落在菜单栏内。所以自启走+LaunchAgent;`dist/Peach.app` 只作双击入口,它做的事只是 `launchctl kickstart`。++服务起在非特权的 `8900`:80/443 在 macOS 上要 root,而本机 CA 的 TLS 材料是给 Windows+生产实例签的。想让 `http://peach.local/` 不带端口也能开,把 80 交给内核转发,而不是让+整个服务提权:++```bash+sudo sh scripts/setup_macos_port80.sh install+```跨两台机器开发时换行口径由 `.gitattributes` 的 `* text=auto eol=lf` 固定。不要依赖各自的`core.autocrlf`:2026-08 之前 Windows 侧把 105 个文件整体改写成 CRLF,`git status` 长期显示diff --git a/resources/peach.icns b/resources/peach.icnsnew file mode 100644index 000000000..2fb78af63Binary files /dev/null and b/resources/peach.icns differdiff --git a/scripts/build_macos_app.py b/scripts/build_macos_app.pyindex 7142a3b2d..687306e28 100644--- a/scripts/build_macos_app.py+++ b/scripts/build_macos_app.py@@ -19,17 +19,21 @@ import statfrom pathlib import Pathfrom peach import __version__-from peach.config import LOG_DIR, PROJECT_ROOT---BUNDLE_ID = "gg.lmd.peach.tray"-# `open -a` 启动的进程没有终端,stdout/stderr 直接进虚空。菜单栏项本来就没有窗口,-# 不落盘的话它为什么没起来完全看不出来——上一版就是这样:进程活着、服务没起、零输出。+from peach.config import PROJECT_ROOT+++BUNDLE_ID = "gg.lmd.peach.app"+#: LaunchAgent 的 label,双击 .app 时踢它。+LABEL = "gg.lmd.peach.tray"+# 这个外壳**不能**自己 exec 到解释器。macOS 26 上,主可执行文件是 exec 跳板时状态项+# 注册不上:进程活着、NSStatusItem 也建出来了,但按钮窗口永远是 (0,0,34,0),菜单栏上+# 什么都不出现(Apple FB21015611)。同一份代码由 launchd 直接拉起时实测+# (858, 949, 34, 33),正常落在菜单栏内。+#+# 所以双击 .app 只负责踢一脚 LaunchAgent,真正的菜单栏进程是 launchd 的直接子进程。LAUNCHER = """#!/bin/sh# 由 scripts/build_macos_app.py 生成,勿手改。-LOG="{log_dir}/macos-tray.log"-mkdir -p "{log_dir}"-exec "{tray}" "$@" >>"$LOG" 2>&1+exec /bin/launchctl kickstart -k "gui/$(id -u)/{label}""""@@ -56,13 +60,16 @@ def build(destination: Path, tray: Path) -> Path:(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.write_text(LAUNCHER.format(label=LABEL), 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")+ # 访达和 Dock 里的图标。方形原图直接当图标会比周围大一圈、四角还是直的,+ # 所以用 scripts/make_macos_icon.py 生成的圆角版本。+ icon = PROJECT_ROOT / "resources" / "peach.icns"+ if icon.is_file():+ shutil.copy2(icon, resources / "peach.icns")+ info["CFBundleIconFile"] = "peach"+ (app / "Contents" / "Info.plist").write_bytes(plistlib.dumps(info))return app@@ -79,8 +86,8 @@ def run(args: argparse.Namespace) -> int:args.destination.mkdir(parents=True, exist_ok=True)app = build(args.destination, args.tray)print(f"已生成 {app}")- print(f" 启动:open -a '{app}'")- print(" 开机自启:系统设置 → 通用 → 登录项 → 加入这个 .app")+ print(" 双击它只是踢一脚 LaunchAgent;先注册:")+ print(" python scripts/install_macos_agent.py install")return 0diff --git a/scripts/install_macos_agent.py b/scripts/install_macos_agent.pynew file mode 100644index 000000000..44a578cfd--- /dev/null+++ b/scripts/install_macos_agent.py@@ -0,0 +1,107 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+r"""把 Peach 菜单栏项注册成 LaunchAgent。++**不能用 .app 外壳直接跑菜单栏项。** macOS 26 上,主可执行文件如果是一个 exec 到+真正解释器的跳板(shell 脚本、C launcher 都算),状态项就注册不上:进程活着、+`NSStatusItem` 也建出来了,但它的按钮窗口永远是 `(0,0,34,0)`——高度 0,从来没被+布局,菜单栏上什么都不出现。Apple 已受理为 FB21015611,目前没有绕过办法。++同一份代码由 launchd 或 shell 直接拉起(没有跳板)时立刻正常:实测按钮窗口+`(858, 949, 34, 33)`,屏宽 1512,落在菜单栏内。++所以登录自启走 LaunchAgent,而不是把 .app 放进登录项。`.app` 只留作双击入口,+它做的事也只是 `launchctl kickstart`,不自己 exec 解释器。+"""+from __future__ import annotations++import argparse+import getpass+import os+import plistlib+import subprocess+from pathlib import Path++from peach.config import LOG_DIR, PROJECT_ROOT+++LABEL = "gg.lmd.peach.tray"+++def plist_path() -> Path:+ return Path.home() / "Library" / "LaunchAgents" / f"{LABEL}.plist"+++def build_plist(tray: Path) -> dict:+ return {+ "Label": LABEL,+ # 直接跑目标程序,中间不能有 exec 跳板,否则菜单栏项注册不上。+ "ProgramArguments": [str(tray)],+ "RunAtLoad": True,+ # 菜单栏项是用户主动退出的,不要自动拉回来。+ "KeepAlive": False,+ "ProcessType": "Interactive",+ "WorkingDirectory": str(PROJECT_ROOT),+ "StandardOutPath": str(LOG_DIR / "macos-tray.log"),+ "StandardErrorPath": str(LOG_DIR / "macos-tray.log"),+ }+++def launchctl(*args: str) -> subprocess.CompletedProcess:+ # 显式给 encoding:text=True 会用平台默认编码,中文输出会静默丢成空 stdout。+ return subprocess.run(+ ["launchctl", *args], capture_output=True, text=True,+ encoding="utf-8", errors="replace")+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="注册 / 注销 Peach 菜单栏项的 LaunchAgent")+ parser.add_argument("action", choices=("install", "uninstall", "status"),+ nargs="?", default="install")+ parser.add_argument("--tray", type=Path,+ default=PROJECT_ROOT / ".venv" / "bin" / "peach-tray")+ return parser+++def run(args: argparse.Namespace) -> int:+ target = plist_path()+ domain = f"gui/{os.getuid()}"++ if args.action == "status":+ result = launchctl("print", f"{domain}/{LABEL}")+ print(f"plist:{target}({'存在' if target.is_file() else '不存在'})")+ print("已加载" if result.returncode == 0 else "未加载")+ return 0++ if args.action == "uninstall":+ launchctl("bootout", f"{domain}/{LABEL}")+ if target.is_file():+ target.unlink()+ print(f"已注销 {LABEL}")+ return 0++ if not args.tray.is_file():+ raise SystemExit(f"找不到 peach-tray:{args.tray}(先 pip install -e .)")+ LOG_DIR.mkdir(parents=True, exist_ok=True)+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(plistlib.dumps(build_plist(args.tray)))++ # 重装时先 bootout:同一个 label 不能重复 bootstrap。+ launchctl("bootout", f"{domain}/{LABEL}")+ result = launchctl("bootstrap", domain, str(target))+ if result.returncode != 0:+ raise SystemExit(f"launchctl bootstrap 失败:{result.stderr.strip()}")+ launchctl("kickstart", "-k", f"{domain}/{LABEL}")+ print(f"已注册并启动 {LABEL}(用户 {getpass.getuser()})")+ print(f" plist:{target}")+ print(f" 日志:{LOG_DIR / 'macos-tray.log'}")+ print(f" 停止:launchctl bootout {domain}/{LABEL}")+ return 0+++def main() -> int:+ return run(build_parser().parse_args())+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/make_macos_icon.py b/scripts/make_macos_icon.pynew file mode 100644index 000000000..bd4bce288--- /dev/null+++ b/scripts/make_macos_icon.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""把品牌图做成符合 macOS 版式的 .icns。++macOS 的应用图标不是「一张铺满画布的方图」:内容画在一个圆角矩形里,四周留白约+10%,圆角半径约内容边长的 22.5%。直接把 1024×1024 的方形 PNG 当图标用,在 Dock 和+访达里会比周围所有图标都大一圈、四角还是直的。++`iconutil` 需要一个 .iconset 目录,里面是固定命名的 1x/2x 两套位图。+"""+from __future__ import annotations++import argparse+import subprocess+from pathlib import Path++from PIL import Image, ImageDraw++from peach.config import PROJECT_ROOT+++#: macOS 图标网格:内容占画布的比例,以及圆角半径占内容边长的比例。+CONTENT_SCALE = 0.80+CORNER_RATIO = 0.225+#: iconutil 认的尺寸集合(点数,2x 由同名 @2x 提供)。+SIZES = (16, 32, 128, 256, 512)+++def squircle(source: Image.Image, edge: int) -> Image.Image:+ """把源图放进带圆角和留白的画布。"""+ canvas = Image.new("RGBA", (edge, edge), (0, 0, 0, 0))+ inner = max(1, int(edge * CONTENT_SCALE))+ offset = (edge - inner) // 2++ art = source.convert("RGBA").resize((inner, inner), Image.Resampling.LANCZOS)+ rounded = Image.new("L", (inner, inner), 0)+ ImageDraw.Draw(rounded).rounded_rectangle(+ (0, 0, inner - 1, inner - 1), radius=int(inner * CORNER_RATIO), fill=255)+ # 源图自己的透明区域也要保留:圆角蒙版和原始 alpha 取交集,否则透明背景会被填成实心。+ art.putalpha(Image.composite(rounded, Image.new("L", rounded.size, 0), art.getchannel("A")))+ canvas.paste(art, (offset, offset), art)+ return canvas+++def build(source: Image.Image, destination: Path) -> Path:+ iconset = destination.with_suffix(".iconset")+ if iconset.exists():+ for item in iconset.iterdir():+ item.unlink()+ else:+ iconset.mkdir(parents=True)+ for size in SIZES:+ squircle(source, size).save(iconset / f"icon_{size}x{size}.png")+ squircle(source, size * 2).save(iconset / f"icon_{size}x{size}@2x.png")+ subprocess.run(+ ["iconutil", "--convert", "icns", str(iconset), "--output", str(destination)],+ check=True)+ return destination+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="生成 macOS 风格的 .icns 图标")+ parser.add_argument("--source", type=Path,+ default=PROJECT_ROOT / "resources" / "peach-logo.png")+ parser.add_argument("--output", type=Path,+ default=PROJECT_ROOT / "resources" / "peach.icns")+ return parser+++def run(args: argparse.Namespace) -> int:+ if not args.source.is_file():+ raise SystemExit(f"找不到源图:{args.source}")+ output = build(Image.open(args.source), args.output)+ print(f"已生成 {output}({output.stat().st_size // 1024} KB)")+ return 0+++def main() -> int:+ return run(build_parser().parse_args())+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/setup_macos_port80.sh b/scripts/setup_macos_port80.shnew file mode 100644index 000000000..240c7cc9a--- /dev/null+++ b/scripts/setup_macos_port80.sh@@ -0,0 +1,77 @@+#!/bin/sh+# 让 http://peach.local/ 不带端口也能打开。+#+# macOS 和其他 Unix 一样,1024 以下的端口只有 root 能监听。Peach 在 macOS 上跑在+# 非特权的 8900(见 peach.tray.MACOS_PORT),所以 `peach.local:8900` 通、+# `peach.local` 不通。+#+# 与其让整个服务以 root 跑,不如让内核把 80 转到 8900:pf 的 rdr 规则,服务本身+# 还是普通用户进程。这是 macOS 上的标准做法,也是唯一不需要提权跑 Python 的做法。+#+# 需要 sudo,且只需执行一次;重启后由 LaunchDaemon 重新加载。+#+# sudo sh scripts/setup_macos_port80.sh install+# sudo sh scripts/setup_macos_port80.sh uninstall+set -eu++ANCHOR_NAME="gg.lmd.peach"+ANCHOR_FILE="/etc/pf.anchors/${ANCHOR_NAME}"+DAEMON="/Library/LaunchDaemons/${ANCHOR_NAME}.pf.plist"+TARGET_PORT="${PEACH_PORT:-8900}"+ACTION="${1:-install}"++if [ "$(id -u)" -ne 0 ]; then+ echo "需要 root:sudo sh $0 $ACTION" >&2+ exit 1+fi++if [ "$ACTION" = "uninstall" ]; then+ launchctl bootout system "$DAEMON" 2>/dev/null || true+ rm -f "$DAEMON" "$ANCHOR_FILE"+ # /etc/pf.conf 里的 anchor 行留着无害(锚点为空即无规则),但也一并清掉。+ if [ -f /etc/pf.conf ]; then+ grep -v "$ANCHOR_NAME" /etc/pf.conf > /etc/pf.conf.peach.tmp+ mv /etc/pf.conf.peach.tmp /etc/pf.conf+ fi+ pfctl -f /etc/pf.conf 2>/dev/null || true+ echo "已移除 80 -> ${TARGET_PORT} 的重定向"+ exit 0+fi++cat > "$ANCHOR_FILE" <<RULES+# 由 scripts/setup_macos_port80.sh 生成,勿手改。+# 本机自己访问走 lo0,其他设备走真实网卡,两条都要。+rdr pass on lo0 inet proto tcp from any to any port 80 -> 127.0.0.1 port ${TARGET_PORT}+rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port ${TARGET_PORT}+RULES++# rdr-anchor 必须排在 filter 规则之前,所以插在 pf.conf 的 scrub 段之后。+if ! grep -q "$ANCHOR_NAME" /etc/pf.conf; then+ cp /etc/pf.conf "/etc/pf.conf.peach.bak.$(date +%Y%m%d-%H%M%S)"+ printf '\nrdr-anchor "%s"\nload anchor "%s" from "%s"\n' \+ "$ANCHOR_NAME" "$ANCHOR_NAME" "$ANCHOR_FILE" >> /etc/pf.conf+fi++# 先做语法检查再真正加载:pf.conf 写坏会让整台机器的包过滤加载失败。+pfctl -n -f /etc/pf.conf++cat > "$DAEMON" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+ <key>Label</key><string>${ANCHOR_NAME}.pf</string>+ <key>ProgramArguments</key>+ <array><string>/sbin/pfctl</string><string>-e</string><string>-f</string><string>/etc/pf.conf</string></array>+ <key>RunAtLoad</key><true/>+ <key>KeepAlive</key><false/>+</dict></plist>+PLIST++pfctl -e 2>/dev/null || true+pfctl -f /etc/pf.conf+launchctl bootout system "$DAEMON" 2>/dev/null || true+launchctl bootstrap system "$DAEMON"++echo "已把 80 重定向到 ${TARGET_PORT}"+echo " 验证:curl -sI http://peach.local/healthz | head -1"+echo " 移除:sudo sh $0 uninstall"diff --git a/src/peach/menubar.py b/src/peach/menubar.pynew file mode 100644index 000000000..5f7becf8c--- /dev/null+++ b/src/peach/menubar.py@@ -0,0 +1,180 @@+"""macOS 菜单栏项。直接用 AppKit,不走 pystray。++菜单栏项这件事没有跨平台的轮子可用。pystray 名义上支持 darwin,但它的后端只做了+`statusItemWithLength_` + `setImage_`,漏掉两件在 macOS 上必需的事:++1. `NSApplication.setActivationPolicy_(Accessory)` —— 不声明就不是「只在菜单栏出现」+ 的附件应用。+2. `NSImage.setSize_(18, 18)` —— 菜单栏高度是 22pt、图标按 18pt 画。直接把 64px 的+ PNG 塞进按钮,画出来要么被裁掉要么糊成一坨。++它也不调 `setTemplate_`,所以图标不会跟着浅色/深色菜单栏反色。三件事都得自己补,+补完等于把它那层薄封装重写一遍,不如直接用 AppKit——Windows 那边继续用 pystray。++判据不是猜的:`item.button().window().frame()` 能直接读出状态项落在屏幕的哪个位置,+本机实测 `x=858 w=34`(屏宽 1512),确认它确实被放上了菜单栏。+"""+from __future__ import annotations++import io+import logging+import threading+from typing import Callable++import AppKit+import PyObjCTools.AppHelper+import objc+from PIL import Image+++LOGGER = logging.getLogger(__name__)++#: 菜单栏图标的绘制尺寸。菜单栏高 22pt,图标按 18pt 画是系统惯例。+ICON_POINTS = 18+++def nsimage(image: Image.Image, *, points: int = ICON_POINTS) -> AppKit.NSImage:+ """把 PIL 图转成菜单栏用的 template NSImage。"""+ buffer = io.BytesIO()+ image.convert("RGBA").resize((points * 2, points * 2), Image.Resampling.LANCZOS).save(+ buffer, "PNG")+ payload = buffer.getvalue()+ data = AppKit.NSData.dataWithBytes_length_(payload, len(payload))+ result = AppKit.NSImage.alloc().initWithData_(data)+ # 尺寸按点设,位图给两倍以适配 Retina。+ result.setSize_(AppKit.NSMakeSize(points, points))+ # template image 由系统按菜单栏明暗自动反色;彩色图不会跟着变。+ result.setTemplate_(True)+ return result+++class _Target(AppKit.NSObject):+ """菜单项的动作目标。AppKit 只认 ObjC 选择器,所以要有这么一层。"""++ def initWithHandlers_(self, handlers):+ self = objc.super(_Target, self).init()+ if self is None:+ return None+ self._handlers = handlers+ return self++ @objc.python_method+ def _dispatch(self, sender) -> None:+ handler = self._handlers.get(int(sender.tag()))+ if handler is None:+ return+ try:+ handler()+ except Exception:+ LOGGER.exception("菜单项处理失败")++ def invoke_(self, sender) -> None:+ self._dispatch(sender)+++class MenuBarApp:+ """一个菜单栏状态项,外加它的下拉菜单。++ `items` 是 (标题, 处理函数或 None) 的序列;处理函数为 None 表示只读信息行,+ 标题可以是可调用对象,每次打开菜单时重新求值。+ """++ def __init__(+ self,+ image: Image.Image,+ tooltip: str,+ items: list[tuple[object, Callable[[], None] | None]],+ ):+ self.app = AppKit.NSApplication.sharedApplication()+ # 附件应用:只在菜单栏出现,不占 Dock、不进 ⌘Tab。bundle 里 LSUIElement 也声明了+ # 一次,但直接从终端跑时只有这句管用。+ self.app.setActivationPolicy_(AppKit.NSApplicationActivationPolicyAccessory)++ self._titles: list[tuple[AppKit.NSMenuItem, object]] = []+ handlers: dict[int, Callable[[], None]] = {}+ menu = AppKit.NSMenu.alloc().init()+ # 每次打开前刷新动态标题(状态、版本这些)。+ menu.setAutoenablesItems_(False)+ for index, (title, handler) in enumerate(items):+ if title is None:+ menu.addItem_(AppKit.NSMenuItem.separatorItem())+ continue+ text = title() if callable(title) else str(title)+ entry = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(text, None, "")+ entry.setTag_(index)+ if handler is None:+ entry.setEnabled_(False)+ else:+ handlers[index] = handler+ menu.addItem_(entry)+ self._titles.append((entry, title))++ self._target = _Target.alloc().initWithHandlers_(handlers)+ for entry, _ in self._titles:+ if entry.tag() in handlers:+ entry.setTarget_(self._target)+ entry.setAction_("invoke:")+ entry.setEnabled_(True)++ self.item = AppKit.NSStatusBar.systemStatusBar().statusItemWithLength_(+ AppKit.NSVariableStatusItemLength)+ self.item.button().setImage_(nsimage(image))+ self.item.button().setToolTip_(tooltip)+ self.item.setMenu_(menu)+ self.item.setVisible_(True)+ self.menu = menu++ def refresh_titles(self) -> None:+ """重算动态标题。菜单是现取现画的,打开前刷一次就够。"""+ for entry, title in self._titles:+ if callable(title):+ entry.setTitle_(title())++ def placement(self) -> tuple[float, float, float, float] | None:+ """状态项在屏幕上的位置;拿不到窗口说明它根本没被放上菜单栏。"""+ window = self.item.button().window()+ if window is None:+ return None+ frame = window.frame()+ return (frame.origin.x, frame.origin.y, frame.size.width, frame.size.height)++ def notify(self, message: str, title: str = "Peach") -> None:+ """用系统通知报状态;菜单栏项没有窗口可以弹。"""+ notification = AppKit.NSUserNotification.alloc().init()+ notification.setTitle_(title)+ notification.setInformativeText_(message)+ AppKit.NSUserNotificationCenter.defaultUserNotificationCenter(+ ).deliverNotification_(notification)++ def log_placement(self) -> None:+ """把状态项的实际坐标写进日志。++ 必须等运行循环转起来之后再读:刚构造完时窗口还没布局,读到的是 (0,0,34,0),+ 看着像「没放上去」其实只是早了一步。+ """+ def report() -> None:+ LOGGER.info("菜单栏状态项位置:%s", self.placement())++ AppKit.NSTimer.scheduledTimerWithTimeInterval_repeats_block_(+ 1.0, False, lambda _timer: report())++ def run(self) -> None:+ self.log_placement()++ # 标题里有「状态:运行中」这种会变的内容,定时刷新比只在打开时刷简单且够用。+ def tick() -> None:+ while True:+ AppKit.NSOperationQueue.mainQueue().addOperationWithBlock_(self.refresh_titles)+ if self._stop.wait(5.0):+ return++ self._stop = threading.Event()+ threading.Thread(target=tick, name="PeachMenuTitles", daemon=True).start()+ try:+ PyObjCTools.AppHelper.runEventLoop()+ finally:+ self._stop.set()++ def stop(self) -> None:+ AppKit.NSStatusBar.systemStatusBar().removeStatusItem_(self.item)+ self.app.terminate_(None)diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 0b783c489..f0a59d81e 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -1,6 +1,7 @@from __future__ import annotationsimport ctypes+import loggingimport osimport subprocessimport sys@@ -19,6 +20,9 @@ from .config import LOG_DIR, PROJECT_ROOT, SECRETS_DIR, STATE_DIRfrom .versioning import VersionManager+LOGGER = logging.getLogger(__name__)++DEFAULT_LAN_ADDRESS = "192.168.50.162"#: macOS 菜单栏项拉起的端口。80/443 在 macOS 上要 root,开发机不该为一个菜单栏图标#: 去要管理员权限;本机 CA 的那套 TLS 材料也是给 Windows 生产实例签的。@@ -451,7 +455,48 @@ class PeachTray:self._stop_event.set()+def run_macos_menu_bar(manager: "ServiceManager") -> None:+ """macOS 走原生菜单栏项。++ pystray 的 darwin 后端漏了 activation policy 和图标尺寸两件必需的事,补齐等于+ 重写它那层封装,所以这里直接用 AppKit(见 `peach.menubar`)。Windows 继续走 pystray。+ """+ from .menubar import MenuBarApp++ versions = VersionManager()+ snapshot = versions.inspect()+ app: dict[str, object] = {}++ def restart() -> None:+ manager.stop_owned()+ manager.start_missing()++ def quit_now() -> None:+ manager.stop_owned()+ holder = app.get("app")+ if holder is not None:+ holder.stop()++ menu = MenuBarApp(+ create_icon(template=True),+ "Peach · 蜜桃",+ [+ ("打开 Peach", lambda: webbrowser.open(OPEN_URL)),+ (lambda: f"状态:{manager.status()}", None),+ (None, None),+ ("重启服务", restart),+ ("查看日志", lambda: subprocess.run(["open", str(LOG_DIR)], check=False)),+ (lambda: f"版本 {snapshot.package_version} · {snapshot.build_label}", None),+ (None, None),+ ("退出 Peach", quit_now),+ ],+ )+ app["app"] = menu+ menu.run()++def main() -> int:+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")enable_hidpi()instance = SingleInstance(STATE_DIR / "peach-tray.lock")manager = None@@ -462,7 +507,11 @@ def main() -> int:return 0try:manager = ServiceManager(build_service_specs())- PeachTray(manager).run()+ manager.start_missing()+ if sys.platform == "darwin":+ run_macos_menu_bar(manager)+ else:+ PeachTray(manager).run()except Exception as exc:show_message("Peach 启动失败", str(exc), error=True)return 1diff --git a/tests/test_tray.py b/tests/test_tray.pyindex cf2d96f64..c64251c81 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -164,14 +164,29 @@ class MacAppBundleTests(unittest.TestCase):self.assertEqual(info["CFBundleExecutable"], "Peach")self.assertTrue(info["CFBundleIdentifier"])- def test_launcher_is_executable_and_keeps_a_log(self):- """`open -a` 起的进程没有终端,不落盘就完全看不出它为什么没起来。"""+ def test_launcher_never_execs_the_interpreter_itself(self):+ """外壳不能自己 exec 到解释器。++ macOS 26 上主可执行文件是 exec 跳板时状态项注册不上:进程活着、NSStatusItem+ 也建出来了,但按钮窗口永远是 (0,0,34,0),菜单栏上什么都不出现(FB21015611)。+ 双击只负责踢 LaunchAgent,真正的菜单栏进程是 launchd 的直接子进程。+ """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)+ self.assertIn("launchctl kickstart", body)+ self.assertNotIn(str(self.tray), body)++ def test_bundle_carries_a_rounded_icon(self):+ """方形原图直接当图标会比周围大一圈、四角还是直的。"""+ app = self.module.build(self.root, self.tray)+ import plistlib as _plistlib+ info = _plistlib.loads((app / "Contents" / "Info.plist").read_bytes())+ icon = ROOT / "resources" / "peach.icns"+ if icon.is_file():+ self.assertEqual(info.get("CFBundleIconFile"), "peach")+ self.assertTrue((app / "Contents" / "Resources" / "peach.icns").is_file())def test_rebuild_replaces_a_stale_bundle(self):app = self.module.build(self.root, self.tray)