Peach: Local-first video metadata scraper and media manager.
feat: add Windows tray autostart
Peach local maintenance3fd6e11651a0
diff --git a/README.md b/README.mdindex 35562c5e9..7d4e3f30f 100644--- a/README.md+++ b/README.md@@ -46,6 +46,26 @@ cd R:\peach-app`serve` 默认只监听 `127.0.0.1:8900`。公网、反代、HTTPS 和认证属于后续部署阶段,不在开发命令中隐式开启。+Windows 日常运行使用登录后托盘,而不是保留命令行窗口或注册系统服务。托盘单击打开+`https://peach.local/`,右键可查看状态、重启服务、打开日志、检查版本和退出;退出只结束+托盘自己启动的 Peach 进程:++```powershell+& .\scripts\manage_tray_startup.ps1 -Action Install+& .\.venv\Scripts\pythonw.exe -m peach.tray+```++检查或移除当前用户自启动:++```powershell+& .\scripts\manage_tray_startup.ps1 -Action Status+& .\scripts\manage_tray_startup.ps1 -Action Uninstall+```++托盘默认固定发布 `192.168.50.162`,避免虚拟网卡误选;地址变化时为启动进程设置+`PEACH_LAN_ADDRESS`。它同时启动 HTTP `:80` 和本地 CA HTTPS `:443`,因此安装前必须先按+下文生成 TLS 材料。+需要本机 TLS 时同时提供证书和私钥;二者应放在 `R:\peach-data\secrets`,不要提交 Git:```powershelldiff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 3dd832929..9ca8c6e6c 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -233,7 +233,14 @@ Verified 2026-08-15 against the mihomo connection counter, five files plus a 115## Operations-- Main command: `peach serve|migrate` after editable installation.+- Main command: `peach serve|migrate` after editable installation. Windows 日常入口是当前用户+ Startup 中的 `Peach.lnk`,它用项目 venv 的 `pythonw.exe -m peach.tray` 启动交互式托盘;+ 不要同时新增系统服务、计划任务或注册表 Run 项。托盘单击打开 HTTPS,右键提供状态、+ 重启、日志、检查更新和退出。它用进程期文件锁拒绝重复实例,并只终止自己创建的服务进程。+- `scripts/manage_tray_startup.ps1` 是唯一自启动安装/状态/卸载入口。托盘同时管理 HTTP+ `0.0.0.0:80`(负责 mDNS)和 HTTPS `192.168.50.162:443`;LAN 地址可用+ `PEACH_LAN_ADDRESS` 覆盖。服务输出追加到 `R:\peach-data\logs\tray-*.log`。仓库当前没有+ Git remote,因此“检查更新”只报告本地提交和无更新源,不伪造自动升级能力。- `peach serve` 默认用 Python zeroconf 发布唯一入口 `peach.local`;使用 `--no-mdns` 可关闭。必须保留迁移前已验证的 `Zeroconf()` 全合格网卡监听语义,不要改用只能发布服务/SRV 的 Windows `DnsServiceRegister`。隧道软件可能让自动路由选择落到 `198.18.0.0/15`;生产启动因此显式传 `--mdns-address 192.168.50.162`,只固定发布的 A 地址,不缩窄 Zeroconf 监听接口。注册在 FastAPI lifespan 中执行,不能在事件循环内同步阻塞。mDNS 修改的验收门槛是:单元测试、运行态 health、DNS-SD 查询、主机名解析,以及一台真实 LAN 客户端;监听端口枚举或注册回调不能单独证明可用。- TLS 仅在同时提供 `--ssl-certfile` 和 `--ssl-keyfile` 时启用;`.local` 使用本地 CA,不使用 Let's Encrypt,证书和私钥留在 `R:\peach-data\secrets`。本地 CA 必须带 critical `CA:TRUE` 和 `keyCertSign,cRLSign`;生成脚本签发后必须用 OpenSSL 验证链。macOS/iOS 只安装并信任 `peach-local-ca.crt`,不得分发 CA key 或服务器 key。- FastAPI is the only Web server. `web_contract.py` contains the stable JSON surface; do not recreate a parallel `http.server` or dynamic legacy loader.diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 9f62263ad..3aa0a29b9 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -31,6 +31,7 @@ These are product behavior and remain custom:| Local file events | watchdog plus periodic reconciliation | media identity and missed-event repair || Transitional metadata/media | Stash GraphQL, CommunityScrapers and Stash job system | adapter, reconciliation and exit gates || LAN discovery | Python zeroconf | service lifecycle and real-client acceptance |+| Windows tray | pystray 0.19.5 (LGPLv3) plus Pillow | Peach service ownership, menu actions and brand mark || Agent usage/quota | official provider quota APIs; T3 Code/CodexBar for local history | task routing, redaction and stale-snapshot labeling || Video source/end-card evidence | existing FFmpeg frame extraction plus a reviewed OCR/vision adapter | opening/ending sample policy, provenance and incomplete-version candidates || Referenced product behavior | current live interaction plus versioned public DOM/CSS/JS, or exact screenshot measurements when source is unavailable | evidence register, accessibility, Peach-specific deviations and regression checks |diff --git a/docs/adr/0011-windows-tray-autostart.md b/docs/adr/0011-windows-tray-autostart.mdnew file mode 100644index 000000000..f53141107--- /dev/null+++ b/docs/adr/0011-windows-tray-autostart.md@@ -0,0 +1,39 @@+# ADR-0011:Windows 托盘拥有登录后运行态++- 状态:Accepted+- 日期:2026-08-15++## 背景++Peach 是单用户本地自托管应用,但此前 HTTP/HTTPS 只能由终端手动启动。主机没有 Peach+系统服务、计划任务、Startup 快捷方式或注册表 Run 项,重启或退出会话后自然不可用;用户也+缺少直观的运行状态和退出入口。++Windows 服务运行在非交互会话,不能可靠承载通知区 UI。计划任务或另一个后台守护进程再+启动托盘会形成双重生命周期和重复服务所有权。++## 决策++- 使用当前用户 Startup 快捷方式,在登录后直接运行项目 venv 的+ `pythonw.exe -m peach.tray`。+- 复用 pystray 0.19.5 的 Windows 通知区实现;左键默认动作打开 Peach,右键显示原生菜单。+- 托盘作为唯一日常进程所有者,同时启动 HTTP/mDNS 和 HTTPS 服务,输出写入运行数据日志;+ 文件锁阻止重复托盘。+- 退出和重启只作用于托盘自己创建的子进程。已由其他入口启动的健康服务不会被托盘误杀。+- 更新检查只读本地版本和更新通道;没有 Git remote 时明确报告“未配置更新源”,不自动拉取、+ 合并或覆盖本地修改。+- 安装、检查和卸载 Startup 快捷方式统一走 `scripts/manage_tray_startup.ps1`。++## 已拒绝方案++- **Windows 服务承载托盘**:会话隔离,不适合交互 UI。+- **计划任务加独立托盘**:重复生命周期、退出语义不清。+- **注册表 Run 项**:可见性和可检查性不如 Startup 快捷方式。+- **自研 Win32 通知区协议**:pystray 已提供原生菜单和默认动作,重复实现没有产品价值。+- **点击“检查更新”自动覆盖工作树**:个人项目仍有并行 agent 与未提交改动,必须先审核集成。++## 后果++Peach 在用户登录后自动出现一个通知区入口,没有控制台窗口;退出语义明确且可回退。它不是+无人登录也运行的系统级服务器。如果未来需要开机未登录即服务,必须另立后台服务 ADR,并把+服务所有权和托盘控制协议拆开,不能并行启动第二套 Web 进程。diff --git a/pyproject.toml b/pyproject.tomlindex 69c6777fd..217d7b540 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -13,6 +13,7 @@ dependencies = ["feedparser==6.0.12","httpx==0.28.1","pillow==12.3.0",+ "pystray==0.19.5","pydantic==2.13.4","starlette==0.47.3","uvicorn==0.35.0",@@ -21,6 +22,7 @@ dependencies = [[project.scripts]peach = "peach.cli:main"+peach-tray = "peach.tray:main"[tool.setuptools]package-dir = {"" = "src"}diff --git a/scripts/manage_tray_startup.ps1 b/scripts/manage_tray_startup.ps1new file mode 100644index 000000000..0f812dff0--- /dev/null+++ b/scripts/manage_tray_startup.ps1@@ -0,0 +1,50 @@+param(+ [ValidateSet('Install', 'Uninstall', 'Status')]+ [string]$Action = 'Install'+)++$ErrorActionPreference = 'Stop'+$ProjectRoot = Split-Path -Parent $PSScriptRoot+$Pythonw = Join-Path $ProjectRoot '.venv\Scripts\pythonw.exe'+$Startup = [Environment]::GetFolderPath('Startup')+$ShortcutPath = Join-Path $Startup 'Peach.lnk'++if ($Action -eq 'Uninstall') {+ if (Test-Path -LiteralPath $ShortcutPath -PathType Leaf) {+ Remove-Item -LiteralPath $ShortcutPath -Force+ }+ [pscustomobject]@{ Installed = $false; Shortcut = $ShortcutPath }+ exit 0+}++if ($Action -eq 'Status') {+ if (-not (Test-Path -LiteralPath $ShortcutPath -PathType Leaf)) {+ [pscustomobject]@{ Installed = $false; Shortcut = $ShortcutPath }+ exit 0+ }+ $Shell = New-Object -ComObject WScript.Shell+ $Shortcut = $Shell.CreateShortcut($ShortcutPath)+ [pscustomobject]@{+ Installed = $true+ Shortcut = $ShortcutPath+ Target = $Shortcut.TargetPath+ Arguments = $Shortcut.Arguments+ WorkingDirectory = $Shortcut.WorkingDirectory+ }+ exit 0+}++if (-not (Test-Path -LiteralPath $Pythonw -PathType Leaf)) {+ throw "Project pythonw.exe not found: $Pythonw"+}++$Shell = New-Object -ComObject WScript.Shell+$Shortcut = $Shell.CreateShortcut($ShortcutPath)+$Shortcut.TargetPath = $Pythonw+$Shortcut.Arguments = '-m peach.tray'+$Shortcut.WorkingDirectory = $ProjectRoot+$Shortcut.Description = 'Start Peach and show its system tray menu'+$Shortcut.IconLocation = "$Pythonw,0"+$Shortcut.Save()++& $PSCommandPath -Action Statusdiff --git a/src/peach/tray.py b/src/peach/tray.pynew file mode 100644index 000000000..b39756497--- /dev/null+++ b/src/peach/tray.py@@ -0,0 +1,342 @@+from __future__ import annotations++import ctypes+import os+import subprocess+import sys+import threading+import time+import webbrowser+from dataclasses import dataclass+from pathlib import Path+from typing import Callable++import httpx+import pystray+from PIL import Image, ImageDraw++from .config import LOG_DIR, PROJECT_ROOT, SECRETS_DIR, STATE_DIR+++DEFAULT_LAN_ADDRESS = "192.168.50.162"+OPEN_URL = "https://peach.local/"+++@dataclass(frozen=True)+class ServiceSpec:+ name: str+ health_url: str+ command: tuple[str, ...]+ verify: bool | str+++class AlreadyRunning(RuntimeError):+ pass+++class SingleInstance:+ """A process-lifetime Windows file lock for the interactive tray."""++ def __init__(self, path: Path) -> None:+ self.path = path+ self._handle = None++ def acquire(self) -> None:+ if os.name != "nt":+ return+ import msvcrt++ self.path.parent.mkdir(parents=True, exist_ok=True)+ self._handle = self.path.open("r+b") if self.path.exists() else self.path.open("w+b")+ if self.path.stat().st_size == 0:+ self._handle.write(b"0")+ self._handle.flush()+ self._handle.seek(0)+ try:+ msvcrt.locking(self._handle.fileno(), msvcrt.LK_NBLCK, 1)+ except OSError as exc:+ self._handle.close()+ self._handle = None+ raise AlreadyRunning("Peach tray is already running") from exc++ def close(self) -> None:+ if self._handle is None:+ return+ if os.name == "nt":+ import msvcrt++ self._handle.seek(0)+ try:+ msvcrt.locking(self._handle.fileno(), msvcrt.LK_UNLCK, 1)+ except OSError:+ pass+ self._handle.close()+ self._handle = None+++class ServiceManager:+ def __init__(+ self,+ specs: tuple[ServiceSpec, ...],+ *,+ popen: Callable[..., subprocess.Popen] = subprocess.Popen,+ health_get: Callable[..., httpx.Response] = httpx.get,+ ) -> None:+ self.specs = specs+ self._popen = popen+ self._health_get = health_get+ self._owned: dict[str, subprocess.Popen] = {}+ self._logs: list[object] = []+ self._last_health = {spec.name: False for spec in specs}+ self._lock = threading.RLock()++ def healthy(self, spec: ServiceSpec) -> bool:+ try:+ response = self._health_get(spec.health_url, timeout=0.5, verify=spec.verify)+ result = response.status_code == 200 and response.json().get("ok") is True+ except (httpx.HTTPError, OSError, ValueError):+ result = False+ with self._lock:+ self._last_health[spec.name] = result+ return result++ def status(self) -> str:+ with self._lock:+ results = [self._last_health[spec.name] for spec in self.specs]+ if all(results):+ return "运行中"+ if any(results):+ return "部分运行"+ return "未运行"++ def start_missing(self) -> None:+ LOG_DIR.mkdir(parents=True, exist_ok=True)+ with self._lock:+ for spec in self.specs:+ owned = self._owned.get(spec.name)+ if owned is not None and owned.poll() is None:+ continue+ if self.healthy(spec):+ continue+ stdout = (LOG_DIR / f"tray-{spec.name}.out.log").open("ab")+ stderr = (LOG_DIR / f"tray-{spec.name}.err.log").open("ab")+ self._logs.extend((stdout, stderr))+ creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0+ self._owned[spec.name] = self._popen(+ list(spec.command),+ cwd=str(PROJECT_ROOT),+ stdin=subprocess.DEVNULL,+ stdout=stdout,+ stderr=stderr,+ shell=False,+ creationflags=creationflags,+ )++ def wait_until_ready(self, timeout: float = 20.0) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if all(self.healthy(spec) for spec in self.specs):+ return True+ time.sleep(0.25)+ return False++ def stop_owned(self) -> None:+ with self._lock:+ processes = list(self._owned.values())+ self._owned.clear()+ for spec in self.specs:+ self._last_health[spec.name] = False+ for process in processes:+ if process.poll() is None:+ process.terminate()+ for process in processes:+ if process.poll() is not None:+ continue+ try:+ process.wait(timeout=8)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=3)+ for handle in self._logs:+ handle.close()+ self._logs.clear()++ def restart(self) -> bool:+ self.stop_owned()+ self.start_missing()+ return self.wait_until_ready()+++def _peach_executable() -> Path:+ sibling = Path(sys.executable).with_name("peach.exe")+ if sibling.is_file():+ return sibling+ candidate = PROJECT_ROOT / ".venv" / "Scripts" / "peach.exe"+ if candidate.is_file():+ return candidate+ raise FileNotFoundError("peach.exe is missing; reinstall the editable project")+++def build_service_specs(lan_address: str | None = None) -> tuple[ServiceSpec, ...]:+ address = lan_address or os.environ.get("PEACH_LAN_ADDRESS", DEFAULT_LAN_ADDRESS)+ peach = str(_peach_executable())+ cert_dir = SECRETS_DIR / "tls"+ ca = cert_dir / "peach-local-ca.crt"+ cert = cert_dir / "peach.crt"+ key = cert_dir / "peach.key"+ missing = [path for path in (ca, cert, key) if not path.is_file()]+ if missing:+ raise FileNotFoundError("TLS material is missing: " + ", ".join(map(str, missing)))+ return (+ ServiceSpec(+ "http",+ "http://127.0.0.1/healthz",+ (peach, "serve", "--host", "0.0.0.0", "--port", "80", "--mdns-address", address),+ True,+ ),+ ServiceSpec(+ "https",+ f"https://{address}/healthz",+ (+ peach, "serve", "--host", address, "--port", "443", "--no-mdns",+ "--ssl-certfile", str(cert), "--ssl-keyfile", str(key),+ ),+ str(ca),+ ),+ )+++def create_icon(size: int = 64) -> Image.Image:+ """Render a tray-sized counterpart of the web favicon with antialiasing."""+ canvas = size * 4+ scale = canvas / 64+ image = Image.new("RGBA", (canvas, canvas), (11, 11, 13, 255))+ draw = ImageDraw.Draw(image)+ draw.rounded_rectangle((0, 0, canvas - 1, canvas - 1), radius=14 * scale, fill=(11, 11, 13, 255))+ draw.ellipse((12 * scale, 23 * scale, 52 * scale, 57 * scale), fill=(246, 104, 118, 255))+ draw.ellipse((18 * scale, 18 * scale, 34 * scale, 52 * scale), fill=(255, 154, 118, 255))+ draw.ellipse((33 * scale, 12 * scale, 52 * scale, 25 * scale), fill=(95, 185, 95, 255))+ draw.line((32 * scale, 15 * scale, 29 * scale, 27 * scale), fill=(138, 90, 59, 255), width=max(1, round(2 * scale)))+ return image.resize((size, size), Image.Resampling.LANCZOS)+++def show_message(title: str, message: str, *, error: bool = False) -> None:+ if os.name == "nt":+ flags = 0x10 if error else 0x40+ ctypes.windll.user32.MessageBoxW(None, message, title, flags)+ else:+ print(f"{title}: {message}")+++def update_status() -> str:+ try:+ revision = subprocess.run(+ ["git", "-C", str(PROJECT_ROOT), "rev-parse", "--short", "HEAD"],+ capture_output=True, text=True, timeout=5, check=True,+ ).stdout.strip()+ remote = subprocess.run(+ ["git", "-C", str(PROJECT_ROOT), "remote", "get-url", "origin"],+ capture_output=True, text=True, timeout=5, check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return "无法读取本地版本信息。"+ if remote.returncode != 0:+ return f"当前提交 {revision}。这是本地开发版,尚未配置更新源。"+ return f"当前提交 {revision}。已配置更新源;自动更新尚未启用,请由项目协调者审核更新。"+++class PeachTray:+ def __init__(self, manager: ServiceManager) -> None:+ self.manager = manager+ self._stop_event = threading.Event()+ self._restart_lock = threading.Lock()+ self.icon = pystray.Icon(+ "Peach",+ create_icon(),+ "Peach · 蜜桃",+ pystray.Menu(+ pystray.MenuItem("打开 Peach", self.open, default=True),+ pystray.MenuItem(lambda _item: f"状态:{self.manager.status()}", None, enabled=False),+ pystray.Menu.SEPARATOR,+ pystray.MenuItem("重启服务", self.restart),+ pystray.MenuItem("查看日志", self.open_logs),+ pystray.MenuItem("检查更新", self.check_updates),+ pystray.Menu.SEPARATOR,+ pystray.MenuItem("退出 Peach", self.exit),+ ),+ )++ def open(self, _icon=None, _item=None) -> None:+ webbrowser.open(OPEN_URL)++ def restart(self, icon=None, _item=None) -> None:+ if not self._restart_lock.acquire(blocking=False):+ return++ def work() -> None:+ try:+ ready = self.manager.restart()+ if self._stop_event.is_set():+ self.manager.stop_owned()+ return+ (icon or self.icon).update_menu()+ if not ready:+ show_message("Peach", "服务未能在 20 秒内恢复,请查看日志。", error=True)+ finally:+ self._restart_lock.release()++ threading.Thread(target=work, name="PeachRestart", daemon=True).start()++ def open_logs(self, _icon=None, _item=None) -> None:+ LOG_DIR.mkdir(parents=True, exist_ok=True)+ if os.name == "nt":+ os.startfile(LOG_DIR)++ def check_updates(self, _icon=None, _item=None) -> None:+ show_message("Peach 更新", update_status())++ def exit(self, icon=None, _item=None) -> None:+ self._stop_event.set()+ self.manager.stop_owned()+ (icon or self.icon).stop()++ def _monitor(self) -> None:+ while not self._stop_event.wait(10):+ for spec in self.manager.specs:+ self.manager.healthy(spec)+ self.icon.update_menu()++ def run(self) -> None:+ self.manager.start_missing()+ if not self.manager.wait_until_ready():+ show_message("Peach", "Peach 只启动了部分服务,请查看托盘状态和日志。", error=True)+ threading.Thread(target=self._monitor, name="PeachHealth", daemon=True).start()+ try:+ self.icon.run()+ finally:+ self._stop_event.set()+++def main() -> int:+ instance = SingleInstance(STATE_DIR / "peach-tray.lock")+ manager = None+ try:+ instance.acquire()+ except AlreadyRunning:+ webbrowser.open(OPEN_URL)+ return 0+ try:+ manager = ServiceManager(build_service_specs())+ PeachTray(manager).run()+ except Exception as exc:+ show_message("Peach 启动失败", str(exc), error=True)+ return 1+ finally:+ if manager is not None:+ manager.stop_owned()+ instance.close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_tray.py b/tests/test_tray.pynew file mode 100644index 000000000..001615b19--- /dev/null+++ b/tests/test_tray.py@@ -0,0 +1,72 @@+import subprocess+import tempfile+import unittest+from pathlib import Path+from unittest.mock import Mock, patch++from peach.tray import AlreadyRunning, ServiceManager, ServiceSpec, SingleInstance, create_icon, update_status+++class Response:+ status_code = 200++ @staticmethod+ def json():+ return {"ok": True}+++class TrayTests(unittest.TestCase):+ def test_create_icon_has_expected_size_and_alpha(self):+ icon = create_icon(64)+ self.assertEqual(icon.size, (64, 64))+ self.assertEqual(icon.mode, "RGBA")++ def test_start_missing_does_not_duplicate_healthy_service(self):+ spec = ServiceSpec("http", "http://local/healthz", ("peach", "serve"), True)+ popen = Mock()+ manager = ServiceManager((spec,), popen=popen, health_get=lambda *args, **kwargs: Response())+ manager.start_missing()+ popen.assert_not_called()++ @patch("peach.tray.LOG_DIR")+ def test_start_and_stop_only_owned_service(self, log_dir):+ with tempfile.TemporaryDirectory() as directory:+ log_dir.__fspath__ = lambda: directory+ log_dir.mkdir.side_effect = lambda **_kwargs: None+ log_dir.__truediv__.side_effect = lambda name: Path(directory) / name+ spec = ServiceSpec("http", "http://local/healthz", ("peach", "serve"), True)+ process = Mock()+ process.poll.return_value = None+ popen = Mock(return_value=process)+ manager = ServiceManager(+ (spec,), popen=popen,+ health_get=Mock(side_effect=OSError("down")),+ )+ manager.start_missing()+ popen.assert_called_once()+ manager.stop_owned()+ process.terminate.assert_called_once()++ @patch("peach.tray.subprocess.run")+ def test_update_status_reports_missing_channel(self, run):+ run.side_effect = (+ subprocess.CompletedProcess([], 0, "abc123\n", ""),+ subprocess.CompletedProcess([], 2, "", "missing"),+ )+ self.assertIn("尚未配置更新源", update_status())++ def test_single_instance_rejects_second_windows_lock(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "tray.lock"+ first = SingleInstance(path)+ second = SingleInstance(path)+ first.acquire()+ try:+ with self.assertRaises(AlreadyRunning):+ second.acquire()+ finally:+ first.close()+++if __name__ == "__main__":+ unittest.main()