Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(desktop): 构建双架构 macOS 独立应用并精简托盘状态

Peach local maintenance004f0fd8d605
diff --git a/README.en.md b/README.en.md
index ad3238cc0..ab107557f 100644
--- a/README.en.md
+++ b/README.en.md
@@ -92,6 +92,10 @@ The full installer includes media tools for offline installation. The smaller li
Test builds are unsigned. If Windows says “Windows protected your PC”, confirm the file came from this project's Releases, then choose “More info → Run anyway”. See the [Windows guide](docs/TESTING_DESKTOP.md) for installation, updates and troubleshooting.
+### Build on macOS
+
+Build a self-contained `.app` and DMG locally on macOS. Running it requires neither Python, a source checkout, nor another computer. See [the macOS build guide](docs/OPERATIONS.md#macos-独立测试包).
+
### Run from source (Windows, macOS)
Requires Git, uv and Python 3.14 or newer. See [running from source](docs/OPERATIONS.md#从源码运行windowsmacos).
diff --git a/README.md b/README.md
index 126526d00..64cb0ce6f 100644
--- a/README.md
+++ b/README.md
@@ -92,6 +92,10 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
测试版尚未签名。若 Windows 提示「已保护你的电脑」,确认来自本项目的 Release,再点「更多信息 → 仍要运行」。安装、更新和故障排查见 [Windows 使用说明](docs/TESTING_DESKTOP.md)。
+### macOS 本机构建
+
+macOS 可在本机构建独立 `.app` 与 DMG,运行不需要 Python、源码或另一台电脑。构建与安装见 [macOS 独立测试包](docs/OPERATIONS.md#macos-独立测试包)。
+
### 从源码运行(Windows、macOS)
需要 Git、uv 和 Python 3.14 或更高,步骤见[源码运行](docs/OPERATIONS.md#从源码运行windowsmacos)。
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 17ea7d28c..4be43e59b 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -19,6 +19,34 @@ macOS 安装依赖:`uv sync --locked --python 3.14 --extra macos`。完成后
托盘会打开浏览器中的首次设置页。源码运行不需要下载 Windows 安装包。
+## macOS 独立测试包
+
+在 macOS 的项目目录安装构建依赖:
+
+```sh
+MACOSX_DEPLOYMENT_TARGET=11.0 uv sync --locked --extra build --extra macos
+```
+
+构建包含 Python、页面、迁移和资源的应用与 DMG:
+
+```sh
+./.venv/bin/python -X utf8 scripts/build_macos_standalone.py
+```
+
+产物在 `dist/macos.noindex/<架构>/`,构建副本避开 Spotlight 索引;日常使用只保留 Applications 里的应用,测试结束卸载已挂载的安装镜像。Apple Silicon 使用 `arm64`,Intel 使用 `x86_64`;分别用对应架构的 Python 与依赖构建。`--target-arch` 显式指定目标,解释器架构不匹配会停止,两个包不混合原生扩展,也不直接合并成 universal2。Intel 构建可在 Intel Mac 或 Rosetta 下的 x86_64 Python 环境完成;Rosetta 验收不能代替 Intel 真机和较旧 macOS 的验收。
+
+源码开发外壳 `build_macos_app.py` 默认输出到 `dist/macos-source.noindex/`,依赖本机 venv 与 LaunchAgent;不要把它当作独立应用安装。
+
+构建脚本读取随包 Mach-O 的系统版本下限,填入 `LSMinimumSystemVersion` 并重新签名。构建解释器也必须支持目标系统;Homebrew Python 可能要求构建机的系统版本。`watchdog` 等本机编译扩展若命中旧缓存,需带部署目标和对应的 `ARCHFLAGS`,通过 `uv sync --locked --extra build --extra macos --no-cache --reinstall-package watchdog --no-binary-package watchdog` 重编,再核对产物报告的 `minimum_macos`。
+
+打开匹配架构的 DMG,把 `Peach.app` 拖入 Applications,再打开应用完成首次设置。菜单栏提供打开页面、重启和退出入口;数据默认保存在 `~/Library/Application Support/Peach/peach-data`,可用 `PEACH_DATA_ROOT` 指定独立目录。
+
+Mac 与 Windows 托盘的首层只显示简短状态与提醒数量,展开状态子菜单按行查看服务和媒体来源。长地址与路径会缩略,子菜单中的「查看完整配置」保留完整设置入口;提醒消失后会随下一轮健康检查更新。
+
+单机设置默认关闭账本复制,不需要 Windows、SMB、LaunchAgent 或系统端口转发。各台电脑各自保存数据;共享馆藏仍按下文的[双机复制](#两台电脑之间的复制)配置,离线修改不能自动合并。已有数据目录不会自动导入。
+
+这条构建路径使用本地 ad-hoc 签名,未完成 Developer ID 签名和 Apple 公证,不作为已签名发行包发布。DMG 只分发应用,不安装系统服务;需要集中部署系统组件时再评估 PKG。转码与抽帧使用本机 FFmpeg,本测试包未内置媒体工具、cloudflared 或 macOS 在线更新安装器。
+
## 首次运行与设置文件
第一次打开 Peach 有两种方式,结果相同:
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 54c00a329..6b373995a 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -1,5 +1,11 @@
# 复用清单
+## macOS 独立构建
+
+独立应用复用项目已有的 PyInstaller 6.22.3(GPL-2.0-or-later,带发行例外),由 macOS 原生 bootloader 承载 Python 3.14 与 Cocoa 菜单栏,资源与 CLI 入口沿用现有桌面实现。镜像使用系统自带的 `hdiutil`,无需新增运行时依赖。构建与签名依据 [PyInstaller macOS 文档](https://www.pyinstaller.org/en/stable/usage.html)和 [Apple 分发文档](https://developer.apple.com/documentation/xcode/packaging-mac-software-for-distribution)。
+
+Peach 负责独立数据目录、首启、构建身份和资源清单。arm64 与 x86_64 使用各自的 Python 和原生扩展,按 [PyInstaller 架构约束](https://pyinstaller.org/en/stable/feature-notes.html#macos-multi-arch-support)分别生成;不使用 lipo 合并冻结程序。应用不安装系统组件,采用 DMG 拖放安装;PKG 的系统级安装流程不属于这条路径。源码运行的 LaunchAgent 外壳继续使用自己的构建入口。独立制品的启动与读写验收使用隔离数据目录,不改变真实 ledger 或双机配置。
+
## 硬件转码后端
整片 MP4 与 HLS 复用现有 FFmpeg 的 CUDA / NVENC、VAAPI、`scale_vaapi` 与 `hwupload`,不引入 Python 命令包装库。Windows 发行工具固定为 FFmpeg 9.0.2(GPL-3.0-or-later,来源清单见 `scripts/ffmpeg-sources.json`);Linux 镜像使用 Debian trixie 的 FFmpeg、`mesa-va-drivers` 与 `vainfo`,随 Debian 安全更新取得版本,不另行复制驱动代码。Mesa 按上游各组件许可证分发,驱动增加的镜像体积由构建决定,AMD 需要宿主机 amdgpu 与固件。设备参数和硬件解码接口依据 [FFmpeg 官方文档](https://ffmpeg.org/ffmpeg.html#Advanced-Video-options),驱动范围依据 [Debian VAAPI 说明](https://wiki.debian.org/HardwareVideoAcceleration)。
diff --git a/scripts/build_macos_app.py b/scripts/build_macos_app.py
index e0546692c..73845953a 100644
--- a/scripts/build_macos_app.py
+++ b/scripts/build_macos_app.py
@@ -8,7 +8,7 @@
macOS 的标准做法是打成 bundle 并在 `Info.plist` 里声明 `LSUIElement`:只在菜单栏
出现,不占 Dock、不进 ⌘Tab。外壳本身只有一个 plist 和一个 exec 到项目 venv 的脚本
-——和 Windows 那边一样,托盘不是可移动的独立发行版,服务进程仍由 venv 承担。
+——这是源码开发入口,服务进程仍由 venv 承担。独立发行包走 build_macos_standalone.py。
"""
from __future__ import annotations
@@ -104,7 +104,7 @@ def build_frontend_bundles() -> None:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="生成 macOS 菜单栏项的 .app 外壳")
- parser.add_argument("--destination", type=Path, default=PROJECT_ROOT / "dist")
+ parser.add_argument("--destination", type=Path, default=PROJECT_ROOT / "dist" / "macos-source.noindex")
parser.add_argument("--tray", type=Path, default=PROJECT_ROOT / ".venv" / "bin" / "peach-tray")
return parser
diff --git a/scripts/build_macos_standalone.py b/scripts/build_macos_standalone.py
new file mode 100644
index 000000000..a75aa319b
--- /dev/null
+++ b/scripts/build_macos_standalone.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+"""构建包含 Python 运行时的 macOS 应用与拖放安装镜像。"""
+from __future__ import annotations
+
+import argparse
+from datetime import datetime, timezone
+import json
+import os
+from pathlib import Path
+import platform
+import plistlib
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+from peach import __version__
+
+
+def minimum_system_version(app: Path) -> str:
+ """以随包 Mach-O 的实际最低系统版本填写应用声明。"""
+ magic = {b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf"}
+ binaries = []
+ for path in app.rglob("*"):
+ if path.is_symlink() or not path.is_file():
+ continue
+ with path.open("rb") as stream:
+ if stream.read(4) in magic:
+ binaries.append(str(path))
+ if not binaries:
+ raise ValueError("应用内没有 Mach-O 可执行文件")
+ result = subprocess.run(["otool", "-l", *binaries], capture_output=True,
+ text=True, encoding="utf-8", check=True)
+ versions = re.findall(r"cmd LC_(?:BUILD_VERSION|VERSION_MIN_MACOSX)\s+cmdsize \d+\s+"
+ r"(?:platform \d+\s+)?(?:minos|version) ([\d.]+)", result.stdout)
+ if not versions:
+ raise ValueError("未取得随包二进制的 macOS 版本下限")
+ return max(versions, key=lambda value: tuple(int(part) for part in value.split(".")))
+
+
+def package_dmg(app: Path, destination: Path) -> Path:
+ """镜像只携带应用、Applications 快捷入口与许可证。"""
+ if not (app / "Contents" / "MacOS" / "Peach").is_file():
+ raise FileNotFoundError(f"找不到应用可执行文件:{app}")
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix="peach-dmg-") as directory:
+ staging = Path(directory)
+ shutil.copytree(app, staging / "Peach.app", symlinks=True)
+ (staging / "Applications").symlink_to("/Applications", target_is_directory=True)
+ shutil.copy2(ROOT / "LICENSE", staging / "LICENSE.txt")
+ subprocess.run([
+ "hdiutil", "create", "-volname", "Peach", "-srcfolder", str(staging),
+ "-format", "UDZO", "-ov", str(destination),
+ ], check=True)
+ return destination
+
+
+def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None) -> dict[str, str]:
+ if sys.platform != "darwin":
+ raise SystemExit("macOS 应用必须在 macOS 上构建")
+ if (ROOT / "resources" / "seed").exists():
+ raise SystemExit("本机实体导出不能进入发行资源")
+ architecture = target_arch or platform.machine()
+ if architecture not in {"arm64", "x86_64"} or architecture != platform.machine():
+ raise SystemExit("目标架构必须与当前 Python 一致;请使用 arm64 或 x86_64 Python 及对应依赖构建")
+ from build_macos_app import build_frontend_bundles
+
+ build_frontend_bundles()
+ destination = destination.resolve()
+ work = ROOT / "build" / "macos-standalone" / architecture
+ work.mkdir(parents=True, exist_ok=True)
+ commit = subprocess.run(["git", "-C", str(ROOT), "rev-parse", "HEAD"],
+ capture_output=True, text=True, encoding="utf-8", check=True).stdout.strip()
+ identity = {
+ "commit": commit, "version": __version__,
+ "built_at": datetime.now(timezone.utc).isoformat(), "architecture": architecture,
+ "dirty": bool(subprocess.run(
+ ["git", "-C", str(ROOT), "status", "--porcelain"],
+ capture_output=True, text=True, encoding="utf-8", check=True).stdout.strip()),
+ }
+ (work / "build-info.json").write_text(json.dumps(identity), encoding="utf-8")
+ subprocess.run([
+ sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean",
+ "--distpath", str(destination), "--workpath", str(work / "app"),
+ str(ROOT / "scripts" / "peach_macos.spec"),
+ ], check=True, cwd=ROOT, env={**os.environ, "PEACH_MACOS_BUILD_INFO": str(work / "build-info.json"),
+ "PEACH_MACOS_TARGET_ARCH": architecture})
+ app = destination / "Peach.app"
+ minimum = minimum_system_version(app)
+ info_path = app / "Contents" / "Info.plist"
+ info = plistlib.loads(info_path.read_bytes())
+ info["LSMinimumSystemVersion"] = minimum
+ info_path.write_bytes(plistlib.dumps(info))
+ subprocess.run(["codesign", "--force", "--sign", "-", str(app)], check=True)
+ subprocess.run(["codesign", "--verify", "--deep", "--strict", str(app)], check=True)
+ result = {"app": str(app), "version": __version__, "commit": commit,
+ "architecture": architecture, "minimum_macos": minimum}
+ if dmg:
+ image = destination / f"Peach-{__version__}-macos-{architecture}.dmg"
+ result["dmg"] = str(package_dmg(app, image))
+ # COLLECT 是 BUNDLE 的中间目录;只留下可分发的应用,避免重复占用与系统索引。
+ shutil.rmtree(destination / "Peach")
+ return result
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--destination", type=Path)
+ parser.add_argument("--target-arch", choices=("arm64", "x86_64"), default=platform.machine())
+ parser.add_argument("--no-dmg", action="store_true", help="只生成独立应用")
+ args = parser.parse_args()
+ destination = args.destination or ROOT / "dist" / "macos.noindex" / args.target_arch
+ print(json.dumps(build(destination, dmg=not args.no_dmg, target_arch=args.target_arch), ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/peach_macos.spec b/scripts/peach_macos.spec
new file mode 100644
index 000000000..d4e6a6a7d
--- /dev/null
+++ b/scripts/peach_macos.spec
@@ -0,0 +1,42 @@
+# -*- mode: python ; coding: utf-8 -*-
+"""macOS 独立应用:原生启动器、内置解释器与只读资源。"""
+import json
+import os
+from pathlib import Path
+import sys
+
+from PyInstaller.utils.hooks import collect_all, copy_metadata
+
+root = Path(SPECPATH).parent
+sys.path.insert(0, str(root / "src"))
+from peach.appid import MACOS_BUNDLE_ID
+
+identity = Path(os.environ["PEACH_MACOS_BUILD_INFO"])
+version = json.loads(identity.read_text(encoding="utf-8"))["version"]
+datas = [(str(root / name), name) for name in ("web", "migrations", "resources")]
+datas += [(str(identity), "."), (str(root / "scripts" / "standalone.txt"), ".")]
+datas += copy_metadata("sentry-sdk")
+binaries = []
+hiddenimports = [
+ "uvicorn.logging", "uvicorn.loops.auto", "uvicorn.protocols.http.auto",
+ "uvicorn.protocols.websockets.auto", "uvicorn.lifespan.on", "peach.menubar",
+]
+for package in ("curl_cffi", "resvg_py"):
+ package_data, package_binaries, package_imports = collect_all(package)
+ datas += package_data
+ binaries += package_binaries
+ hiddenimports += package_imports
+
+a = Analysis([str(root / "scripts" / "build_app_entry.py")],
+ pathex=[str(root / "src")], binaries=binaries, datas=datas,
+ hiddenimports=hiddenimports, excludes=["tkinter"])
+pyz = PYZ(a.pure)
+exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name="Peach",
+ console=False, argv_emulation=False, strip=False, upx=False,
+ target_arch=os.environ["PEACH_MACOS_TARGET_ARCH"])
+collection = COLLECT(exe, a.binaries, a.datas, strip=False, upx=False, name="Peach")
+app = BUNDLE(collection, name="Peach.app", icon=str(root / "resources" / "peach.icns"),
+ bundle_identifier=MACOS_BUNDLE_ID,
+ info_plist={"CFBundleName": "Peach", "CFBundleDisplayName": "Peach 蜜桃",
+ "CFBundleShortVersionString": version, "CFBundleVersion": version,
+ "LSUIElement": True, "NSHighResolutionCapable": True})
diff --git a/scripts/smoke_desktop.py b/scripts/smoke_desktop.py
index d993c01d0..3b4f22f40 100644
--- a/scripts/smoke_desktop.py
+++ b/scripts/smoke_desktop.py
@@ -365,7 +365,8 @@ def assert_standalone_tunnel(configuration: dict) -> None:
assert tunnel['available'] is True
-def complete_first_run(opener, base: str, media: Path, port: int, password: str, *, data_root: Path | None = None) -> None:
+def complete_first_run(opener, base: str, media: Path, port: int, password: str, *,
+ data_root: Path | None = None, media_root: str | None = None) -> None:
"""首启服务的薄壳与页面包都取得到,再按页面包的提交形态完成一次设置。"""
with opener.open(base + "/", timeout=5) as response:
assert 'data-page="setup"' in response.read().decode("utf-8")
@@ -376,6 +377,8 @@ def complete_first_run(opener, base: str, media: Path, port: int, password: str,
"port": str(port), "mdns_name": "peach", "access_enabled": True,
"access_password": password, "access_confirm": password,
"remote_reporting": {"usage": False, "errors": False}}
+ if media_root is not None:
+ answers["media_dir"][0]["root"] = media_root
if data_root is not None:
answers["data_root"] = str(data_root)
request = urllib.request.Request(base + "/api/setup", data=json.dumps(answers).encode(),
diff --git a/scripts/smoke_macos.py b/scripts/smoke_macos.py
new file mode 100644
index 000000000..8045a37fa
--- /dev/null
+++ b/scripts/smoke_macos.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+"""在源码树外、无开发工具的 PATH 下验证 macOS 应用。"""
+from __future__ import annotations
+
+import argparse
+import http.cookiejar
+import json
+from pathlib import Path
+import shutil
+import socket
+import subprocess
+import tempfile
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from smoke_desktop import assert_requires_login, complete_first_run, smoke_environment, wait_health
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("app", type=Path)
+ args = parser.parse_args()
+ app = args.app.resolve(strict=True)
+ with tempfile.TemporaryDirectory(prefix="peach-macos-smoke-") as directory:
+ root = Path(directory).resolve()
+ shutil.copytree(app, root / "Peach.app", symlinks=True)
+ executable = root / "Peach.app" / "Contents" / "MacOS" / "Peach"
+ data, media = root / "data", root / "media"
+ media.mkdir()
+ environment = smoke_environment(data)
+ with socket.socket() as reservation:
+ reservation.bind(("127.0.0.1", 0))
+ port = reservation.getsockname()[1]
+ command = [str(executable), "serve", "--host", "127.0.0.1", "--port", str(port),
+ "--no-ledger-sync", "--no-mdns"]
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
+ urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
+ base = f"http://127.0.0.1:{port}"
+ process = None
+ log_path = root / "runtime.log"
+ with log_path.open("wb") as log:
+ try:
+ process = subprocess.Popen([*command, "--setup"], cwd=root, env=environment,
+ stdout=log, stderr=log)
+ wait_health(opener, base, process, log_path)
+ password = "macos-smoke-password"
+ complete_first_run(opener, base, media, port, password, media_root="B:/")
+ process.terminate()
+ process.wait(timeout=20)
+ process = subprocess.Popen(command, cwd=root, env=environment, stdout=log, stderr=log)
+ health = wait_health(opener, base, process, log_path)
+ assert health["ledger_sync"] == "disabled", health
+ assert_requires_login(opener, base)
+ request = urllib.request.Request(base + "/login",
+ data=urllib.parse.urlencode({"token": password, "days": "0"}).encode(),
+ headers={"Origin": base})
+ with opener.open(request, timeout=10) as response:
+ assert response.status == 200
+ for path in ("/", "/dist/peach-app.js", "/dist/peach-app.css", "/api/items",
+ "/healthz?ready=1"):
+ with opener.open(base + path, timeout=30) as response:
+ assert response.status == 200, path
+ with opener.open(base + "/api/configuration", timeout=15) as response:
+ configuration = json.load(response)
+ second = root / "second-media"
+ second.mkdir()
+ request = urllib.request.Request(base + "/api/configuration",
+ data=json.dumps({"media_sources": configuration["media_sources"] +
+ [{"location": "pikpak", "root": "A:/", "path": str(second)}],
+ "port": port, "revision": configuration["revision"]}).encode(),
+ headers={"Origin": base, "Content-Type": "application/json"})
+ with opener.open(request, timeout=15) as response:
+ assert json.load(response)["saved"]
+ assert (data / "config.previous.toml").is_file()
+ print(json.dumps({"ok": True, "version": health.get("version"),
+ "checks": ["relocated-app", "no-development-tools", "first-run", "migrations",
+ "standalone-ledger", "login", "frontend", "configuration-write"]}))
+ except BaseException as error:
+ if isinstance(error, urllib.error.HTTPError):
+ print(error.read().decode("utf-8", "replace"))
+ print(log_path.read_text(errors="replace"))
+ raise
+ finally:
+ if process is not None and process.poll() is None:
+ process.terminate()
+ process.wait(timeout=20)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 5bb2247dd..ed68f5aa6 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -69,7 +69,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_providers.py", "test_segments.py", "test_streaming.py",
"test_subtitles.py", "test_transcodes.py", "test_hardware_transcode.py", "test_strm.py",
"test_guangya_sources.py", "test_media_sources.py"),
- "sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray*.py", "test_log_retention.py",
+ "sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray*.py", "test_macos_standalone.py", "test_log_retention.py",
"test_mdns.py", "test_netwatch.py", "test_certs.py",
"test_review_mirror.py", "test_runtime_prepare.py"),
"metadata": ("test_custom_metadata.py", "test_scraping_access.py", "test_browser_transport.py", "test_metadata*.py", "test_genre_taxonomy.py", "test_processing_control.py",
@@ -110,7 +110,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_agent_worktree.py", "test_test_evidence.py", "test_test_environment.py", "test_dependency_policy.py",
"test_version_bump.py", "test_changelog.py", "test_release_due.py",
"test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py",
- "test_buildinfo.py", "test_versioning.py",
+ "test_buildinfo.py", "test_versioning.py", "test_macos_standalone.py",
"test_windows_update.py", "test_release_updates.py", "test_automatic_updates.py", "test_standalone_update.py", "test_certs.py", "test_config.py",
"test_fsutil.py", "test_desktop_settings.py", "test_desktop_installer.py",
"test_job_status.py", "test_jobs.py", "test_task_runs.py", "test_followups.py", "test_update_tasks.py",
@@ -146,7 +146,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_platform.py", "test_mount.py", "test_tray.py", "test_certs.py",
"test_folder_picker.py", "test_fsutil.py", "test_runtime_consistency.py",
"test_subprocess_encoding.py", "test_windows_update.py", "test_buildinfo.py"),
- "packaging": ("test_dependency_policy.py", "test_buildinfo.py", "test_onboarding.py",
+ "packaging": ("test_dependency_policy.py", "test_buildinfo.py", "test_onboarding.py", "test_macos_standalone.py",
"test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py",
"test_cloudflared_packaging.py", "test_desktop_installer.py",
"test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py"),
@@ -185,6 +185,7 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"src/peach/routes_pages.py": ("catalog", "tooling", "web"),
# 托盘既是 sync 域的服务编排,也被版本与桌面设置那些 tooling 测试读源码。
"src/peach/tray.py": ("sync", "tooling"),
+ "src/peach/menubar.py": ("sync", "tooling"),
# 托盘子服务与隧道的 cloudflared 共用这份 Job Object;两边的测试都要跑到。
"src/peach/process_job.py": ("tooling", "sync"),
# 托盘重启的实现由 `test_restart_windows_tray.py` 验,模块名推不出来。
diff --git a/src/peach/menubar.py b/src/peach/menubar.py
index 5f7becf8c..7f9743040 100644
--- a/src/peach/menubar.py
+++ b/src/peach/menubar.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import io
import logging
import threading
+from dataclasses import dataclass
from typing import Callable
import AppKit
@@ -72,63 +73,80 @@ class _Target(AppKit.NSObject):
self._dispatch(sender)
+@dataclass(frozen=True)
+class Submenu:
+ """原生子菜单;每次刷新取得当前的服务与提醒行。"""
+
+ items: Callable[[], list[tuple[object, object]]]
+
+
class MenuBarApp:
"""一个菜单栏状态项,外加它的下拉菜单。
- `items` 是 (标题, 处理函数或 None) 的序列;处理函数为 None 表示只读信息行,
- 标题可以是可调用对象,每次打开菜单时重新求值。
+ `items` 是 (标题, 处理函数、Submenu 或 None) 的序列;None 表示只读信息行。
+ 动态标题和子菜单每五秒刷新,内容不变时保留原菜单。
"""
def __init__(
self,
image: Image.Image,
tooltip: str,
- items: list[tuple[object, Callable[[], None] | None]],
+ items: list[tuple[object, Callable[[], None] | Submenu | 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]] = {}
+ self._items = items
+ self._handlers: dict[int, Callable[[], None]] = {}
+ self._target = _Target.alloc().initWithHandlers_(self._handlers)
+ self._rendered = None
+
+ self.item = AppKit.NSStatusBar.systemStatusBar().statusItemWithLength_(
+ AppKit.NSVariableStatusItemLength)
+ self.item.button().setImage_(nsimage(image))
+ self.item.button().setToolTip_(tooltip)
+ self.refresh_titles()
+ self.item.setVisible_(True)
+
+ def _resolve(self, items):
+ return [(title() if callable(title) else title,
+ self._resolve(handler.items()) if isinstance(handler, Submenu) else handler)
+ for title, handler in items]
+
+ def _menu(self, items):
menu = AppKit.NSMenu.alloc().init()
- # 每次打开前刷新动态标题(状态、版本这些)。
menu.setAutoenablesItems_(False)
- for index, (title, handler) in enumerate(items):
+ for title, handler in 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 = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(str(title), None, "")
+ if isinstance(handler, list):
+ entry.setSubmenu_(self._menu(handler))
+ entry.setEnabled_(True)
+ elif 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:
+ index = len(self._handlers)
+ self._handlers[index] = handler
+ entry.setTag_(index)
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
+ menu.addItem_(entry)
+ return menu
def refresh_titles(self) -> None:
- """重算动态标题。菜单是现取现画的,打开前刷一次就够。"""
- for entry, title in self._titles:
- if callable(title):
- entry.setTitle_(title())
+ """同时更新摘要与子菜单;已消失的提醒和旧动作不留在原生菜单里。"""
+ rendered = self._resolve(self._items)
+ if rendered == self._rendered:
+ return
+ self._handlers.clear()
+ self.menu = self._menu(rendered)
+ self.item.setMenu_(self.menu)
+ self._rendered = rendered
def placement(self) -> tuple[float, float, float, float] | None:
"""状态项在屏幕上的位置;拿不到窗口说明它根本没被放上菜单栏。"""
diff --git a/src/peach/tray.py b/src/peach/tray.py
index f8180c960..83b58a62a 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -112,6 +112,12 @@ READINESS_LABELS = {
TRAY_RESTART_WAIT = 300.0
+def menu_text(value: str, limit: int = 48) -> str:
+ """原生菜单不折行;详细路径留在配置页,菜单中的每行限制宽度。"""
+ text = " ".join(value.split())
+ return text if len(text) <= limit else text[:limit - 1] + "…"
+
+
def tray_restart_required(changed_paths: tuple[str, ...]) -> bool:
"""这次更新动没动托盘自己的代码。"""
return any(path in TRAY_SOURCES for path in changed_paths)
@@ -280,6 +286,7 @@ class ServiceManager:
self._last_health: dict[str, tuple[bool, str]] = {
spec.name: (False, "未检测") for spec in specs
}
+ self._mount_warnings: dict[str, tuple[str, ...]] = {}
self._lock = threading.RLock()
def healthy(self, spec: ServiceSpec) -> bool:
@@ -287,6 +294,7 @@ class ServiceManager:
# HTTP 代理,httpx 默认读它(urllib.getproxies 在 macOS 走系统配置),于是
# 探测 http://127.0.0.1 的请求被送进代理、由代理回 503——服务明明活着,
# 状态却显示「未运行」。实测 Stash 开着时就是这样,HTTPS 探测不受影响。
+ warnings: tuple[str, ...] = ()
try:
response = self._health_get(
spec.health_url, timeout=0.5, verify=spec.verify, trust_env=False,
@@ -295,13 +303,15 @@ class ServiceManager:
ok = response.status_code == 200 and payload.get("ok") is True
detail = "" if ok else f"状态码 {response.status_code}"
if ok and isinstance(payload.get("media_mounts"), dict):
- warnings = payload["media_mounts"].get("warnings", [])
- if isinstance(warnings, list):
- detail = ";".join(value[:120] for value in warnings[:3] if isinstance(value, str))
+ values = payload["media_mounts"].get("warnings", [])
+ if isinstance(values, list):
+ warnings = tuple(value for value in values if isinstance(value, str) and value.strip())
+ detail = ";".join(value[:120] for value in warnings[:3])
except (httpx.HTTPError, OSError, ValueError, AttributeError):
ok, detail = False, "无响应"
with self._lock:
self._last_health[spec.name] = (ok, detail)
+ self._mount_warnings[spec.name] = warnings
return ok
@property
@@ -322,6 +332,27 @@ class ServiceManager:
parts.append(f"{spec.name.upper()} {state}")
return " · ".join(parts)
+ def status_summary(self) -> str:
+ """两种托盘共用的短状态;同一个挂载提醒不因 HTTP/HTTPS 重复计数。"""
+ with self._lock:
+ healthy = sum(self._last_health[spec.name][0] for spec in self.specs)
+ warnings = set(value for spec in self.specs
+ for value in self._mount_warnings.get(spec.name, ()))
+ state = ("运行中" if healthy == len(self.specs) else "部分服务异常") if healthy else "服务未运行"
+ return f"{state} · {len(warnings)} 项提醒" if warnings else state
+
+ def status_details(self) -> tuple[str, ...]:
+ """服务与挂载分行呈现,避免一行堆入所有来源。"""
+ with self._lock:
+ services = []
+ for spec in self.specs:
+ ok, detail = self._last_health[spec.name]
+ state = "正常" if ok else f"异常({detail})" if detail else "异常"
+ services.append(menu_text(f"{spec.name.upper()} {state}"))
+ warnings = dict.fromkeys(value for spec in self.specs
+ for value in self._mount_warnings.get(spec.name, ()))
+ return tuple(services + [menu_text(value) for value in warnings])
+
def replace_specs(
self, specs: tuple[ServiceSpec, ...], *, log_dir: Path | None = None,
extra_env: dict[str, str] | None = None,
@@ -338,6 +369,7 @@ class ServiceManager:
if extra_env is not None:
self._extra_env = dict(extra_env)
self._last_health = {spec.name: (False, "未检测") for spec in self.specs}
+ self._mount_warnings.clear()
def child_environment(self) -> dict[str, str]:
environment = os.environ.copy()
@@ -897,8 +929,8 @@ class SetupGate:
def status_line(self) -> str:
if self._waiting:
- return f"等待完成首次设置 · {self.manager.status()}"
- return self.manager.status()
+ return "等待完成首次设置"
+ return self.manager.status_summary()
def open(self) -> None:
self._open_browser(self.open_url())
@@ -1057,7 +1089,14 @@ class PeachTray:
pystray.Menu(
pystray.MenuItem(lambda _item: self.gate.open_label(), self.open, default=True),
pystray.MenuItem("配置 Peach", lambda *_: webbrowser.open(self.gate.open_url() + "configuration")),
- pystray.MenuItem(lambda _item: f"状态:{self.gate.status_line()}", None, enabled=False),
+ pystray.MenuItem(lambda _item: f"状态:{self.gate.status_line()}", pystray.Menu(
+ lambda: (
+ *(pystray.MenuItem(line, None, enabled=False)
+ for line in self.manager.status_details()),
+ pystray.MenuItem(menu_text(f"地址:{self.gate.open_url()}"), self.open),
+ pystray.MenuItem("查看完整配置", lambda *_: webbrowser.open(
+ self.gate.open_url() + "configuration")),
+ ))),
pystray.Menu.SEPARATOR,
pystray.MenuItem("同步开发进度", self.sync_source,
visible=lambda _: not standalone()),
@@ -1495,7 +1534,7 @@ def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = Non
pystray 的 darwin 后端漏了 activation policy 和图标尺寸两件必需的事,补齐等于
重写它那层封装,所以这里直接用 AppKit(见 `peach.menubar`)。Windows 继续走 pystray。
"""
- from .menubar import MenuBarApp
+ from .menubar import MenuBarApp, Submenu
gate = gate or SetupGate(manager, settings_file.active(), waiting=False)
versions = VersionManager()
@@ -1586,21 +1625,30 @@ def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = Non
def take_ownership() -> None:
run_ledger_action(take_ownership=True)
+ def open_configuration() -> None:
+ webbrowser.open(gate.open_url() + "configuration")
+
menu = MenuBarApp(
create_icon(template=True),
"Peach · 蜜桃",
[
(gate.open_label, gate.open),
- (lambda: f"状态:{gate.status_line()}", None),
- (lambda: f"地址:{gate.open_url()}", None),
+ (lambda: f"状态:{gate.status_line()}", Submenu(lambda: [
+ *((line, None) for line in manager.status_details()),
+ (menu_text(f"地址:{gate.open_url()}"), gate.open),
+ ("查看完整配置", open_configuration),
+ ])),
(None, None),
- ("同步开发进度", sync_source),
+ *((("同步开发进度", sync_source),) if not standalone() else ()),
*ledger_menu_items(
lambda label, action: (label, action), sync_ledger, take_ownership),
("重启服务", restart),
("查看日志", lambda: subprocess.run(["open", str(LOG_DIR)], check=False)),
- (lambda: f"版本 {state['snapshot'].package_version}"
- f" · {state['snapshot'].build_label}", None),
+ ("版本信息", Submenu(lambda: [
+ (f"Peach {state['snapshot'].package_version}", None),
+ (menu_text(state['snapshot'].build_label), None),
+ (menu_text(state['snapshot'].channel_label), None),
+ ])),
(None, None),
("退出 Peach", quit_now),
],
@@ -1670,15 +1718,18 @@ def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = Non
stopped = threading.Event()
threading.Thread(target=poll_health, name="PeachMenuHealth", daemon=True).start()
- # 启动时先对一次账,之后由网络变化事件驱动(失败按退避重试)。
- refresh_certificate_with_retry()
- watcher = NetworkChangeWatcher(on_network_change)
- watcher.start()
+ watcher = None
+ if not standalone():
+ # 源码部署维护本机 CA;独立应用使用设置中的高位端口。
+ refresh_certificate_with_retry()
+ watcher = NetworkChangeWatcher(on_network_change)
+ watcher.start()
try:
menu.run()
finally:
stopped.set()
- watcher.stop()
+ if watcher is not None:
+ watcher.stop()
def build_parser() -> argparse.ArgumentParser:
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 85c4c8979..273705a7a 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -153,6 +153,7 @@ class FollowContractTests(unittest.TestCase):
def test_background_taste_refresh_has_a_readable_result(self):
self.contract.taste_history_store = self.root / 'missing-history.sqlite'
with mock.patch.object(web_stats, 'enabled_history_sources', return_value=[]), \
+ mock.patch.object(web_stats, 'enabled_bookmark_sources', return_value=[]), \
mock.patch.object(web_stats, 'q_taste', return_value={'demo': True}):
started = self._post('/api/taste/refresh', {'background': True})
self.contract.taste_refresh_job.thread.join(5)
diff --git a/tests/test_macos_standalone.py b/tests/test_macos_standalone.py
new file mode 100644
index 000000000..7a105142b
--- /dev/null
+++ b/tests/test_macos_standalone.py
@@ -0,0 +1,154 @@
+"""独立 macOS 制品的分发边界。"""
+from __future__ import annotations
+
+import importlib.util
+import sys
+import tempfile
+from types import SimpleNamespace
+from pathlib import Path
+from unittest import TestCase, mock, skipUnless
+from dataclasses import dataclass
+
+
+@dataclass
+class FakeSubmenu:
+ items: object
+
+class MacStandaloneDistributionTests(TestCase):
+ def setUp(self):
+ path = Path(__file__).resolve().parents[1] / "scripts" / "build_macos_standalone.py"
+ spec = importlib.util.spec_from_file_location("macos_standalone_builder", path)
+ self.builder = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(self.builder)
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name).resolve()
+
+ def test_disk_image_preserves_bundle_links_and_provides_an_install_destination(self):
+ app = self.root / "Peach.app"
+ executable = app / "Contents" / "MacOS" / "Peach"
+ executable.parent.mkdir(parents=True)
+ executable.write_bytes(b"native executable")
+ resource = app / "Contents" / "Resources"
+ resource.mkdir()
+ (resource / "runtime").symlink_to("../MacOS/Peach")
+ destination = self.root / "release" / "Peach.dmg"
+
+ def create_image(command, *, check):
+ staging = Path(command[command.index("-srcfolder") + 1])
+ self.assertEqual((staging / "Applications").readlink(), Path("/Applications"))
+ copied = staging / "Peach.app" / "Contents" / "Resources" / "runtime"
+ self.assertEqual(copied.read_bytes(), b"native executable")
+ self.assertTrue(copied.is_symlink())
+ self.assertTrue((staging / "LICENSE.txt").is_file())
+ destination.write_bytes(b"disk image")
+
+ with mock.patch.object(self.builder.subprocess, "run", side_effect=create_image):
+ result = self.builder.package_dmg(app, destination)
+ self.assertEqual(result.read_bytes(), b"disk image")
+ self.assertTrue((resource / "runtime").is_symlink())
+
+ def test_incomplete_bundle_is_rejected_before_creating_an_image(self):
+ destination = self.root / "release" / "Peach.dmg"
+ with self.assertRaises(FileNotFoundError):
+ self.builder.package_dmg(self.root / "Peach.app", destination)
+ self.assertFalse(destination.parent.exists())
+
+ def test_non_macos_build_is_rejected_before_running_tools(self):
+ with mock.patch.object(self.builder.sys, "platform", "win32"), \
+ mock.patch.object(self.builder.subprocess, "run") as run:
+ with self.assertRaises(SystemExit):
+ self.builder.build(self.root)
+ run.assert_not_called()
+
+ def test_mismatched_python_architecture_is_rejected_before_building(self):
+ with mock.patch.object(self.builder.sys, "platform", "darwin"), \
+ mock.patch.object(self.builder.platform, "machine", return_value="arm64"), \
+ mock.patch.object(self.builder.subprocess, "run") as run:
+ with self.assertRaises(SystemExit):
+ self.builder.build(self.root, target_arch="x86_64")
+ run.assert_not_called()
+
+ def test_minimum_system_uses_dependency_requirements_and_ignores_the_sdk_version(self):
+ app = self.root / "Peach.app"
+ app.mkdir()
+ (app / "native").write_bytes(b"\xcf\xfa\xed\xfe")
+ commands = "cmd LC_BUILD_VERSION\n cmdsize 32\n platform 1\n minos 11.0\n sdk 26.5\n"
+ commands += "cmd LC_VERSION_MIN_MACOSX\n cmdsize 16\n version 14.0\n sdk 26.5\n"
+ with mock.patch.object(self.builder.subprocess, "run", return_value=mock.Mock(stdout=commands)):
+ self.assertEqual(self.builder.minimum_system_version(app), "14.0")
+
+ def test_menu_actions_and_certificate_lifecycle_follow_the_distribution(self):
+ from peach import tray
+
+ for independent in (True, False):
+ with self.subTest(standalone=independent):
+ gate = mock.Mock()
+ gate.config.directory.return_value = self.root
+ gate.waiting = False
+ menu = mock.Mock()
+ menu_type = mock.Mock(return_value=menu)
+ with mock.patch.dict(sys.modules, {"peach.menubar": SimpleNamespace(
+ MenuBarApp=menu_type, Submenu=FakeSubmenu)}), \
+ mock.patch.object(tray, "standalone", return_value=independent), \
+ mock.patch.object(tray, "VersionManager"), \
+ mock.patch.object(tray, "create_icon"), \
+ mock.patch.object(tray, "lan_ipv4", return_value="192.0.2.1"), \
+ mock.patch.object(tray, "ensure_certificate", return_value=None) as certificate, \
+ mock.patch.object(tray, "NetworkChangeWatcher") as watcher:
+ tray.run_macos_menu_bar(mock.Mock(specs=()), gate, silent=True)
+ labels = [title for title, _ in menu_type.call_args.args[2]]
+ self.assertEqual("同步开发进度" in labels, not independent)
+ if independent:
+ certificate.assert_not_called()
+ watcher.assert_not_called()
+ else:
+ certificate.assert_called_once()
+ watcher.return_value.start.assert_called_once()
+ watcher.return_value.stop.assert_called_once()
+ self.assertLess(labels.index("同步开发进度"), labels.index("重启服务"))
+ menu.run.assert_called_once()
+
+ @skipUnless(sys.platform == "darwin", "AppKit 是 macOS 专属")
+ def test_native_submenu_updates_rows_and_routes_nested_actions(self):
+ from peach import menubar
+
+ class Menu:
+ def __init__(self):
+ self.rows = []
+
+ def setAutoenablesItems_(self, value):
+ pass
+
+ def addItem_(self, item):
+ self.rows.append(item)
+
+ menu_type = mock.Mock()
+ menu_type.alloc.return_value.init.side_effect = Menu
+ item_type = mock.Mock()
+ item_type.alloc.return_value.initWithTitle_action_keyEquivalent_.side_effect = (
+ lambda title, *_: mock.Mock(title=title))
+ app = object.__new__(menubar.MenuBarApp)
+ app.item, app._target = mock.Mock(), mock.Mock()
+ action = mock.Mock()
+ rows = [("目录不可用", None), ("打开配置", action)]
+ app._items = [("状态", menubar.Submenu(lambda: rows)), ("退出", action)]
+ app._handlers, app._rendered = {}, None
+ with mock.patch.object(menubar.AppKit, "NSMenu", menu_type), \
+ mock.patch.object(menubar.AppKit, "NSMenuItem", item_type):
+ app.refresh_titles()
+ parent = app.menu.rows[0]
+ nested = parent.setSubmenu_.call_args.args[0]
+ self.assertEqual([row.title for row in nested.rows], ["目录不可用", "打开配置"])
+ nested.rows[0].setEnabled_.assert_called_once_with(False)
+ self.assertEqual(len(app._handlers), 2)
+ app._handlers[0]()
+ action.assert_called_once()
+ original = app.menu
+ app.refresh_titles()
+ self.assertIs(app.menu, original)
+ rows[:] = [("HTTP 正常", None)]
+ app.refresh_titles()
+ nested = app.menu.rows[0].setSubmenu_.call_args.args[0]
+ self.assertEqual([row.title for row in nested.rows], ["HTTP 正常"])
+ self.assertEqual(len(app._handlers), 1)
diff --git a/tests/test_tray.py b/tests/test_tray.py
index 64702f3e7..7edf6631d 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -213,6 +213,43 @@ class ServiceStatusTests(unittest.TestCase):
self.assertEqual(manager.status(), "HTTPS 正常(CloudDrive · 115:没有权限读取)")
popen.assert_not_called()
+ def test_short_summary_deduplicates_mount_warnings_and_recovers(self):
+ warnings = ["本地磁盘:目录不存在", "CloudDrive · 115:" + "很长的目录/" * 40]
+ response = Mock(status_code=200)
+ response.json.return_value = {"ok": True, "media_mounts": {"warnings": warnings}}
+ manager = self.manager({"http": (False, "未检测"), "https": (False, "未检测")})
+ manager._health_get = lambda *a, **k: response
+ for spec in manager.specs:
+ self.assertTrue(manager.healthy(spec))
+ self.assertEqual(manager.status_summary(), "运行中 · 2 项提醒")
+ self.assertEqual(manager.status_details()[:3], ("HTTP 正常", "HTTPS 正常", warnings[0]))
+ self.assertTrue(manager.status_details()[-1].endswith("…"))
+ self.assertTrue(all(len(line) <= 48 for line in manager.status_details()))
+ response.json.return_value = {"ok": True, "media_mounts": {"warnings": []}}
+ for spec in manager.specs:
+ manager.healthy(spec)
+ self.assertEqual(manager.status_summary(), "运行中")
+ self.assertEqual(manager.status_details(), ("HTTP 正常", "HTTPS 正常"))
+
+ def test_short_summary_preserves_service_failures(self):
+ manager = self.manager({"http": (True, ""), "https": (False, "状态码 503")})
+ self.assertEqual(manager.status_summary(), "部分服务异常")
+ self.assertEqual(manager.status_details(), ("HTTP 正常", "HTTPS 异常(状态码 503)"))
+ self.assertEqual(self.manager({"http": (False, "无响应")}).status_summary(), "服务未运行")
+
+ def test_windows_style_menu_keeps_details_out_of_the_root_and_refreshes(self):
+ manager = self.manager({"http": (True, "")})
+ with patch("peach.tray.pystray.Icon") as icon:
+ tray = PeachTray(manager)
+ root = icon.call_args.args[3]
+ status = next(item for item in root.items if item.text.startswith("状态:"))
+ self.assertEqual(status.text, "状态:运行中")
+ self.assertIn("HTTP 正常", [item.text for item in status.submenu.items])
+ manager._last_health["http"] = (False, "无响应")
+ self.assertEqual(status.text, "状态:服务未运行")
+ self.assertIn("HTTP 异常(无响应)", [item.text for item in status.submenu.items])
+ self.assertIs(tray.manager, manager)
+
def test_partial_names_the_broken_one_with_reason(self):
self.assertEqual(
self.manager({"http": (True, ""), "https": (False, "状态码 503")}).status(),
@@ -706,23 +743,6 @@ class SourceSyncTests(unittest.TestCase):
self.assertFalse(launchd_owns_this_process(
Mock(return_value=Mock(returncode=113, stdout="")), uid=501))
- def test_the_menu_lists_source_sync_next_to_the_ledger_actions(self):
- """标签和位置是语义契约:菜单只有一条,写错了没有第二处会报错。"""
- from peach import tray as tray_module
-
- source = inspect.getsource(tray_module.run_macos_menu_bar)
- labels = [
- line.split('"')[1]
- for line in source.splitlines()
- if line.strip().startswith('("') and '",' in line
- ]
- self.assertIn("同步开发进度", labels)
- # 两个 Ledger 项由 `ledger_menu_items` 统一给出(复制关掉时为空),
- # 位置契约因此变成「同步开发进度 紧挨着那次调用之前」。
- self.assertLess(source.index("同步开发进度"), source.index("ledger_menu_items"))
- self.assertLess(source.index("ledger_menu_items"), source.index("重启服务"))
- self.assertIn("sync_source", source)
-
def test_windows_tray_lists_source_sync_next_to_ledger(self):
source = inspect.getsource(PeachTray.__init__)
self.assertIn('MenuItem("同步开发进度", self.sync_source,', source)