Peach: Local-first video metadata scraper and media manager.
fix(tray): 记录退出来源并自动恢复异常停止的托盘
longmeidaod19d1edc8f11
diff --git a/README.en.md b/README.en.mdindex 03ec7ee61..5c9c1a450 100644--- a/README.en.md+++ b/README.en.md@@ -82,6 +82,8 @@ Want to look around before installing? The [live demo](https://demo.peach.video)The test package is not code-signed yet. If Windows says "Windows protected your PC", make sure the file came from this project's Releases, then choose "More info → Run anyway". Transcoding and thumbnails need FFmpeg; without it you can still browse and play MP4 and WebM. See [Windows test build](docs/TESTING_DESKTOP.md) for how to install it.+On Windows, Peach attempts to recover after an unexpected tray exit, up to three times within five minutes. Choosing “Quit Peach” keeps it closed. Exit reasons and recovery results are recorded in `tray-lifecycle.log` in the logs folder.+### Run from source (Windows, macOS)You need Git, [uv](https://docs.astral.sh/uv/getting-started/installation/) and Python 3.12 or newer (uv downloads a missing interpreter for you):diff --git a/README.md b/README.mdindex aafac6b56..157c69a65 100644--- a/README.md+++ b/README.md@@ -82,6 +82,8 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62测试包还没有代码签名。Windows 提示「已保护你的电脑」时,确认文件来自本项目的 Release,再点「更多信息 → 仍要运行」。转码和缩略图要用到 FFmpeg,没装也能浏览和播放 MP4、WebM,安装方法见 [Windows 测试版](docs/TESTING_DESKTOP.md)。+Windows 托盘异常退出后会自动尝试恢复;5 分钟内最多恢复 3 次。主动选择「退出 Peach」会保持关闭。退出原因和恢复结果可在日志目录的 `tray-lifecycle.log` 中查看。+### 从源码运行(Windows、macOS)需要 Git、[uv](https://docs.astral.sh/uv/getting-started/installation/) 和 Python 3.12 或更高(uv 会自动下载缺的解释器):diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 7d363003a..e8673cd62 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -333,6 +333,12 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt#### 刷新源码运行态:`restart_windows_tray.py`+Windows 托盘在取得单实例锁后启动独立监视器。监视器用 Win32 进程句柄等待托盘退出,核对进程创建时间,避免 PID 复用;意外退出(包括未登记退出意图的零退出码)按 2、5、10 秒延迟恢复,5 分钟内至多 3 次。恢复保持当前数据根和源码入口,以静默模式启动。新托盘的监视器就绪后完成交接;导入或启动失败计入同一重试预算。手动启动的新实例会取消旧实例尚未执行的恢复。达到上限后保持停止,需检查日志后手动启动。++菜单退出、更新、卸载、外部停止消息和系统会话结束都会登记退出意图并停止监视器。正常重启由重启脚本负责拉起,监视器不参与依赖同步与换包。`tray-lifecycle.log` 每行是一条 JSON,包含 UTC 时间、实例标识、托盘及监视器 PID、启动父进程、退出意图、外部消息发送者 PID、异常退出码和恢复结果。强制结束进程时,记录的操作者为 `unknown`,不能从退出码判断是谁关闭了它。++监视器与托盘共用当前用户权限,不注册计划任务或 Windows 服务。监视器自身被结束、整棵进程树被结束或系统关机时不能自动恢复。监视器启动失败写入 `tray.log`;日志不可写时保留退出和服务清理行为。macOS 沿用 LaunchAgent 的启动行为。+适用于代码已经在检出里、只需要让运行中的托盘重新加载、不换二进制的情况。- 不要用 Computer Use 点托盘。`python scripts/restart_windows_tray.py` 按精确的 EXE 路径找到 pystray 隐藏窗口,发送正常停止消息,等托盘自己关掉子服务,再静默启动新托盘,并确认新托盘接管了两个服务。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex b4525fe64..f35f7e92a 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -262,6 +262,7 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/| 局域网发现 | Python zeroconf | 服务生命周期和真实客户端验收 || 生成产物跨机同步 | Syncthing 2.1.x,Windows send-only → Mac receive-only | 目录划分、忽略规则、方向固定与「Mac 不发布正式产物」的边界 || Windows 托盘 | pystray 0.19.5(LGPLv3)、Pillow、Win32 Per-Monitor V2 DPI | Peach 服务归属、后台更新检查、菜单动作、品牌图标 |+| Windows 托盘恢复 | Windows 自带 `OpenProcess`、`GetProcessTimes`、[`WaitForSingleObject`](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)、`GetExitCodeProcess`;Python 3.12+ 标准库 `ctypes` / `subprocess`,无新增依赖或分发体积 | `tray_lifecycle` 保留明确退出意图、创建时间校验、3 次 / 5 分钟预算与重启交接。pystray 0.19.5 的 `_message_handlers` 接收 `WM_STOP` / `WM_ENDSESSION`,已核对安装包源码;Windows 临时进程实验证明强制退出能恢复,明确退出不会恢复。原生 API 随受支持的 Windows 维护;pystray 使用项目固定版本。不采用 Task Scheduler `RestartOnFailure`:它只管理任务启动的实例,桌面快捷方式与现有重启脚本不归其管理;不新增 psutil 运行时依赖,进程句柄已覆盖等待与退出码。已知边界是监视器随整棵进程树被终止时不能恢复。 || macOS 菜单栏 | `pyobjc-framework-Cocoa==12.2.2`(MIT)提供 AppKit / PyObjCTools / objc | 附件应用策略、18 pt template 图、服务归属与菜单动作 || 人脸取景 | `opencv-python-headless==5.0.0.93`(Apache-2.0)的 `cv2.FaceDetectorYN` + opencv_zoo 定版模型 `face_detection_yunet_2023mar.onnx`(sha256 `8f2383e4…52fa4`,232 KB,放 `peach-data/tools/yunet/`,不进 Git);MetaTube SDK `6a5e6128c725187aeaf921d48ed7d9cd9f30671b` 的主脸聚类只作算法参考 | 头像/封面离线脚本共用 `peach.face_detect`(主脸、归一化焦点与 sidecar)。`detect` 按长边 320/640/1280 各检一次、分数取中位数;`main_face` 先筛掉分数落后最好那张 0.1 以上的框,再取最大。不用 Haar 级联(OpenCV 5 wheel 里没有、检出率低)与 Pigo v1.4.6(有无脸误报)。[实测](SOURCING.md#人脸与水印实测) || 人脸比对 | 同一 OpenCV 的 `cv2.FaceRecognizerSF` + opencv_zoo 定版模型 `face_recognition_sface_2021dec.onnx`(sha256 `0ba9fbfa…34e79`,与 LFS 指针的 oid 一致,37 MB,放 `peach-data/tools/sface/`,不进 Git) | `peach.face_match` 提特征、算余弦,阈值用 SFace 官方的 0.363;补头像后继拿图库候选与单人封面截到的脸比(ADR-0056),小脸先放大再检(ADR-0070)。检脸用 `peach.face_detect`,取模型走同一条 `fetch_model`。不引 `face_recognition`/dlib(要编译、体积大)与 InsightFace(模型限非商用、需 onnxruntime)。[实测](SOURCING.md#人脸与水印实测) |diff --git a/docs/STATUS.md b/docs/STATUS.mdindex c95df526c..035e42ff5 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -2,14 +2,14 @@最后核验:2026-10-02-本页是核验日期的观察;实时版本与健康状态查运行实例的 `/healthz`。另见 [待办](PRODUCT_BACKLOG.md)、[复用清单](REUSE.md)、[长期约定](HANDOFF.md)。+实时版本与健康状态查运行实例的 `/healthz`。另见 [待办](PRODUCT_BACKLOG.md)、[复用清单](REUSE.md)、[长期约定](HANDOFF.md)。## 运行态- 女优头像 816 张(中位脸宽 258px,38 张带水印待复核);替下的在 `avatars-superseded/`。- 数据管理页「整理」(ADR-0039)可预览、执行、回滚上一批,真实库未跑过。- 产地是独立维度、JAV 是其投影:`region` 空时按厂牌、创作者、番号逐层推断,不落库;韩国 MIB 不算 JAV。-- Windows 是 ledger writer,入口是源码托盘(`pythonw -m peach.tray`),重启 `restart_windows_tray.py --source`;代码数据在内置盘,外置盘只供 `R:\media`。+- Windows:ledger writer;源码托盘异常退出会恢复,主动退出保持关闭。用 `restart_windows_tray.py --source` 重启;代码数据在内置盘,外置盘只供 `R:\media`。- 托盘须普通权限启动:提权令牌看不到 CloudDrive 的 `A:`/`B:`,误报脱盘。- Windows HTTP `0.0.0.0:80` 只跳转 HTTPS,HTTPS 只绑当前 LAN IPv4 的 443,mDNS 名 `peach-win`;线上版本 `0.37.0`、`ledger_sync=writer`,项目 CA 严格校验的 `/healthz` 通过。- 正式域名下 `/healthz` 报 `configurable=true`;配置读写与选文件夹共用本机连接判据,托盘管配置重载与正式 HTTPS 地址、端口。diff --git a/scripts/build_app_entry.py b/scripts/build_app_entry.pyindex 3b60000a0..67767c699 100644--- a/scripts/build_app_entry.py+++ b/scripts/build_app_entry.py@@ -22,9 +22,19 @@ if "--data-root" in sys.argv:os.environ["PEACH_DATA_ROOT"] = sys.argv[_root_index + 1]del sys.argv[_root_index:_root_index + 2]-from peach.cli import main as cli_main-from peach.cli import subcommands-from peach.tray import main as tray_main+def cli_main(argv):+ from peach.cli import main+ return main(argv)+++def subcommands():+ from peach.cli import subcommands as commands+ return commands()+++def tray_main():+ from peach.tray import main+ return main()_ATTACH_PARENT_PROCESS = -1_STD_OUTPUT_HANDLE = -11@@ -72,6 +82,9 @@ def wants_cli(argv: list[str]) -> bool:def main(argv: list[str] | None = None) -> int:argv = list(sys.argv if argv is None else argv)+ if len(argv) == 3 and argv[1] == "--tray-watchdog":+ from peach.tray_lifecycle import main as watchdog_main+ return watchdog_main(argv[2:])if len(argv) == 4 and argv[1] == "--apply-standalone-update":from peach.standalone_update import applyreturn apply(Path(argv[2]), int(argv[3]))diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex afe53aadd..b386cc02c 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -66,7 +66,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_previews.py","test_providers.py", "test_segments.py", "test_streaming.py","test_subtitles.py", "test_transcodes.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_log_retention.py","test_mdns.py", "test_netwatch.py", "test_certs.py","test_review_mirror.py", "test_runtime_prepare.py"),"metadata": ("test_scraping_access.py", "test_browser_transport.py", "test_metadata*.py", "test_genre_taxonomy.py",@@ -629,6 +629,17 @@ def environment_preflight(scopes: tuple[str, ...], timings: Path | None = None,raise SystemExit(3)+def run_local_suite(scopes: tuple[str, ...], jobs: int) -> tuple[bool, int, list]:+ """按并发预算执行本机测试;全量分片可逐批释放模块与测试缓存。"""+ chosen = {path for scope in scopes for path in selected_files(scope)}+ if (jobs > 1 or "full" in scopes) and len(chosen) > 1:+ shard_count = min(len(chosen), 4 * jobs, MAX_SHARDS)+ print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程", flush=True)+ return run_shards(scopes, jobs=jobs, shard_count=shard_count)+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))+ return result.wasSuccessful() and result.testsRun > 0, result.testsRun, result.timings++def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser()# `--scope` 可重复:本机并行的父进程把 `auto` 算出来的几个域原样交给每个分片子进程。@@ -725,19 +736,7 @@ def verified_run(args, requested, scopes, files) -> int:folder = test_evidence.evidence_dir(ROOT)(folder / f"{state}.json").unlink(missing_ok=True)started = time.monotonic()- chosen = {path for scope in scopes for path in selected_files(scope)}- if args.jobs > 1 and len(chosen) > 1:- # 每个并发槽分配四片,先完成的进程继续领片,避免少数大分片占满尾段。- shard_count = min(len(chosen), 4 * args.jobs, MAX_SHARDS)- print(f"本机并行:{shard_count} 片、同时 {min(args.jobs, shard_count)} 个子进程",- flush=True)- passed, count, timings = run_shards(scopes, jobs=args.jobs,- shard_count=shard_count)- else:- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(- build_suite(*scopes))- passed, count, timings = (result.wasSuccessful() and result.testsRun > 0,- result.testsRun, result.timings)+ passed, count, timings = run_local_suite(scopes, args.jobs)stable = state == test_evidence.key(ROOT)success = passed and stableslowest = sorted(timings, reverse=True)[:20]diff --git a/src/peach/desktop_uninstall.py b/src/peach/desktop_uninstall.pyindex 4b806abb0..1c3cb3409 100644--- a/src/peach/desktop_uninstall.py+++ b/src/peach/desktop_uninstall.py@@ -226,7 +226,7 @@ def poll(tray) -> None:process.stdin.write(json.dumps(job).encode("utf-8"))process.stdin.close()path.unlink()- tray.exit()+ tray.exit(reason="uninstall")except Exception as exc:path.unlink(missing_ok=True)tray.icon.notify(f"卸载未能启动:{exc}", "Peach")diff --git a/src/peach/standalone_update.py b/src/peach/standalone_update.pyindex 107c4ae60..45256001c 100644--- a/src/peach/standalone_update.py+++ b/src/peach/standalone_update.py@@ -170,7 +170,7 @@ def poll(tray) -> None:environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"subprocess.Popen([str(helper), "--apply-standalone-update", str(state_path()), str(os.getpid())],cwd=str(helper.parent), env=environment, creationflags=subprocess.CREATE_NO_WINDOW)- tray.exit()+ tray.exit(reason="standalone-update")except Exception as exc:write(read(), state="error", message=f"未能重启:{exc}")finally:diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 8a7bc92db..0cc27c2eb 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -32,6 +32,7 @@ from .mdns import lan_ipv4from .netwatch import NetworkChangeWatcherfrom .mount import mount_share as mount_smb_sharefrom .process_job import assign_to_job, create_kill_on_close_job+from .tray_lifecycle import Lifecyclefrom .sync import COPY_ACTIONS, SyncPlan, device_id, resolvefrom .versioning import VersionManager, VersionSnapshotfrom .windows_update import (@@ -973,6 +974,7 @@ class PeachTray:show_browser: bool = False,preparation: TrayPreparation | None = None,) -> None:+ self.lifecycle = Noneself.manager = managerself.silent = silentself.show_browser = show_browser@@ -1230,6 +1232,8 @@ class PeachTray:returnif prepared.state == "replace":tray_icon.notify(prepared.message, "Peach 开发进度")+ if self.lifecycle is not None:+ self.lifecycle.stop("source-update", os.getpid())self.manager.stop_owned()self._stop_event.set()tray_icon.stop()@@ -1250,7 +1254,9 @@ class PeachTray:threading.Thread(target=work, name="PeachSourceSync", daemon=True).start()- def exit(self, icon=None, _item=None) -> None:+ def exit(self, icon=None, _item=None, *, reason="menu-exit") -> None:+ if self.lifecycle is not None:+ self.lifecycle.stop(reason, os.getpid())self._stop_event.set()self.manager.stop_owned()(icon or self.icon).stop()@@ -1645,6 +1651,8 @@ def main(argv: list[str] | None = None) -> int:waiting = needs_setup(config)instance = SingleInstance(config.directory("state") / "peach-tray.lock")manager = None+ lifecycle = None+ exit_code = 1try:instance.acquire()except AlreadyRunning:@@ -1652,7 +1660,6 @@ def main(argv: list[str] | None = None) -> int:webbrowser.open(setup_url(config) if waiting else normal_url(config))return 0try:- specs = build_setup_service_specs(config) if waiting else configured_service_specs(config)# 日志按半年保留、按月切段,必须排在任何子进程打开日志之前:Windows 上被占着的# 文件改不了名也删不掉。整理不了只记日志,不能因此不起托盘。try:@@ -1661,18 +1668,37 @@ def main(argv: list[str] | None = None) -> int:except Exception:logging.getLogger(__name__).warning("日志整理失败", exc_info=True)log_to_file(config.directory("logs") / "tray.log")+ if sys.platform == "win32":+ lifecycle = Lifecycle(config.directory("state"), config.directory("logs"),+ config.data_root, PROJECT_ROOT)+ try:+ lifecycle.start()+ except Exception:+ LOGGER.exception("托盘异常退出自动恢复未能启用")+ lifecycle.stop("watchdog-start-failed", os.getpid())+ lifecycle = None+ specs = build_setup_service_specs(config) if waiting else configured_service_specs(config)manager = ServiceManager(specs, log_dir=config.directory("logs"))gate = SetupGate(manager, config, waiting=waiting)if sys.platform == "darwin":manager.start_missing()run_macos_menu_bar(manager, gate, silent=args.silent, show_browser=args.show)else:- PeachTray(manager, gate=gate, silent=args.silent, show_browser=args.show,- preparation=tray_preparation(config, manager)).run()+ tray = PeachTray(manager, gate=gate, silent=args.silent, show_browser=args.show,+ preparation=tray_preparation(config, manager))+ tray.lifecycle = lifecycle+ if lifecycle is not None:+ lifecycle.attach(tray.icon)+ tray.run()+ exit_code = 0except Exception as exc:- show_message("Peach 启动失败", str(exc), error=True)+ LOGGER.exception("托盘运行失败")+ if not os.environ.get("PEACH_TRAY_RECOVERIES"):+ show_message("Peach 启动失败", str(exc), error=True)return 1finally:+ if lifecycle is not None:+ lifecycle.exited(exit_code)if manager is not None:manager.stop_owned()instance.close()diff --git a/src/peach/tray_lifecycle.py b/src/peach/tray_lifecycle.pynew file mode 100644index 000000000..daed012c8--- /dev/null+++ b/src/peach/tray_lifecycle.py@@ -0,0 +1,278 @@+"""Windows 托盘退出取证与进程恢复;监视器只加载标准库。"""+from __future__ import annotations++import ctypes+import json+import logging+import os+import subprocess+import sys+import time+import uuid+from ctypes import wintypes+from datetime import datetime, timezone+from pathlib import Path++from .fsutil import atomic_write_text++WM_STOP = 0x0400 + 10+WM_ENDSESSION = 0x0016+HISTORY_ENV = "PEACH_TRAY_RECOVERIES"+ACK_ENV = "PEACH_TRAY_RECOVERY_ACK"+RECOVERY_WINDOW = 300+RECOVERY_DELAYS = (2, 5, 10)+++def remove_records(paths) -> None:+ for path in paths:+ try:+ path.unlink(missing_ok=True)+ except OSError:+ logging.getLogger(__name__).warning("托盘监视记录清理失败:%s", path, exc_info=True)+++def audit(log: Path, event: str, session: str, **fields) -> None:+ record = dict(at=datetime.now(timezone.utc).isoformat(), event=event,+ session=session, observer_pid=os.getpid(), **fields)+ try:+ log.parent.mkdir(parents=True, exist_ok=True)+ with log.open("a", encoding="utf-8") as stream:+ stream.write(json.dumps(record, ensure_ascii=False) + "\n")+ except OSError:+ logging.getLogger(__name__).exception("托盘退出记录写入失败")+++def recovery_history(value: str, now: float) -> list[float]:+ try:+ values = json.loads(value)+ if not isinstance(values, list):+ return []+ return [float(stamp) for stamp in values[-10:]+ if type(stamp) in (float, int) and 0 <= now - stamp < RECOVERY_WINDOW]+ except (TypeError, ValueError):+ return []+++class ProcessHandle:+ """持有内核进程对象,避免轮询 PID 时认到复用该号码的其他进程。"""++ def __init__(self, pid: int):+ self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)+ self.kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ self.kernel.OpenProcess.restype = wintypes.HANDLE+ self.kernel.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4+ self.kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]+ self.kernel.WaitForSingleObject.restype = wintypes.DWORD+ self.kernel.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]+ self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]+ self.handle = self.kernel.OpenProcess(0x100000 | 0x1000, False, pid)+ if not self.handle:+ raise ctypes.WinError(ctypes.get_last_error())+ times = [wintypes.FILETIME() for _ in range(4)]+ if not self.kernel.GetProcessTimes(self.handle, *(ctypes.byref(t) for t in times)):+ self.close()+ raise ctypes.WinError(ctypes.get_last_error())+ self.created = (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime++ def wait(self, milliseconds: int) -> int | None:+ status = self.kernel.WaitForSingleObject(self.handle, milliseconds)+ if status == 258:+ return None+ if status != 0:+ raise ctypes.WinError(ctypes.get_last_error())+ code = wintypes.DWORD()+ if not self.kernel.GetExitCodeProcess(self.handle, ctypes.byref(code)):+ raise ctypes.WinError(ctypes.get_last_error())+ return code.value++ def close(self) -> None:+ if self.handle:+ self.kernel.CloseHandle(self.handle)+ self.handle = None+++def watch(path: Path, *, open_process=ProcessHandle, popen=subprocess.Popen,+ sleep=time.sleep, now=time.time) -> int:+ """单个实例的监视器;有退出意图就交还控制权,异常退出最多恢复三次。"""+ record = json.loads(path.read_text(encoding="utf-8"))+ log, session = Path(record["log"]), record["session"]+ ready, stop = path.with_suffix(".ready"), path.with_suffix(".stop")+ process = None+ try:+ process = open_process(record["pid"])+ if process.created != record["created"]:+ raise RuntimeError("托盘进程身份不一致")+ audit(log, "watchdog_ready", session, tray_pid=record["pid"])+ atomic_write_text(ready, str(os.getpid()))+ while True:+ if stop.exists():+ audit(log, "watchdog_disarmed", session, tray_pid=record["pid"])+ return 0+ code = process.wait(250)+ if code is not None:+ break+ if stop.exists():+ return 0+ audit(log, "unexpected_exit", session, tray_pid=record["pid"], exit_code=code,+ actor="unknown")+ history = recovery_history(record.get("history", "[]"), now())+ ack = path.with_suffix(".recovered")+ while len(history) < len(RECOVERY_DELAYS):+ current = Path(record["current"])+ if current.read_text(encoding="utf-8") != session:+ audit(log, "recovery_superseded", session)+ return 0+ delay = RECOVERY_DELAYS[len(history)]+ audit(log, "recovery_scheduled", session, delay_seconds=delay, attempt=len(history) + 1)+ sleep(delay)+ if current.read_text(encoding="utf-8") != session:+ audit(log, "recovery_superseded", session)+ return 0+ history.append(now())+ environment = os.environ.copy()+ environment["PEACH_DATA_ROOT"] = record["data_root"]+ environment[HISTORY_ENV] = json.dumps(history)+ environment[ACK_ENV] = str(ack)+ environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"+ try:+ child = popen(record["argv"], cwd=record["cwd"], env=environment,+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ creationflags=getattr(subprocess, "DETACHED_PROCESS", 0)+ | getattr(subprocess, "CREATE_NO_WINDOW", 0))+ except OSError as exc:+ audit(log, "recovery_start_failed", session, error=str(exc))+ continue+ audit(log, "recovery_started", session, launcher_pid=child.pid)+ # 新托盘自己的监视器就绪才交接;导入失败也进入有限重试。+ for _ in range(240):+ if ack.exists():+ audit(log, "recovery_handoff", session, tray_pid=int(ack.read_text()))+ return 0+ code = child.poll()+ if code is not None:+ audit(log, "recovery_launcher_exit", session, exit_code=code)+ if code == 0:+ return 0 # 单实例锁可能已经由用户手动启动的托盘持有。+ break+ sleep(0.25)+ else:+ audit(log, "recovery_handoff_timeout", session, launcher_pid=child.pid)+ return 1+ audit(log, "recovery_limit", session, attempts=len(history), window_seconds=RECOVERY_WINDOW)+ return 1+ except Exception as exc:+ audit(log, "watchdog_error", session, error=str(exc))+ return 1+ finally:+ if process is not None:+ process.close()+ remove_records((ready, stop, path.with_suffix(".recovered"), path))+++class Lifecycle:+ """托盘内的退出意图与监视器握手。仅由取得单实例锁的托盘创建。"""++ def __init__(self, state: Path, log: Path, data_root: Path, root: Path):+ self.session = uuid.uuid4().hex+ self.path = state / "tray-watchdogs" / (self.session + ".json")+ self.log = log / "tray-lifecycle.log"+ self.data_root, self.root = data_root, root+ self.reason: str | None = None+ self.guard = None++ def start(self) -> None:+ process = ProcessHandle(os.getpid())+ try:+ frozen = getattr(sys, "frozen", False)+ if frozen:+ argv = [sys.executable, "--silent"]+ helper = [sys.executable, "--tray-watchdog", str(self.path)]+ self.root = Path(sys.executable).parent+ else:+ # 基础解释器只加载标准库,依赖同步期间不占项目 venv 的启动器或扩展。+ pythonw = str(Path(sys.executable).with_name("pythonw.exe"))+ base = str(Path(sys._base_executable).with_name("pythonw.exe"))+ argv = [pythonw, "-m", "peach.tray", "--silent"]+ helper = [base, "-m", "peach.tray_lifecycle", str(self.path)]+ record = dict(session=self.session, pid=os.getpid(), created=process.created,+ log=str(self.log), data_root=str(self.data_root), cwd=str(self.root),+ argv=argv, history=os.environ.get(HISTORY_ENV, "[]"))+ self.path.parent.mkdir(parents=True, exist_ok=True)+ current = self.path.parent / "current"+ record["current"] = str(current)+ atomic_write_text(current, self.session)+ atomic_write_text(self.path, json.dumps(record))+ audit(self.log, "started", self.session, tray_pid=os.getpid(), parent_pid=os.getppid(),+ executable=sys.executable, project=str(self.root))+ environment = os.environ.copy()+ environment["PYTHONPATH"] = str(self.root / "src")+ environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"+ self.guard = subprocess.Popen(helper, cwd=self.root, env=environment,+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW)+ deadline = time.monotonic() + 10+ while not self.path.with_suffix(".ready").exists():+ if self.guard.poll() is not None or time.monotonic() >= deadline:+ raise RuntimeError("托盘监视器未能就绪")+ time.sleep(0.05)+ ack = os.environ.pop(ACK_ENV, None)+ if ack:+ atomic_write_text(Path(ack), str(os.getpid()))+ finally:+ process.close()++ def stop(self, reason: str, actor_pid: int | None = None) -> None:+ if self.reason is not None:+ return+ self.reason = reason+ try:+ audit(self.log, "stop_requested", self.session, tray_pid=os.getpid(),+ reason=reason, actor_pid=actor_pid)+ atomic_write_text(self.path.with_suffix(".stop"), reason)+ except OSError:+ logging.getLogger(__name__).exception("托盘退出意图写入失败,正在停止本实例监视器")+ finally:+ if self.guard is not None:+ self._disarm()++ def _disarm(self) -> None:+ if self.guard is not None:+ try:+ self.guard.wait(timeout=5)+ except subprocess.TimeoutExpired:+ # 这是本实例创建的监视器;它不能越过明确退出意图继续恢复。+ self.guard.terminate()+ self.guard.wait(timeout=5)+ remove_records((self.path.with_suffix(".ready"), self.path.with_suffix(".stop"), self.path))++ def exited(self, code: int) -> None:+ audit(self.log, "exited", self.session, tray_pid=os.getpid(), exit_code=code,+ reason=self.reason or "unexpected")++ def attach(self, icon) -> None:+ handlers = icon._message_handlers+ original = handlers[WM_STOP]++ def stopped(sender, reason):+ self.stop("external-stop" if sender else "window-stop", int(sender) or None)+ return original(sender, reason)++ def end_session(ending, flags):+ if ending:+ self.stop("session-end")+ return 0++ handlers[WM_STOP] = stopped+ handlers[WM_ENDSESSION] = end_session+++def main(argv: list[str] | None = None) -> int:+ import argparse+ parser = argparse.ArgumentParser(description="监视一个 Windows Peach 托盘实例")+ parser.add_argument("record", type=Path)+ return watch(parser.parse_args(argv).record)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/windows_restart.py b/src/peach/windows_restart.pyindex cec431c84..a7365c6dc 100644--- a/src/peach/windows_restart.py+++ b/src/peach/windows_restart.py@@ -286,7 +286,7 @@ def post_stop(window_handle: int) -> bool:user32 = ctypes.WinDLL("user32", use_last_error=True)user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]user32.PostMessageW.restype = wintypes.BOOL- return bool(user32.PostMessageW(window_handle, WM_STOP, 0, 0))+ return bool(user32.PostMessageW(window_handle, WM_STOP, os.getpid(), 0))def _descends_from(process_id: int, ancestor: int, parents: dict[int, int]) -> bool:diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.pyindex 6fd07e10e..b6bf9cb59 100644--- a/tests/test_test_evidence.py+++ b/tests/test_test_evidence.py@@ -266,13 +266,12 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "ROOT", self.repo), \mock.patch.object(evidence, "describe_holder", side_effect=describe_wait), \mock.patch.object(runner, "environment_preflight"), \- mock.patch.object(runner, "build_suite", return_value=unittest.TestSuite([- unittest.FunctionTestCase(lambda: None)])) as build, \+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run, \ThreadPoolExecutor(max_workers=1) as pool:with evidence.held(lock, scope="integrate"):future = pool.submit(runner.main, ["--scope", "full", "--lock-timeout", "5"])self.assertTrue(waiting.wait(5), "验证应等待持锁的集成")- build.assert_not_called()+ run.assert_not_called()(self.repo / "README.md").write_text("集成完成\n", encoding="utf-8")self.assertEqual(future.result(timeout=15), 0)self.assertIn("等待 full-suite.lock", errors.getvalue())@@ -291,8 +290,7 @@ class VerificationTests(unittest.TestCase):with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \mock.patch.object(runner, "ROOT", self.repo), \mock.patch.object(evidence, "write", side_effect=publish_locked) as written, \- mock.patch.object(runner, "build_suite", return_value=unittest.TestSuite([- unittest.FunctionTestCase(lambda: None)])):+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])):self.assertEqual(runner.main(["--scope", "full"]), 0)written.assert_called_once()self.assertEqual(self.git("rev-parse", "HEAD"), before)@@ -303,10 +301,10 @@ class VerificationTests(unittest.TestCase):return {"ok": True}with redirect_stdout(io.StringIO()), mock.patch.object(runner, "ROOT", self.repo), \- mock.patch.object(runner, "build_suite") as build, \+ mock.patch.object(runner, "run_local_suite") as run, \mock.patch.object(coordinator, "_integrate_locked", side_effect=merge):self.assertTrue(coordinator.integrate(self.repo, "unused")["ok"])- build.assert_not_called()+ run.assert_not_called()def test_integration_waits_for_full_verification_before_mutation(self):lock = evidence.evidence_dir(self.repo) / "full-suite.lock"@@ -379,6 +377,19 @@ class VerificationTests(unittest.TestCase):self.assertEqual(runner.main(["--scope", "checks", "--jobs", "2", "--fresh"]), 1)self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))+ def test_serial_full_run_releases_memory_between_shards(self):+ with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \+ mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "build_suite", side_effect=AssertionError("父进程不加载全量用例")), \+ mock.patch.object(runner, "run_shards", return_value=(True, 7, [])) as shards:+ self.assertEqual(runner.main(["--scope", "full", "--jobs", "1"]), 0)+ shards.assert_called_once()+ self.assertEqual(shards.call_args.kwargs["jobs"], 1)+ self.assertEqual(shards.call_args.kwargs["shard_count"], 4)+ record = evidence.read(self.repo, evidence.key(self.repo))+ self.assertTrue(evidence.covers(record, ("full",)))+ self.assertEqual(record["count"], 7)+def test_full_baseline_requires_only_new_scopes_without_extending_its_age(self):original = self.certify(self.repo, ("full",))stamp = evidence.read(self.repo, original)["validated"]["full"]@@ -401,10 +412,9 @@ class VerificationTests(unittest.TestCase):with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \mock.patch.object(runner, "ROOT", self.repo), \mock.patch.object(runner, "resolve_auto_scope", return_value=(("full",), "fixture")), \- mock.patch.object(runner, "build_suite", return_value=unittest.TestSuite([- unittest.FunctionTestCase(lambda: None)])) as build:+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:self.assertEqual(runner.main(["--scope", "auto"]), 0)- build.assert_called_once_with("full")+ run.assert_called_once_with(("full",), 1)def test_baseline_does_not_expand_a_small_requested_scope(self):self.certify(self.repo, ("full",))diff --git a/tests/test_tray_lifecycle.py b/tests/test_tray_lifecycle.pynew file mode 100644index 000000000..8dcb5359d--- /dev/null+++ b/tests/test_tray_lifecycle.py@@ -0,0 +1,207 @@+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import time+import unittest+from pathlib import Path+from unittest.mock import Mock, patch++from peach import tray_lifecycle as lifecycle++ROOT = Path(__file__).resolve().parents[1]+++class TrayLifecycleTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name).resolve()+ self.path = self.root / "session.json"+ self.log = self.root / "lifecycle.log"+ self.current = self.root / "current"+ self.current.write_text("one", encoding="utf-8")+ self.record = dict(session="one", pid=123, created=456, log=str(self.log),+ data_root=str(self.root), cwd=str(self.root),+ argv=[sys.executable, "-c", "pass"], history="[]", current=str(self.current))+ self.save()+ self.process = Mock(created=456)+ self.process.wait.return_value = 99+ self.child = Mock(pid=789)+ self.child.poll.return_value = 0+ self.spawn = Mock(return_value=self.child)++ def save(self):+ self.path.write_text(json.dumps(self.record), encoding="utf-8")++ def events(self):+ return [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines()]++ def watch(self):+ return lifecycle.watch(self.path, open_process=lambda _: self.process,+ popen=self.spawn, sleep=lambda _: None, now=lambda: 1000)++ def test_abnormal_exit_preserves_data_root_and_records_unknown_actor(self):+ self.assertEqual(self.watch(), 0)+ fields = self.spawn.call_args.kwargs+ self.assertEqual(fields["env"]["PEACH_DATA_ROOT"], str(self.root))+ self.assertEqual(json.loads(fields["env"][lifecycle.HISTORY_ENV]), [1000])+ failure = next(row for row in self.events() if row["event"] == "unexpected_exit")+ self.assertEqual((failure["exit_code"], failure["actor"]), (99, "unknown"))+ self.process.close.assert_called_once()+ self.assertFalse(self.path.exists())++ def test_explicit_stop_disarms_without_recovery(self):+ self.path.with_suffix(".stop").write_text("menu-exit")+ self.assertEqual(self.watch(), 0)+ self.spawn.assert_not_called()+ self.assertEqual(self.events()[-1]["event"], "watchdog_disarmed")++ def test_zero_exit_without_intent_is_also_recovered(self):+ self.process.wait.return_value = 0+ self.watch()+ self.spawn.assert_called_once()++ def test_reused_pid_is_rejected(self):+ self.process.created = 457+ self.assertEqual(self.watch(), 1)+ self.spawn.assert_not_called()+ self.assertEqual(self.events()[-1]["event"], "watchdog_error")++ def test_manual_start_supersedes_pending_recovery(self):+ self.current.write_text("manual-session")+ self.assertEqual(self.watch(), 0)+ self.spawn.assert_not_called()+ self.assertEqual(self.events()[-1]["event"], "recovery_superseded")++ def test_manual_start_during_delay_supersedes_recovery(self):+ self.assertEqual(lifecycle.watch(+ self.path, open_process=lambda _: self.process, popen=self.spawn,+ sleep=lambda _: self.current.write_text("manual-session"), now=lambda: 1000), 0)+ self.spawn.assert_not_called()++ def test_record_cleanup_failure_does_not_interrupt_explicit_quit(self):+ item = lifecycle.Lifecycle(self.root, self.root, self.root, ROOT)+ item.guard = Mock()+ with patch.object(Path, "unlink", side_effect=PermissionError("busy")), \+ self.assertLogs("peach.tray_lifecycle", level="WARNING"):+ item.stop("menu-exit")+ self.assertEqual(item.reason, "menu-exit")+ item.guard.wait.assert_called_once_with(timeout=5)++ def test_repeated_launch_failure_stops_at_three_attempts(self):+ self.spawn.side_effect = OSError("entry missing")+ self.assertEqual(self.watch(), 1)+ self.assertEqual(self.spawn.call_count, 3)+ self.assertEqual(self.events()[-1]["event"], "recovery_limit")++ def test_import_failures_share_the_attempt_budget(self):+ self.child.poll.return_value = 1+ self.record["history"] = "[990,995]"+ self.save()+ self.assertEqual(self.watch(), 1)+ self.spawn.assert_called_once()++ def test_new_watchdog_acknowledges_handoff(self):+ def spawn(*args, **kwargs):+ Path(kwargs["env"][lifecycle.ACK_ENV]).write_text("222")+ return self.child+ self.spawn.side_effect = spawn+ self.assertEqual(self.watch(), 0)+ self.assertEqual(self.events()[-1]["event"], "recovery_handoff")++ def test_attempts_expire_and_malformed_history_is_ignored(self):+ self.assertEqual(lifecycle.recovery_history('[1,900,"bad",true,1100]', 1000), [900])+ self.assertEqual(lifecycle.recovery_history("{}", 1000), [])+ self.assertEqual(lifecycle.recovery_history("not json", 1000), [])++ def test_stop_message_records_sender_and_session_end_respects_cancellation(self):+ item = lifecycle.Lifecycle(self.root, self.root, self.root, ROOT)+ item.guard = Mock()+ original = Mock(return_value=42)+ icon = Mock(_message_handlers={lifecycle.WM_STOP: original})+ item.attach(icon)+ icon._message_handlers[lifecycle.WM_ENDSESSION](0, 0)+ self.assertIsNone(item.reason)+ self.assertEqual(icon._message_handlers[lifecycle.WM_STOP](987, 0), 42)+ rows = [json.loads(line) for line in (self.root / "tray-lifecycle.log").read_text(encoding="utf-8").splitlines()]+ self.assertEqual((rows[0]["actor_pid"], rows[0]["reason"]), (987, "external-stop"))+ item.guard.wait.assert_called_once_with(timeout=5)++ def test_menu_exit_disarms_before_stopping_services(self):+ from peach.tray import PeachTray+ tray = PeachTray.__new__(PeachTray)+ events = []+ tray.lifecycle = Mock()+ tray.lifecycle.stop.side_effect = lambda *args: events.append("intent")+ tray._stop_event = Mock()+ tray.manager = Mock()+ tray.manager.stop_owned.side_effect = lambda: events.append("services")+ tray.icon = Mock()+ tray.icon.stop.side_effect = lambda: events.append("icon")+ tray.exit()+ self.assertEqual(events, ["intent", "services", "icon"])+ tray.lifecycle.stop.assert_called_once_with("menu-exit", os.getpid())++[email protected](os.name == "nt", "Windows 内核进程句柄")+class WindowsWatchdogTests(TrayLifecycleTests):+ def test_native_lifecycle_arms_base_interpreter_and_disarms(self):+ item = lifecycle.Lifecycle(self.root, self.root, self.root, ROOT)+ try:+ item.start()+ self.assertIsNone(item.guard.poll())+ self.assertTrue(item.path.with_suffix(".ready").exists())+ finally:+ item.stop("menu-exit")+ self.assertEqual(item.guard.poll(), 0)+ rows = [json.loads(line) for line in (self.root / "tray-lifecycle.log").read_text(encoding="utf-8").splitlines()]+ self.assertIn("watchdog_ready", [row["event"] for row in rows])++ def native_case(self, intentional):+ target = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"],+ creationflags=subprocess.CREATE_NO_WINDOW)+ guard = None+ handle = lifecycle.ProcessHandle(target.pid)+ try:+ marker = self.root / "recovered.txt"+ self.record.update(pid=target.pid, created=handle.created,+ argv=[sys.executable, "-c",+ "from pathlib import Path; Path(" + repr(str(marker)) + ").write_text('ok')"])+ self.save()+ environment = {**os.environ, "PYTHONPATH": str(ROOT / "src")}+ guard = subprocess.Popen([sys.executable, "-m", "peach.tray_lifecycle", str(self.path)],+ env=environment, creationflags=subprocess.CREATE_NO_WINDOW)+ deadline = time.monotonic() + 10+ while not self.path.with_suffix(".ready").exists():+ self.assertIsNone(guard.poll())+ self.assertLess(time.monotonic(), deadline)+ time.sleep(0.05)+ if intentional:+ self.path.with_suffix(".stop").write_text("menu-exit")+ self.assertEqual(guard.wait(timeout=10), 0)+ target.terminate()+ target.wait(timeout=5)+ self.assertEqual(guard.wait(timeout=15), 0)+ self.assertEqual(marker.exists(), not intentional)+ if not intentional:+ self.assertTrue(any(row["event"] == "unexpected_exit" for row in self.events()))+ finally:+ handle.close()+ for process in (guard, target):+ if process is not None and process.poll() is None:+ process.terminate()+ process.wait(timeout=5)++ def test_native_process_death_recovers_a_temporary_command(self):+ self.native_case(False)++ def test_native_intent_keeps_the_process_stopped(self):+ self.native_case(True)+++if __name__ == "__main__":+ unittest.main()