Peach: Local-first video metadata scraper and media manager.
feat: macOS 标识改成中性的 io.github.longmeidao.peach.*
longmeidaofeb7591a8796
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex cf8edaa04..1371b5d50 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -81,7 +81,7 @@ cp ../peach-data/config.toml ../peach-data/config.toml.bak 2>/dev/null./.venv/bin/peach init --from-existing --force \--mount local=/Volumes/RESOURCES/media \--writer-origin https://<writer>.local --smb-host <writer>.local --smb-user <钥匙串账号>-launchctl kickstart -k gui/$(id -u)/gg.lmd.peach.tray+launchctl kickstart -k gui/$(id -u)/io.github.longmeidao.peach.tray```核对:随便打开一个本地媒体资产能播(挂载表生效)、`/healthz` 报 `ledger_sync: reader`、@@ -94,6 +94,22 @@ launchctl kickstart -k gui/$(id -u)/gg.lmd.peach.tray## 桌面入口与发布- Windows 日常入口是当前用户 Startup 里唯一的 `Peach.lnk`,指向项目内的 `dist\Peach\Peach.exe`。+- macOS 日常入口是 LaunchAgent `io.github.longmeidao.peach.tray`,由 `python scripts/install_macos_agent.py`(`install`/`status`/`uninstall`)管理;`.app` 外壳的 bundle ID 是 `io.github.longmeidao.peach.app`,80/443 的转发落在 pf anchor `io.github.longmeidao.peach`。三个标识都取自 `src/peach/appid.py`,`setup_macos_port80.sh` 里那份 shell 字面量由 `tests/test_tray.py` 钉住一致。+- 标识变更在 Mac 上生效要跑一遍下面这串,遗留的 LaunchAgent 与 pf anchor 由 `install` 自己清掉:++```bash+launchctl bootout gui/$(id -u)/gg.lmd.peach.tray || true+python scripts/install_macos_agent.py install+sudo sh scripts/setup_macos_port80.sh install+python scripts/install_macos_agent.py status+launchctl print gui/$(id -u)/io.github.longmeidao.peach.tray | grep -E '^\s+pid'+launchctl print gui/$(id -u)/gg.lmd.peach.tray # 期望「Could not find service」+sudo pfctl -a io.github.longmeidao.peach -s nat+curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' http://peach.local/healthz+curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healthz+```++ 验收四项:菜单栏只出现一个 Peach 图标且 `status` 报「已加载」;`launchctl print` 的 pid 就是那个菜单栏进程;`pfctl -s nat` 列出 80 → 8900、443 → 8443 两条 rdr;两条 `/healthz` 都回 200。`peach.local` 换成本机 `[server].mdns_name` 的值。- 发布入口是 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 生成方形 Logo 与多尺寸 `.ico`,再构建单一 `dist/Peach/Peach.exe`;无参数运行托盘,`serve`/`migrate` 运行 CLI。桌面快捷方式由 `scripts/create_desktop_shortcut.ps1` 创建,自启动只由 `scripts/manage_tray_startup.ps1` 管理。- 对外发布由 `.github/workflows/release.yml` 承担:推 `v<__version__>` 形式的 tag(`v0.7.13` ↔ `0.7.13`)就在 GitHub 上跑 `build_windows.ps1` 与 `build_macos_app.py`,产出 `Peach-<版本>-windows-x64.zip` 与 `Peach-<版本>-macos-<arch>.zip` 并挂到同名 Release;tag 与 `__version__` 不一致在构建前失败。Release 正文取附注 tag 的正文,轻量 tag 由 GitHub 按提交历史生成。`workflow_dispatch` 只上传 artifact,不发布。- 刷新源码运行态不要用 Computer Use 点托盘:`python scripts/restart_windows_tray.py` 按精确 EXE 路径找到 pystray 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务;找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。diff --git a/scripts/build_macos_app.py b/scripts/build_macos_app.pyindex 0d2944af9..9599d01ba 100644--- a/scripts/build_macos_app.py+++ b/scripts/build_macos_app.py@@ -27,12 +27,13 @@ SRC_DIR = PROJECT_ROOT / "src"if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))+from peach.appid import MACOS_BUNDLE_ID, MACOS_LAUNCH_AGENT_LABELfrom peach.config import PROJECT_ROOT-BUNDLE_ID = "gg.lmd.peach.app"+BUNDLE_ID = MACOS_BUNDLE_ID#: LaunchAgent 的 label,双击 .app 时踢它。-LABEL = "gg.lmd.peach.tray"+LABEL = MACOS_LAUNCH_AGENT_LABEL# 这个外壳**不能**自己 exec 到解释器。macOS 26 上,主可执行文件是 exec 跳板时状态项# 注册不上:进程活着、NSStatusItem 也建出来了,但按钮窗口永远是 (0,0,34,0),菜单栏上# 什么都不出现(Apple FB21015611)。同一份代码由 launchd 直接拉起时实测diff --git a/scripts/install_macos_agent.py b/scripts/install_macos_agent.pyindex c589d5a55..3fb8dd6ef 100644--- a/scripts/install_macos_agent.py+++ b/scripts/install_macos_agent.py@@ -12,6 +12,11 @@ r"""把 Peach 菜单栏项注册成 LaunchAgent。所以登录自启走 LaunchAgent,而不是把 .app 放进登录项。`.app` 只留作双击入口,它做的事也只是 `launchctl kickstart`,不自己 exec 解释器。++`install` 会先清理 `peach.appid.LEGACY_MACOS_LAUNCH_AGENT_LABELS` 里的遗留标签:+`launchctl bootout` 只作用于给定的那一个 label,装着遗留标签的机器上会同时活着两个+菜单栏进程,两个都拿 `.local` 的 80/443 转发。清理的动作是逐个 bootout 再删掉+`~/Library/LaunchAgents/<遗留标签>.plist`;那台机器上没有遗留标签就静默跳过。"""from __future__ import annotations@@ -29,16 +34,21 @@ SRC_DIR = PROJECT_ROOT / "src"if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))+from peach.appid import LEGACY_MACOS_LAUNCH_AGENT_LABELS, MACOS_LAUNCH_AGENT_LABELfrom peach.config import LOG_DIR, PROJECT_ROOT-LABEL = "gg.lmd.peach.tray"+LABEL = MACOS_LAUNCH_AGENT_LABEL#: 交给 agent 的 PATH。Homebrew 的前缀在 launchd 的默认 PATH 里没有。AGENT_PATH = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"-def plist_path() -> Path:- return Path.home() / "Library" / "LaunchAgents" / f"{LABEL}.plist"+def launch_agents_dir() -> Path:+ return Path.home() / "Library" / "LaunchAgents"+++def plist_path(label: str = LABEL) -> Path:+ return launch_agents_dir() / f"{label}.plist"def build_plist(tray: Path) -> dict:@@ -66,6 +76,26 @@ def launchctl(*args: str) -> subprocess.CompletedProcess:encoding="utf-8", errors="replace")+def remove_legacy_agents(domain: str) -> list[str]:+ """卸掉遗留标签的 LaunchAgent 并删掉它的 plist,返回真正清掉的标签。++ `launchctl bootout` 只作用于给定的那一个 label,所以装新标签这一步碰不到遗留的+ 那份:它会继续开机自启一个菜单栏进程,继续在 80/443 上抢转发目标。判据取「已加载+ 或 plist 还在」,两者都不成立就静默跳过——多数机器没有遗留标签,不该为此打印噪音。+ """+ cleaned: list[str] = []+ for label in LEGACY_MACOS_LAUNCH_AGENT_LABELS:+ stale = plist_path(label)+ loaded = launchctl("print", f"{domain}/{label}").returncode == 0+ if not loaded and not stale.is_file():+ continue+ launchctl("bootout", f"{domain}/{label}")+ if stale.is_file():+ stale.unlink()+ cleaned.append(label)+ return cleaned++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description="注册 / 注销 Peach 菜单栏项的 LaunchAgent")parser.add_argument("action", choices=("install", "uninstall", "status"),@@ -94,6 +124,8 @@ def run(args: argparse.Namespace) -> int:if not args.tray.is_file():raise SystemExit(f"找不到 peach-tray:{args.tray}(先 pip install -e .)")+ for label in remove_legacy_agents(domain):+ print(f"已清理遗留 LaunchAgent {label}")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)))diff --git a/scripts/setup_macos_port80.sh b/scripts/setup_macos_port80.shindex 4bf6031f3..bc9620ae9 100644--- a/scripts/setup_macos_port80.sh+++ b/scripts/setup_macos_port80.sh@@ -22,7 +22,12 @@# sh scripts/setup_macos_port80.sh check # 只验证,不需要 rootset -eu-ANCHOR_NAME="gg.lmd.peach"+# 和 src/peach/appid.py 的 MACOS_PF_ANCHOR 必须一致;shell 里 import 不了 Python,+# 这两行由 tests/test_tray.py 钉住。+ANCHOR_NAME="io.github.longmeidao.peach"+# 已部署机器上装着的遗留 anchor 名(peach.appid.LEGACY_MACOS_PF_ANCHORS)。留着不清+# 会让 /etc/pf.conf 里多一条指向已删除文件的 load anchor,整份包过滤规则加载不起来。+LEGACY_ANCHOR_NAMES="gg.lmd.peach"ANCHOR_FILE="/etc/pf.anchors/${ANCHOR_NAME}"DAEMON="/Library/LaunchDaemons/${ANCHOR_NAME}.pf.plist"TARGET_PORT="${PEACH_PORT:-8900}"@@ -34,10 +39,12 @@ IFACE="${IFACE:-en0}"WORK="$(mktemp -d)"trap 'rm -rf "$WORK"' EXIT-# 去掉本脚本写过的行,并把 rdr-anchor 插回 translation 段。+# 去掉本脚本写过的行(含遗留 anchor 名那几行),并把 rdr-anchor 插回 translation 段。rebuild_conf() {- awk -v name="$ANCHOR_NAME" -v anchor_file="$ANCHOR_FILE" '- index($0, name) { next } # 幂等:先剥掉旧的+ awk -v name="$ANCHOR_NAME" -v anchor_file="$ANCHOR_FILE" -v legacy="$LEGACY_ANCHOR_NAMES" '+ BEGIN { split(legacy, stale, " ") }+ index($0, name) { next } # 幂等:本脚本写过的先剥掉+ { for (k in stale) if (stale[k] != "" && index($0, stale[k])) next }{ line[++n] = $0; if ($0 ~ /^[[:space:]]*(rdr|nat)-anchor/) last = n }END {for (i = 1; i <= n; i++) {@@ -49,6 +56,26 @@ rebuild_conf() {' "$1"}+# 只剥不加:uninstall 用它把两种 anchor 名的行都从 /etc/pf.conf 里去掉。+strip_conf() {+ awk -v name="$ANCHOR_NAME" -v legacy="$LEGACY_ANCHOR_NAMES" '+ BEGIN { split(legacy, stale, " ") }+ index($0, name) { next }+ { for (k in stale) if (stale[k] != "" && index($0, stale[k])) next }+ { print }+ ' "$1"+}++# 卸掉遗留 anchor 名的 LaunchDaemon 并删掉它的 anchor 文件。那个 daemon 每次开机都+# 重新加载一份指向它自己的规则,留着就和新的抢同一个 80/443 转发。没有就静默跳过。+remove_legacy() {+ for stale_name in $LEGACY_ANCHOR_NAMES; do+ stale_daemon="/Library/LaunchDaemons/${stale_name}.pf.plist"+ launchctl bootout system "$stale_daemon" 2>/dev/null || true+ rm -f "$stale_daemon" "/etc/pf.anchors/${stale_name}"+ done+}+if [ "$ACTION" = "check" ]; thenrebuild_conf /etc/pf.conf > "$WORK/pf.conf"if pfctl -n -f "$WORK/pf.conf" 2>"$WORK/err"; then@@ -67,13 +94,16 @@ fiif [ "$ACTION" = "uninstall" ]; thenlaunchctl bootout system "$DAEMON" 2>/dev/null || truerm -f "$DAEMON" "$ANCHOR_FILE"- grep -v "$ANCHOR_NAME" /etc/pf.conf > "$WORK/pf.conf"+ remove_legacy+ strip_conf /etc/pf.conf > "$WORK/pf.conf"cp "$WORK/pf.conf" /etc/pf.confpfctl -f /etc/pf.conf 2>/dev/null || trueecho "已移除 80/443 的重定向"exit 0fi+remove_legacy+cat > "$ANCHOR_FILE" <<RULES# 由 scripts/setup_macos_port80.sh 生成,勿手改。#diff --git a/src/peach/appid.py b/src/peach/appid.pynew file mode 100644index 000000000..9094d2a3f--- /dev/null+++ b/src/peach/appid.py@@ -0,0 +1,35 @@+"""macOS 上的反向域名标识:bundle ID、launchd 标签与 pf anchor 名。++同一个名字要在四个地方同时成立:`.app` 的 `CFBundleIdentifier`、+`~/Library/LaunchAgents/<标签>.plist` 的文件名与 `Label`、`launchctl` 的服务路径+`gui/<uid>/<标签>`,以及 `/etc/pf.conf` 里的 anchor 与 `/etc/pf.anchors/<名字>`。+任何一处对不上都不报错:`launchctl kickstart` 去踢一个不存在的服务、pf 加载一个空+anchor,表现是菜单栏图标不出现、`peach.local` 不带端口打不开,看上去像代码坏了。++所以标识只在这里写一次。单独成模块而不是并进 `peach.config`:它不是设置层的投影,+用户改不了它;也不放进 `peach.tray`,那个模块 import 了 pystray 与 PIL,macOS 的+构建脚本不该为了取一个字符串把整个托盘拉起来。`scripts/setup_macos_port80.sh` 是+POSIX shell,import 不了 Python,它那份字面量由 `tests/test_tray.py` 钉住与这里一致。+"""+from __future__ import annotations++#: 反向域名前缀。取仓库的 GitHub 归属而不是维护者的私有域名:下载者装上的东西不该+#: 带着别人的域名(ADR-0023 第 4 阶段)。+BUNDLE_PREFIX = "io.github.longmeidao.peach"++#: 双击 `.app` 时的 `CFBundleIdentifier`。+MACOS_BUNDLE_ID = f"{BUNDLE_PREFIX}.app"+#: 菜单栏项 LaunchAgent 的 `Label`,同时是它 plist 的文件名主干。+MACOS_LAUNCH_AGENT_LABEL = f"{BUNDLE_PREFIX}.tray"+#: pf 的 anchor 名,同时是 `/etc/pf.anchors` 下的文件名与 80/443 转发那个+#: LaunchDaemon 的 label 主干。+MACOS_PF_ANCHOR = BUNDLE_PREFIX++#: 已部署机器上装着的遗留标签。安装脚本装新标签之前要按这张表把旧 agent bootout 并+#: 删掉它的 plist:`launchctl bootout` 只认给定的那一个 label,留着的旧 agent 会继续+#: 跑一个菜单栏进程、继续占着 80/443 的转发。找不到就静默跳过。+#:+#: 这是一次性迁移。所有部署都跑过一轮之后,这张表连同用到它的分支一起删。+LEGACY_MACOS_LAUNCH_AGENT_LABELS: tuple[str, ...] = ("gg.lmd.peach.tray",)+#: 同上,pf 侧的遗留 anchor 名。+LEGACY_MACOS_PF_ANCHORS: tuple[str, ...] = ("gg.lmd.peach",)diff --git a/src/peach/tray.py b/src/peach/tray.pyindex d73e76255..5008182b0 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -18,6 +18,7 @@ import httpximport pystrayfrom PIL import Image+from .appid import MACOS_LAUNCH_AGENT_LABELfrom .certs import ensure_certificatefrom .config import (DATABASE_PATH, LOG_DIR, MDNS_HOSTNAME, PROJECT_ROOT, REPLICATION_ENABLED,@@ -45,8 +46,8 @@ MACOS_TLS_PORT = 8443#: 高位端口(scripts/setup_macos_port80.sh)。OPEN_URL = f"https://{MDNS_HOSTNAME}/"-#: LaunchAgent 的标签,和 `scripts/install_macos_agent.py` 里那个必须一致。-LAUNCH_AGENT_LABEL = "gg.lmd.peach.tray"+#: LaunchAgent 的标签。托盘、安装脚本和 `.app` 外壳共用 `peach.appid` 这一处定义。+LAUNCH_AGENT_LABEL = MACOS_LAUNCH_AGENT_LABELdef ledger_menu_items(make_item, sync_ledger, take_ownership) -> list:diff --git a/tests/test_tray.py b/tests/test_tray.pyindex 228ad7a1b..acaa3437b 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -4,6 +4,7 @@ import inspectimport ioimport osimport plistlib+import reimport sysimport tempfileimport threading@@ -23,6 +24,8 @@ def load_script(name: str):return module+from peach import appid+from peach import tray as tray_modulefrom peach.config import SECRETS_DIRfrom peach.tray import (AlreadyRunning, PeachTray, ServiceManager, ServiceSpec, SingleInstance,@@ -573,7 +576,8 @@ class SourceSyncTests(unittest.TestCase):restart_tray_process(runner, uid=501)self.assertEqual(runner.call_args.args[0],- ["launchctl", "kickstart", "-k", "gui/501/gg.lmd.peach.tray"],+ ["launchctl", "kickstart", "-k",+ "gui/501/io.github.longmeidao.peach.tray"],)def test_sync_changes_restart_the_tray_and_failed_kickstart_restores_services(self):@@ -681,6 +685,90 @@ class MacAppBundleTests(unittest.TestCase):self.assertFalse((app / "Contents" / "MacOS" / "stale").exists())+class MacIdentityTests(unittest.TestCase):+ """bundle ID、launchd 标签与 pf anchor 名只有 `peach.appid` 一个来源。++ 这四处名字对不上时没有任何报错:`launchctl kickstart` 去踢一个不存在的服务、+ pf 加载一个空 anchor,表现只是菜单栏没图标、`peach.local` 不带端口打不开。+ 所以每个消费者都在这里对着同一处常量核一遍。+ """++ def setUp(self):+ self.shell = (ROOT / "scripts" / "setup_macos_port80.sh").read_text(encoding="utf-8")++ def test_every_consumer_takes_the_identifier_from_peach_appid(self):+ self.assertEqual(tray_module.LAUNCH_AGENT_LABEL, appid.MACOS_LAUNCH_AGENT_LABEL)+ self.assertEqual(load_script("build_macos_app").BUNDLE_ID, appid.MACOS_BUNDLE_ID)+ self.assertEqual(load_script("build_macos_app").LABEL,+ appid.MACOS_LAUNCH_AGENT_LABEL)+ self.assertEqual(load_script("install_macos_agent").LABEL,+ appid.MACOS_LAUNCH_AGENT_LABEL)++ 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,+ appid.MACOS_PF_ANCHOR):+ self.assertTrue(value.startswith("io.github."), value)++ def test_the_shell_script_pins_the_same_anchor_names(self):+ """POSIX shell import 不了 Python,那两行字面量只能由这条用例守住。"""+ found = dict(re.findall(r'^(ANCHOR_NAME|LEGACY_ANCHOR_NAMES)="([^"]*)"',+ self.shell, re.MULTILINE))+ self.assertEqual(found.get("ANCHOR_NAME"), appid.MACOS_PF_ANCHOR)+ self.assertEqual(found.get("LEGACY_ANCHOR_NAMES"),+ " ".join(appid.LEGACY_MACOS_PF_ANCHORS))++ def test_the_port_forward_script_clears_the_legacy_anchor_on_both_paths(self):+ """遗留 anchor 的那份 LaunchDaemon 每次开机都抢同一个 80/443 转发目标。"""+ self.assertIn("remove_legacy()", self.shell)+ uninstall = self.shell.split('if [ "$ACTION" = "uninstall" ]', 1)[1]+ self.assertIn("remove_legacy", uninstall)+ self.assertIn("strip_conf /etc/pf.conf", uninstall)+++class MacLegacyAgentTests(unittest.TestCase):+ """装新标签之前先卸掉遗留标签的 LaunchAgent。++ `launchctl bootout` 只作用于给定的那一个 label,装新标签这一步碰不到遗留的那份:+ 它会继续开机自启一个菜单栏进程,也继续占着 80/443 的转发。+ """++ def setUp(self):+ self.module = load_script("install_macos_agent")+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.agents = Path(tmp.name).resolve() / "LaunchAgents"+ self.agents.mkdir()+ self.module.launch_agents_dir = lambda: self.agents+ self.calls: list[tuple[str, ...]] = []++ def _launchctl(self, *args: str, loaded: bool):+ self.calls.append(args)+ returncode = 0 if (args[0] == "print" and loaded) else 1+ return Mock(returncode=returncode, stdout="", stderr="")++ def test_installing_boots_out_the_legacy_label_and_deletes_its_plist(self):+ legacy = appid.LEGACY_MACOS_LAUNCH_AGENT_LABELS[0]+ stale = self.agents / f"{legacy}.plist"+ stale.write_bytes(b"stale")+ self.module.launchctl = lambda *args: self._launchctl(*args, loaded=True)++ self.assertEqual(self.module.remove_legacy_agents("gui/501"), [legacy])+ self.assertFalse(stale.exists())+ self.assertIn(("bootout", f"gui/501/{legacy}"), self.calls)++ def test_a_machine_without_the_legacy_label_is_left_alone(self):+ self.module.launchctl = lambda *args: self._launchctl(*args, loaded=False)+ self.assertEqual(self.module.remove_legacy_agents("gui/501"), [])+ self.assertEqual([args[0] for args in self.calls], ["print"])++ def test_install_clears_the_legacy_label_before_writing_the_new_plist(self):+ """顺序反了就会把刚装好的那份又 bootout 掉一次,白等一轮超时。"""+ source = inspect.getsource(self.module.run)+ self.assertLess(source.index("remove_legacy_agents"),+ source.index("plistlib.dumps"))++class TrayCommandLineTests(unittest.TestCase):"""`peach-tray` 的参数解析先于一切进程级副作用。