Peach: Local-first video metadata scraper and media manager.
feat(ops): 换生产托盘二进制走一条带回滚的入口
longmeidao1282346b8217
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 2576cc8ed..e0a234804 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -177,7 +177,8 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt验收四项:菜单栏只出现一个 Peach 图标且 `status` 报「已加载」;`launchctl print` 的 pid 就是那个菜单栏进程;`pfctl -s nat` 列出 80 → 8900、443 → 8443 两条 rdr;两条 `/healthz` 都回 200。`peach.local` 换成本机 `[server].mdns_name` 的值。- 发布入口是 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 生成方形 Logo 与多尺寸 `.ico`,再构建单一 `dist/Peach/Peach.exe`;无参数运行托盘,`serve`/`migrate` 运行 CLI。桌面快捷方式由 `scripts/create_desktop_shortcut.ps1` 创建,自启动只由 `scripts/manage_tray_startup.ps1` 管理。- 对外测试包由 `.github/workflows/release.yml` 承担:`build_windows.ps1 -Standalone` 用 PyInstaller onedir 生成完整 Windows 程序目录,压缩后由不检出源码的消费任务运行 `scripts/smoke_desktop.py`。`v<__version__>` tag 与版本不一致会失败,通过制品验收才创建 GitHub 预发布并附 SHA256;`workflow_dispatch` 只生成和验收 artifact。macOS 独立包另列待办,源码菜单栏构建入口仍为 `build_macos_app.py`。-- 刷新源码运行态不要用 Computer Use 点托盘:`python scripts/restart_windows_tray.py` 按精确 EXE 路径找到 pystray 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务;找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。+- 刷新源码运行态不要用 Computer Use 点托盘:`python scripts/restart_windows_tray.py` 按精确 EXE 路径找到 pystray 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务;找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。`--swap-from <暂存包>` 让它在旧托盘退出后、新托盘启动前顺手换掉二进制,那是整条链路上唯一一个目标文件没有进程持有的窗口;换生产二进制用下面那条入口,不要单独调它。+- 换掉生产托盘二进制走 `python scripts/deploy_windows_tray.py`,在主检出里用项目 venv 的 Python 跑:拒绝脏检出 → 按 HEAD 提交号在 `<数据根>/state/source-sync-build/<commit>/` 构建 → 让暂存包自己跑一次 `migrate status` → 停旧托盘、原地换 `dist/Peach/Peach.exe`(旧的留成 `Peach.pre-source-sync-<时间>.exe`)、起新托盘 → 用项目 CA 严格校验读生产 HTTPS 口的 `/healthz` 并核对版本号。结果打印成一份 JSON,`step` 说明停在哪一步。新托盘起不来或拿不到两个子服务时自动换回备份并重开旧托盘;`--staged <路径>` 复用已经打好的包、跳过构建。不要就地构建 `dist/Peach/`:运行中的托盘持有那个文件,PyInstaller 清目录会撞上 WinError 5。换生产入口本身仍要当场授权,脚本不代替那次授权。- `dist/Peach/Peach.exe` 是本机打包入口而不是可移动的独立发行版:托盘只打包了自己,服务进程仍由项目 venv 的 `peach.exe` 承担,`_peach_executable()` 从 exe 位置逐级向上找 `.venv\Scripts\peach.exe`,所以不要按「单文件绿色版」对外描述。- `<数据根>/logs` 里的 `*.log` 统一保留半年、大小不设限(`peach.log_retention.sweep`,托盘在起任何子进程之前跑):半年没再写过的文件整份删掉;还在写的文件按自然月切段,上次写入落在更早月份就改名成 `<名字>.until-<最后写入日期>.log`,段再等半年被删。子进程是直接追加 stdout,不经 `logging`,所以按文件而不是按行处理。- 更新与打包的产物自带清退:托盘每次启动只保留最近 2 份 `dist/Peach/Peach.pre-source-sync-*.exe` 备份,并删掉 `<数据根>/state/source-sync-build/` 里不属于待应用记录的暂存构建(`WindowsUpdateInstaller.sweep_artifacts`);`build_windows.ps1` 成功后删掉 PyInstaller 工作目录 `build/windows/app`;单文件托盘每次启动还会删掉 `%TEMP%` 里超过一天、不属于自己的 `_MEI*` 解压残留(`sweep_onefile_extractions`,托盘被结束进程时 PyInstaller 不会自清,每份 40–80 MB)。自动边界只认这几个命名:`Peach.exe` 本体、手工放进 `dist/` 的目录、`build/release-*`、`attic/` 都不碰,手工构建的残留自己删。diff --git a/scripts/deploy_windows_tray.py b/scripts/deploy_windows_tray.pynew file mode 100644index 000000000..dd2823e4d--- /dev/null+++ b/scripts/deploy_windows_tray.py@@ -0,0 +1,158 @@+"""换掉 Windows 生产托盘二进制的入口:构建、验证、原地替换、失败自动回滚。++托盘运行时持有自己的 `dist/Peach/Peach.exe`,所以整条链路只有一个能换文件的窗口——+旧托盘正常退出之后、新托盘启动之前。这个脚本按顺序走完它:干净检出 → 暂存目录里+构建 → 用暂存包自己跑一次打包迁移检查 → 停旧托盘、换二进制、起新托盘(新托盘起不来+就换回备份并重开旧的)→ 走项目 CA 严格校验读生产 HTTPS 口的 `/healthz`。++在主检出里运行,用 `.venv` 的 Python:++ .venv\\Scripts\\python.exe scripts\\deploy_windows_tray.py++换生产入口属于要当场授权的动作,脚本本身不代替那次授权。+"""+from __future__ import annotations++import argparse+import json+import subprocess+import sys+import time+from pathlib import Path+from typing import Callable++PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / "src"+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))++import httpx++from peach import __version__+from peach.config import LOG_DIR, STATE_DIR+from peach.tray import build_service_specs+from peach.windows_restart import restart_tray+from peach.windows_update import WindowsUpdateInstaller+++def serving_version(*, timeout: float = 60.0, sleep: Callable[[float], None] = time.sleep) -> str | None:+ """轮询生产 HTTPS 口的 `/healthz`,返回它报的版本号;期限内没回话返回 None。++ 地址和 CA 都取自 `build_service_specs()`,跟托盘自己探活用的是同一份规格。+ HTTPS 的结论必须由项目 CA 严格校验得出,明文口的 200 不算数:那条只是跳转进程。+ """+ spec = next(spec for spec in build_service_specs() if spec.name == "https")+ deadline = time.monotonic() + timeout+ while True:+ try:+ response = httpx.get(spec.health_url, timeout=5.0, verify=spec.verify,+ trust_env=False)+ if response.status_code == 200:+ return str(response.json().get("version"))+ except (httpx.HTTPError, OSError, ValueError):+ pass+ if time.monotonic() >= deadline:+ return None+ sleep(1.0)+++def _outcome(ok: bool, step: str, message: str, **fields) -> dict:+ return {"ok": ok, "step": step, "message": message, **fields}+++def _git(run: Callable[..., subprocess.CompletedProcess], root: Path,+ *args: str) -> subprocess.CompletedProcess:+ return run(["git", *args], cwd=str(root), capture_output=True, text=True, check=False)+++def deploy(+ root: Path,+ *,+ target: Path,+ staged: Path | None = None,+ timeout: float = 60.0,+ installer: WindowsUpdateInstaller | None = None,+ restart: Callable[..., object] = restart_tray,+ run: Callable[..., subprocess.CompletedProcess] = subprocess.run,+ version: Callable[..., str | None] = serving_version,+) -> dict:+ """把 `root` 这份检出打成新托盘并换上 `target`,返回可直接打印的结果字典。++ 每一步失败都在原地停住并说明停在哪:只有替换那一步动了生产入口,它自己带回滚,+ 其余步骤失败时旧托盘一直在跑。`staged` 给定时跳过构建,复用已经打好的那份包。+ """+ root = root.resolve()+ target = target.resolve()++ status = _git(run, root, "status", "--porcelain")+ if status.returncode != 0:+ return _outcome(False, "checkout", f"读不到检出状态:{status.stderr.strip()}")+ if status.stdout.strip():+ return _outcome(False, "checkout",+ "检出不干净:生产二进制只从干净的检出里打,先提交或清理再来。")+ commit = _git(run, root, "rev-parse", "HEAD").stdout.strip()+ branch = _git(run, root, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()+ if not commit:+ return _outcome(False, "checkout", "读不到 HEAD 提交号。")+ fields = {"commit": commit, "branch": branch, "target": str(target)}++ installer = installer or WindowsUpdateInstaller(+ root, state_dir=STATE_DIR, log_dir=LOG_DIR, current_executable=target,+ )+ if staged is None:+ built = installer.build_staged_tray(commit)+ if built is None:+ return _outcome(False, "build",+ f"新托盘构建失败,生产入口未动;日志见 {installer.log_path}。",+ **fields)+ staged = built+ staged = staged.resolve()+ if not staged.is_file():+ return _outcome(False, "build", f"暂存包不存在:{staged}", **fields)+ fields["staged"] = str(staged)++ if not installer.packaged_migrations_pass(staged):+ return _outcome(False, "validate",+ f"暂存包没通过打包迁移资源检查,生产入口未动;日志见 {installer.log_path}。",+ **fields)++ result = restart(target, swap_from=staged)+ fields.update({+ "old_tray_pid": result.old_tray_pid, "new_tray_pid": result.new_tray_pid,+ "service_pids": list(result.service_pids), "backup": result.backup,+ })+ if not result.ok:+ return _outcome(False, "swap", result.message, **fields)++ served = version(timeout=timeout)+ fields["expected_version"] = __version__+ fields["version"] = served+ if served is None:+ return _outcome(False, "verify",+ "新托盘已就位,但生产 HTTPS 口的 /healthz 没在期限内回话。",+ **fields)+ if served != __version__:+ return _outcome(False, "verify",+ f"新托盘已就位,但 /healthz 报的是 {served},不是这份检出的 {__version__}。",+ **fields)+ return _outcome(True, "verify",+ f"生产入口已换成 {commit[:8]} 打出的托盘,/healthz 报 {served}。", **fields)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="构建并换上 Windows 生产托盘二进制")+ parser.add_argument("--target", type=Path,+ default=PROJECT_ROOT / "dist" / "Peach" / "Peach.exe")+ parser.add_argument("--staged", type=Path, default=None,+ help="复用这份已经打好的暂存包,跳过构建")+ parser.add_argument("--timeout", type=float, default=60.0,+ help="等生产 HTTPS 口 /healthz 回话的秒数")+ args = parser.parse_args(argv)+ outcome = deploy(PROJECT_ROOT, target=args.target, staged=args.staged,+ timeout=max(1.0, args.timeout))+ print(json.dumps(outcome, ensure_ascii=False, indent=2))+ return 0 if outcome["ok"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/replace_windows_tray.py b/scripts/replace_windows_tray.pyindex 7f038bf03..763952861 100644--- a/scripts/replace_windows_tray.py+++ b/scripts/replace_windows_tray.py@@ -4,11 +4,19 @@ import argparseimport osimport shutilimport subprocess+import sysimport timefrom datetime import datetimefrom pathlib import Pathfrom typing import Callable+PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / "src"+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))++from peach.windows_update import replace_with_retry+def process_alive(process_id: int) -> bool:try:@@ -18,24 +26,6 @@ def process_alive(process_id: int) -> bool:return True-def replace_with_retry(- source: Path,- destination: Path,- *,- timeout: float = 45.0,- sleep: Callable[[float], None] = time.sleep,-) -> None:- deadline = time.monotonic() + timeout- while True:- try:- os.replace(source, destination)- return- except OSError:- if time.monotonic() >= deadline:- raise- sleep(0.25)--def append_log(path: Path, message: str) -> None:path.parent.mkdir(parents=True, exist_ok=True)with path.open("a", encoding="utf-8") as handle:diff --git a/scripts/restart_windows_tray.py b/scripts/restart_windows_tray.pyindex 1476c4876..1ea95cd84 100644--- a/scripts/restart_windows_tray.py+++ b/scripts/restart_windows_tray.py@@ -1,231 +1,35 @@+"""重启 Windows 托盘的命令行入口,实现在 `peach.windows_restart`。++ .venv\\Scripts\\python.exe scripts\\restart_windows_tray.py++换生产二进制走 `scripts/deploy_windows_tray.py`,不要单独用这里的 `--swap-from`。+"""from __future__ import annotationsimport argparse-import ctypesimport json-import os-import subprocess-import time-from ctypes import wintypes-from dataclasses import asdict, dataclass+import sys+from dataclasses import asdictfrom pathlib import Path-from typing import Callable---WM_STOP = 0x0400 + 10 # pystray._util.win32.WM_STOP---@dataclass(frozen=True)-class TrayWindow:- process_id: int- handle: int---@dataclass(frozen=True)-class RestartResult:- ok: bool- message: str- old_tray_pid: int | None = None- new_tray_pid: int | None = None- service_pids: tuple[int, ...] = ()---def _normal_path(path: str | Path) -> str:- return os.path.normcase(os.path.abspath(os.fspath(path)))---def process_alive(process_id: int) -> bool:- try:- os.kill(process_id, 0)- except OSError:- return False- return True---def _process_paths_and_parents() -> tuple[dict[int, str], dict[int, int]]:- if os.name != "nt":- raise OSError("Windows tray control is only available on Windows")- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)- kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]- kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]- kernel32.CloseHandle.restype = wintypes.BOOL- snapshot = kernel32.CreateToolhelp32Snapshot(0x00000002, 0)- if snapshot == wintypes.HANDLE(-1).value:- raise ctypes.WinError(ctypes.get_last_error())-- class ProcessEntry(ctypes.Structure):- _fields_ = [- ("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),- ("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_size_t),- ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),- ("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", wintypes.LONG),- ("dwFlags", wintypes.DWORD), ("szExeFile", wintypes.WCHAR * 260),- ]-- kernel32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]- kernel32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]- kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]- kernel32.OpenProcess.restype = wintypes.HANDLE- kernel32.QueryFullProcessImageNameW.argtypes = [- wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD),- ]- paths: dict[int, str] = {}- parents: dict[int, int] = {}- entry = ProcessEntry()- entry.dwSize = ctypes.sizeof(entry)- try:- more = bool(kernel32.Process32FirstW(snapshot, ctypes.byref(entry)))- while more:- process_id = int(entry.th32ProcessID)- parents[process_id] = int(entry.th32ParentProcessID)- handle = kernel32.OpenProcess(0x1000, False, process_id)- if handle:- try:- buffer = ctypes.create_unicode_buffer(32768)- length = wintypes.DWORD(len(buffer))- if kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(length)):- paths[process_id] = buffer.value- finally:- kernel32.CloseHandle(handle)- more = bool(kernel32.Process32NextW(snapshot, ctypes.byref(entry)))- finally:- kernel32.CloseHandle(snapshot)- return paths, parents---def find_tray_windows(target: Path) -> tuple[TrayWindow, ...]:- if os.name != "nt":- return ()- user32 = ctypes.WinDLL("user32", use_last_error=True)- paths, _parents = _process_paths_and_parents()- target_key = _normal_path(target)- found: list[TrayWindow] = []- callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)- user32.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]- user32.EnumWindows.restype = wintypes.BOOL- user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]- user32.GetClassNameW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]-- @callback_type- def visit(window, _extra):- process_id = wintypes.DWORD()- user32.GetWindowThreadProcessId(window, ctypes.byref(process_id))- buffer = ctypes.create_unicode_buffer(512)- user32.GetClassNameW(window, buffer, len(buffer))- class_name = buffer.value- if (class_name.startswith("Peach") and class_name.endswith("SystemTrayIcon")- and _normal_path(paths.get(int(process_id.value), "")) == target_key):- found.append(TrayWindow(int(process_id.value), int(window)))- return True-- ctypes.set_last_error(0)- if not user32.EnumWindows(visit, 0):- error = ctypes.get_last_error()- if error:- raise ctypes.WinError(error)- return tuple(found)---def post_stop(window_handle: int) -> bool:- if os.name != "nt":- return False- 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))---def owned_service_pids(tray_process_id: int, service_executable: Path) -> tuple[int, ...]:- paths, parents = _process_paths_and_parents()- service_key = _normal_path(service_executable)-- def descends_from(process_id: int) -> bool:- seen: set[int] = set()- parent = parents.get(process_id, 0)- while parent and parent not in seen:- if parent == tray_process_id:- return True- seen.add(parent)- parent = parents.get(parent, 0)- return False-- return tuple(sorted(- process_id for process_id, path in paths.items()- if _normal_path(path) == service_key and descends_from(process_id)- ))---def start_tray(target: Path) -> subprocess.Popen:- environment = os.environ.copy()- environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"- creationflags = subprocess.CREATE_NO_WINDOW | subprocess.DETACHED_PROCESS- return subprocess.Popen(- [str(target)], cwd=str(target.parent), stdin=subprocess.DEVNULL,- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=False,- env=environment, creationflags=creationflags,- )---def restart_tray(- target: Path,- *,- timeout: float = 25.0,- find_windows: Callable[[Path], tuple[TrayWindow, ...]] = find_tray_windows,- stop_window: Callable[[int], bool] = post_stop,- alive: Callable[[int], bool] = process_alive,- start: Callable[[Path], subprocess.Popen] = start_tray,- services: Callable[[int, Path], tuple[int, ...]] = owned_service_pids,- sleep: Callable[[float], None] = time.sleep,-) -> RestartResult:- target = target.resolve()- service_executable = target.parents[2] / ".venv" / "Scripts" / "peach.exe"- if not target.is_file() or target.name.lower() != "peach.exe":- return RestartResult(False, f"拒绝重启:入口不存在或不是 Peach.exe:{target}")- if not service_executable.is_file():- return RestartResult(False, f"拒绝重启:服务入口不存在:{service_executable}")-- windows = find_windows(target)- process_ids = {window.process_id for window in windows}- if len(process_ids) != 1 or not windows:- return RestartResult(False, "拒绝重启:没有找到唯一且路径匹配的 Peach 托盘窗口")- old_process_id = next(iter(process_ids))- if not all(stop_window(window.handle) for window in windows):- return RestartResult(False, "托盘停止消息发送失败", old_tray_pid=old_process_id)- deadline = time.monotonic() + timeout- while alive(old_process_id) and time.monotonic() < deadline:- sleep(0.1)- if alive(old_process_id):- return RestartResult(False, "托盘未在期限内正常退出;未强杀、未另启", old_tray_pid=old_process_id)+PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / "src"+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))- launched = start(target)- while time.monotonic() < deadline:- if launched.poll() is not None:- return RestartResult(False, f"新托盘退出,代码 {launched.returncode}", old_tray_pid=old_process_id)- new_windows = find_windows(target)- new_process_ids = {window.process_id for window in new_windows}- if len(new_process_ids) == 1:- new_process_id = next(iter(new_process_ids))- service_pids = services(new_process_id, service_executable)- if len(service_pids) >= 2:- return RestartResult(- True, "托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",- old_tray_pid=old_process_id, new_tray_pid=new_process_id,- service_pids=service_pids,- )- sleep(0.2)- return RestartResult(False, "新托盘或两个子服务未在期限内就绪", old_tray_pid=old_process_id)+from peach.windows_restart import restart_traydef main(argv: list[str] | None = None) -> int:- project_root = Path(__file__).resolve().parents[1]parser = argparse.ArgumentParser(description="静默、正常地重启 Windows Peach 托盘及其子服务")parser.add_argument("--target", type=Path,- default=project_root / "dist" / "Peach" / "Peach.exe")+ default=PROJECT_ROOT / "dist" / "Peach" / "Peach.exe")parser.add_argument("--timeout", type=float, default=25.0)+ parser.add_argument("--swap-from", type=Path, default=None,+ help="旧托盘退出后把这个暂存包换上生产入口,失败自动回滚")args = parser.parse_args(argv)- result = restart_tray(args.target, timeout=max(1.0, args.timeout))+ result = restart_tray(args.target, timeout=max(1.0, args.timeout),+ swap_from=args.swap_from)print(json.dumps(asdict(result), ensure_ascii=False))return 0 if result.ok else 1diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 78abc03ac..2fe19f48c 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -64,7 +64,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"tooling": ("test_scripts.py", "test_auth.py", "test_cli.py", "test_script_policy.py","test_scan.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py","test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py",- "test_restart_windows_tray.py",+ "test_restart_windows_tray.py", "test_deploy_windows_tray.py","test_buildinfo.py", "test_versioning.py","test_windows_update.py", "test_certs.py", "test_config.py","test_fsutil.py",diff --git a/src/peach/windows_restart.py b/src/peach/windows_restart.pynew file mode 100644index 000000000..12ef7da05--- /dev/null+++ b/src/peach/windows_restart.py@@ -0,0 +1,291 @@+"""正常重启 Windows 托盘:发停止消息、等它自己退出、再启动并核对子服务。++绝不强杀。托盘退出时要自己关掉两个 `peach serve` 子进程,被强杀的话那两个进程会+变成没人管的孤儿,继续占着 80 和 443,下一份托盘于是永远起不来服务。+`swap_from` 让它在旧托盘退出后、新托盘启动前顺手换掉二进制,那是整条链路上唯一一个+目标文件没有进程持有的窗口。+"""+from __future__ import annotations++import ctypes+import os+import shutil+import subprocess+import time+from ctypes import wintypes+from dataclasses import dataclass+from pathlib import Path+from typing import Callable++from .windows_update import replace_with_retry, swap_tray_binary+++WM_STOP = 0x0400 + 10 # pystray._util.win32.WM_STOP+++@dataclass(frozen=True)+class TrayWindow:+ process_id: int+ handle: int+++@dataclass(frozen=True)+class RestartResult:+ ok: bool+ message: str+ old_tray_pid: int | None = None+ new_tray_pid: int | None = None+ service_pids: tuple[int, ...] = ()+ swapped_from: str | None = None+ backup: str | None = None+++def _normal_path(path: str | Path) -> str:+ return os.path.normcase(os.path.abspath(os.fspath(path)))+++def process_alive(process_id: int) -> bool:+ try:+ os.kill(process_id, 0)+ except OSError:+ return False+ return True+++def _process_paths_and_parents() -> tuple[dict[int, str], dict[int, int]]:+ if os.name != "nt":+ raise OSError("Windows tray control is only available on Windows")+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]+ kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ snapshot = kernel32.CreateToolhelp32Snapshot(0x00000002, 0)+ if snapshot == wintypes.HANDLE(-1).value:+ raise ctypes.WinError(ctypes.get_last_error())++ class ProcessEntry(ctypes.Structure):+ _fields_ = [+ ("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),+ ("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_size_t),+ ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),+ ("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", wintypes.LONG),+ ("dwFlags", wintypes.DWORD), ("szExeFile", wintypes.WCHAR * 260),+ ]++ kernel32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]+ kernel32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.QueryFullProcessImageNameW.argtypes = [+ wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD),+ ]+ paths: dict[int, str] = {}+ parents: dict[int, int] = {}+ entry = ProcessEntry()+ entry.dwSize = ctypes.sizeof(entry)+ try:+ more = bool(kernel32.Process32FirstW(snapshot, ctypes.byref(entry)))+ while more:+ process_id = int(entry.th32ProcessID)+ parents[process_id] = int(entry.th32ParentProcessID)+ handle = kernel32.OpenProcess(0x1000, False, process_id)+ if handle:+ try:+ buffer = ctypes.create_unicode_buffer(32768)+ length = wintypes.DWORD(len(buffer))+ if kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(length)):+ paths[process_id] = buffer.value+ finally:+ kernel32.CloseHandle(handle)+ more = bool(kernel32.Process32NextW(snapshot, ctypes.byref(entry)))+ finally:+ kernel32.CloseHandle(snapshot)+ return paths, parents+++def find_tray_windows(target: Path) -> tuple[TrayWindow, ...]:+ if os.name != "nt":+ return ()+ user32 = ctypes.WinDLL("user32", use_last_error=True)+ paths, _parents = _process_paths_and_parents()+ target_key = _normal_path(target)+ found: list[TrayWindow] = []+ callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)+ user32.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]+ user32.EnumWindows.restype = wintypes.BOOL+ user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]+ user32.GetClassNameW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]++ @callback_type+ def visit(window, _extra):+ process_id = wintypes.DWORD()+ user32.GetWindowThreadProcessId(window, ctypes.byref(process_id))+ buffer = ctypes.create_unicode_buffer(512)+ user32.GetClassNameW(window, buffer, len(buffer))+ class_name = buffer.value+ if (class_name.startswith("Peach") and class_name.endswith("SystemTrayIcon")+ and _normal_path(paths.get(int(process_id.value), "")) == target_key):+ found.append(TrayWindow(int(process_id.value), int(window)))+ return True++ ctypes.set_last_error(0)+ if not user32.EnumWindows(visit, 0):+ error = ctypes.get_last_error()+ if error:+ raise ctypes.WinError(error)+ return tuple(found)+++def post_stop(window_handle: int) -> bool:+ if os.name != "nt":+ return False+ 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))+++def owned_service_pids(tray_process_id: int, service_executable: Path) -> tuple[int, ...]:+ paths, parents = _process_paths_and_parents()+ service_key = _normal_path(service_executable)++ def descends_from(process_id: int) -> bool:+ seen: set[int] = set()+ parent = parents.get(process_id, 0)+ while parent and parent not in seen:+ if parent == tray_process_id:+ return True+ seen.add(parent)+ parent = parents.get(parent, 0)+ return False++ return tuple(sorted(+ process_id for process_id, path in paths.items()+ if _normal_path(path) == service_key and descends_from(process_id)+ ))+++def start_tray(target: Path) -> subprocess.Popen:+ environment = os.environ.copy()+ environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"+ creationflags = subprocess.CREATE_NO_WINDOW | subprocess.DETACHED_PROCESS+ return subprocess.Popen(+ [str(target)], cwd=str(target.parent), stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=False,+ env=environment, creationflags=creationflags,+ )+++def _rolled_back(+ backup: Path,+ target: Path,+ *,+ start: Callable[[Path], subprocess.Popen],+ sleep: Callable[[float], None],+ message: str,+ old_tray_pid: int | None,+ swapped_from: str | None,+) -> RestartResult:+ """新二进制起不来就把备份换回去再开一次,别把机器留在没有托盘的状态。++ 备份先复制成临时名再 `os.replace`:直接把备份本身换回去的话,回滚成功了+ `dist/Peach/` 里那份可回退的副本也没了,下一次失败就无处可退。+ """+ restore = target.with_name(".Peach.rollback.exe")+ try:+ shutil.copy2(backup, restore)+ replace_with_retry(restore, target, sleep=sleep)+ except OSError as exc:+ return RestartResult(False, f"{message};回滚失败,生产入口停在新二进制:{exc}",+ old_tray_pid=old_tray_pid, swapped_from=swapped_from,+ backup=str(backup))+ started = start(target)+ if started.poll() is not None:+ return RestartResult(False, f"{message};已回滚到备份,但旧托盘也没起来",+ old_tray_pid=old_tray_pid, swapped_from=swapped_from,+ backup=str(backup))+ return RestartResult(False, f"{message};已回滚到备份并重开旧托盘",+ old_tray_pid=old_tray_pid, swapped_from=swapped_from,+ backup=str(backup))+++def restart_tray(+ target: Path,+ *,+ timeout: float = 25.0,+ swap_from: Path | None = None,+ find_windows: Callable[[Path], tuple[TrayWindow, ...]] = find_tray_windows,+ stop_window: Callable[[int], bool] = post_stop,+ alive: Callable[[int], bool] = process_alive,+ start: Callable[[Path], subprocess.Popen] = start_tray,+ services: Callable[[int, Path], tuple[int, ...]] = owned_service_pids,+ swap: Callable[[Path, Path], Path] = swap_tray_binary,+ sleep: Callable[[float], None] = time.sleep,+) -> RestartResult:+ target = target.resolve()+ service_executable = target.parents[2] / ".venv" / "Scripts" / "peach.exe"+ if not target.is_file() or target.name.lower() != "peach.exe":+ return RestartResult(False, f"拒绝重启:入口不存在或不是 Peach.exe:{target}")+ if not service_executable.is_file():+ return RestartResult(False, f"拒绝重启:服务入口不存在:{service_executable}")++ windows = find_windows(target)+ process_ids = {window.process_id for window in windows}+ if len(process_ids) != 1 or not windows:+ return RestartResult(False, "拒绝重启:没有找到唯一且路径匹配的 Peach 托盘窗口")+ old_process_id = next(iter(process_ids))+ if not all(stop_window(window.handle) for window in windows):+ return RestartResult(False, "托盘停止消息发送失败", old_tray_pid=old_process_id)++ deadline = time.monotonic() + timeout+ while alive(old_process_id) and time.monotonic() < deadline:+ sleep(0.1)+ if alive(old_process_id):+ return RestartResult(False, "托盘未在期限内正常退出;未强杀、未另启", old_tray_pid=old_process_id)++ backup: Path | None = None+ if swap_from is not None:+ try:+ backup = swap(swap_from.resolve(), target)+ except (OSError, ValueError) as exc:+ started = start(target)+ message = f"换二进制失败,已按原样重开旧托盘:{exc}"+ if started.poll() is not None:+ message = f"换二进制失败,且旧托盘未能重开:{exc}"+ return RestartResult(False, message, old_tray_pid=old_process_id,+ swapped_from=str(swap_from))++ swapped_from = str(swap_from) if swap_from is not None else None+ backup_path = str(backup) if backup is not None else None+ # 停和起各拿一份完整预算:换一份 40 MB 的 EXE 要几秒,那几秒不该从新托盘的+ # 启动窗口里扣掉,否则带 --swap-from 的这条路比不带的更容易假超时。+ deadline = time.monotonic() + timeout+ launched = start(target)+ while time.monotonic() < deadline:+ if launched.poll() is not None:+ if backup is not None:+ return _rolled_back(+ backup, target, start=start, sleep=sleep,+ message=f"新托盘退出,代码 {launched.returncode}",+ old_tray_pid=old_process_id, swapped_from=swapped_from)+ return RestartResult(False, f"新托盘退出,代码 {launched.returncode}", old_tray_pid=old_process_id)+ new_windows = find_windows(target)+ new_process_ids = {window.process_id for window in new_windows}+ if len(new_process_ids) == 1:+ new_process_id = next(iter(new_process_ids))+ service_pids = services(new_process_id, service_executable)+ if len(service_pids) >= 2:+ return RestartResult(+ True, "托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",+ old_tray_pid=old_process_id, new_tray_pid=new_process_id,+ service_pids=service_pids, swapped_from=swapped_from,+ backup=backup_path,+ )+ sleep(0.2)+ if backup is not None:+ return _rolled_back(+ backup, target, start=start, sleep=sleep,+ message="新托盘或两个子服务未在期限内就绪",+ old_tray_pid=old_process_id, swapped_from=swapped_from)+ return RestartResult(False, "新托盘或两个子服务未在期限内就绪", old_tray_pid=old_process_id)diff --git a/src/peach/windows_update.py b/src/peach/windows_update.pyindex 9ee41eafd..3cf84ef0c 100644--- a/src/peach/windows_update.py+++ b/src/peach/windows_update.py@@ -6,6 +6,7 @@ import osimport shutilimport subprocessimport sys+import timefrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom pathlib import Path@@ -91,6 +92,61 @@ def sweep_onefile_extractions(return tuple(removed)+def replace_with_retry(+ source: Path,+ destination: Path,+ *,+ timeout: float = 45.0,+ sleep: Callable[[float], None] = time.sleep,+) -> None:+ """把 `source` 原子换到 `destination`,直到目标不再被占用。++ Windows 上刚退出的进程仍会短暂持有自己的映像文件,`os.replace` 因此抛+ `PermissionError`。重试到期限为止;期限内换不上就把原始异常抛给调用方,+ 由它决定是回滚还是原样报出来,这里不吞。+ """+ deadline = time.monotonic() + timeout+ while True:+ try:+ os.replace(source, destination)+ return+ except OSError:+ if time.monotonic() >= deadline:+ raise+ sleep(0.25)+++def swap_tray_binary(+ staged: Path,+ target: Path,+ *,+ timeout: float = 45.0,+ now: Callable[[], datetime] = datetime.now,+ sleep: Callable[[float], None] = time.sleep,+) -> Path:+ """换掉生产托盘 EXE,先在原地留一份可回滚的备份,返回备份路径。++ 调用方必须先让旧托盘正常退出:这个函数不发停止消息,也不判断谁还活着。+ 备份名沿用 `BACKUP_GLOB`,托盘下次启动的 `sweep_artifacts` 才认得出它、+ 才会按 `KEEP_BACKUPS` 收口;换个名字就会在 `dist/Peach/` 里越堆越多。+ """+ if not staged.is_file():+ raise FileNotFoundError(f"暂存包不存在:{staged}")+ if target.name.lower() != "peach.exe" or not target.is_file():+ raise ValueError(f"生产入口不存在或不是 Peach.exe:{target}")+ if os.path.normcase(os.path.abspath(staged)) == os.path.normcase(os.path.abspath(target)):+ raise ValueError("暂存包与生产入口是同一个文件")++ backup = target.with_name(f"Peach.pre-source-sync-{now().strftime('%Y%m%d-%H%M%S')}.exe")+ shutil.copy2(target, backup)+ try:+ replace_with_retry(staged, target, timeout=timeout, sleep=sleep)+ except OSError:+ backup.unlink(missing_ok=True)+ raise+ return backup++class WindowsUpdateInstaller:"""Test an updated checkout and stage a recoverable Windows tray replacement."""@@ -204,6 +260,47 @@ class WindowsUpdateInstaller:)return result.returncode+ def build_staged_tray(self, commit: str, *, shell: str | None = None) -> Path | None:+ """把当前检出打成一份托盘 EXE,暂存到 `state/source-sync-build/<commit>/`。++ 不能就地构建 `dist/Peach/`:那份 `Peach.exe` 正被运行中的托盘持有,PyInstaller+ 清理输出目录时会撞上 `WinError 5`。暂存目录的命名是 `sweep_artifacts` 认得的+ 那一种,换名字它就清不掉。构建失败返回 None,原因在 `log_path` 里。+ """+ shell = shell or self._powershell_executable()+ if shell is None:+ return None+ staging_dir = self.state_dir / STAGING_DIRNAME / commit+ staging_dir.mkdir(parents=True, exist_ok=True)+ staged = staging_dir / "Peach.exe"+ staged.unlink(missing_ok=True)+ build_script = self.root / "scripts" / "build_windows.ps1"+ build_exit = self._run_logged([+ shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(build_script),+ "-OutputDirectory", str(staging_dir),+ ])+ if build_exit != 0 or not staged.is_file():+ return None+ return staged++ def packaged_migrations_pass(self, staged: Path) -> bool:+ """在换上生产入口之前,先让暂存包自己跑一次 `migrate status`。++ PyInstaller 漏掉 `migrations/` 的话包能构建、能启动,直到第一次开库才炸;+ 那时旧二进制已经被换走了。这一步用真实的包在真实数据根上验证一遍。+ """+ reset_environment = os.environ.copy()+ reset_environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"+ self.log_path.parent.mkdir(parents=True, exist_ok=True)+ with self.log_path.open("a", encoding="utf-8", errors="replace") as log:+ validation = self._run(+ [str(staged), "migrate", "status"],+ cwd=str(self.root), stdin=subprocess.DEVNULL, stdout=log,+ stderr=subprocess.STDOUT, check=False, env=reset_environment,+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,+ )+ return validation.returncode == 0+def prepare(self, commit: str, changed_paths: tuple[str, ...],) -> WindowsUpdatePreparation:@@ -238,30 +335,12 @@ class WindowsUpdateInstaller:"failed", "代码与测试已通过,但找不到当前托盘 EXE,未执行替换。",)- staging_dir = self.state_dir / "source-sync-build" / commit- staging_dir.mkdir(parents=True, exist_ok=True)- staged = staging_dir / "Peach.exe"- staged.unlink(missing_ok=True)- build_script = self.root / "scripts" / "build_windows.ps1"- build_exit = self._run_logged([- shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(build_script),- "-OutputDirectory", str(staging_dir),- ])- if build_exit != 0 or not staged.is_file():+ staged = self.build_staged_tray(commit, shell=shell)+ if staged is None:return WindowsUpdatePreparation("failed", "代码与测试已通过,但新托盘构建失败;旧托盘和服务保持运行。",)-- reset_environment = os.environ.copy()- reset_environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"- with self.log_path.open("a", encoding="utf-8", errors="replace") as log:- validation = self._run(- [str(staged), "migrate", "status"],- cwd=str(self.root), stdin=subprocess.DEVNULL, stdout=log,- stderr=subprocess.STDOUT, check=False, env=reset_environment,- creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,- )- if validation.returncode != 0:+ if not self.packaged_migrations_pass(staged):return WindowsUpdatePreparation("failed", "新托盘未通过打包迁移资源检查;旧托盘和服务保持运行。",)diff --git a/tests/test_deploy_windows_tray.py b/tests/test_deploy_windows_tray.pynew file mode 100644index 000000000..6ed2589fc--- /dev/null+++ b/tests/test_deploy_windows_tray.py@@ -0,0 +1,131 @@+from __future__ import annotations++import importlib.util+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from peach import __version__+++ROOT = Path(__file__).resolve().parents[1]+SCRIPT = ROOT / "scripts" / "deploy_windows_tray.py"+SPEC = importlib.util.spec_from_file_location("deploy_windows_tray", SCRIPT)+deploy_windows_tray = importlib.util.module_from_spec(SPEC)+assert SPEC.loader is not None+sys.modules[SPEC.name] = deploy_windows_tray+SPEC.loader.exec_module(deploy_windows_tray)+++def git_runner(porcelain: str = "", commit: str = "abc12345def", branch: str = "master"):+ answers = {+ "status --porcelain": porcelain,+ "rev-parse HEAD": commit,+ "rev-parse --abbrev-ref HEAD": branch,+ }++ def run(command, **_kwargs):+ return subprocess.CompletedProcess(+ command, 0, stdout=answers[" ".join(command[1:])], stderr="",+ )++ return run+++class DeployWindowsTrayTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ # 部署入口先 resolve 检出根和目标,断言也得拿 resolve 过的路径比。+ self.root = Path(self.temp.name).resolve()+ self.target = self.root / "dist" / "Peach" / "Peach.exe"+ self.target.parent.mkdir(parents=True)+ self.target.write_bytes(b"old")+ self.staged = self.root / "staging" / "Peach.exe"+ self.staged.parent.mkdir()+ self.staged.write_bytes(b"new")+ self.installer = mock.Mock()+ self.installer.log_path = self.root / "sync.log"+ self.installer.build_staged_tray.return_value = self.staged+ self.installer.packaged_migrations_pass.return_value = True+ self.restarted = mock.Mock(return_value=mock.Mock(+ ok=True, message="托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",+ old_tray_pid=10, new_tray_pid=30, service_pids=(51, 52),+ backup=str(self.target.with_name("Peach.pre-source-sync-20260906-120000.exe")),+ ))++ def tearDown(self):+ self.temp.cleanup()++ def run_deploy(self, **overrides):+ arguments = dict(+ target=self.target, installer=self.installer, restart=self.restarted,+ run=git_runner(), version=lambda **_kwargs: __version__,+ )+ arguments.update(overrides)+ return deploy_windows_tray.deploy(self.root, **arguments)++ def test_a_dirty_checkout_stops_before_anything_is_built_or_swapped(self):+ outcome = self.run_deploy(run=git_runner(porcelain=" M src/peach/tray.py\n"))+ self.assertFalse(outcome["ok"])+ self.assertEqual(outcome["step"], "checkout")+ self.installer.build_staged_tray.assert_not_called()+ self.restarted.assert_not_called()++ def test_a_package_that_fails_the_migration_check_never_reaches_production(self):+ self.installer.packaged_migrations_pass.return_value = False+ outcome = self.run_deploy()+ self.assertFalse(outcome["ok"])+ self.assertEqual(outcome["step"], "validate")+ self.restarted.assert_not_called()+ self.assertEqual(self.target.read_bytes(), b"old")++ def test_a_given_package_is_reused_instead_of_building_again(self):+ outcome = self.run_deploy(staged=self.staged)+ self.assertTrue(outcome["ok"], outcome["message"])+ self.installer.build_staged_tray.assert_not_called()+ self.assertEqual(self.restarted.call_args.kwargs["swap_from"], self.staged)+ self.assertEqual(outcome["commit"], "abc12345def")+ self.assertEqual(outcome["version"], __version__)++ def test_a_tray_that_serves_another_version_is_reported_as_a_failure(self):+ outcome = self.run_deploy(version=lambda **_kwargs: "0.0.1")+ self.assertFalse(outcome["ok"])+ self.assertEqual(outcome["step"], "verify")+ self.assertEqual(outcome["expected_version"], __version__)+ self.assertEqual(outcome["backup"], self.restarted.return_value.backup)++ def test_a_silent_health_endpoint_is_reported_as_a_failure(self):+ outcome = self.run_deploy(version=lambda **_kwargs: None)+ self.assertFalse(outcome["ok"])+ self.assertEqual(outcome["step"], "verify")+ self.assertIn("/healthz", outcome["message"])+++class ServingVersionTests(unittest.TestCase):+ def test_the_verdict_comes_from_the_https_port_checked_against_the_project_ca(self):+ specs = (+ mock.Mock(name="http", health_url="http://127.0.0.1/healthz", verify=True),+ mock.Mock(health_url="https://192.168.0.2/healthz", verify="/ca/peach.crt"),+ )+ specs[0].name = "http"+ specs[1].name = "https"+ response = mock.Mock(status_code=200)+ response.json.return_value = {"ok": True, "version": "9.9.9"}+ with (+ mock.patch.object(deploy_windows_tray, "build_service_specs",+ return_value=specs),+ mock.patch.object(deploy_windows_tray.httpx, "get",+ return_value=response) as get,+ ):+ self.assertEqual(deploy_windows_tray.serving_version(), "9.9.9")+ self.assertEqual(get.call_args.args[0], "https://192.168.0.2/healthz")+ self.assertEqual(get.call_args.kwargs["verify"], "/ca/peach.crt")+ self.assertFalse(get.call_args.kwargs["trust_env"],+ "系统代理会替生产口回话,探测必须直连")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.pyindex 561991987..e64b43083 100644--- a/tests/test_restart_windows_tray.py+++ b/tests/test_restart_windows_tray.py@@ -1,20 +1,29 @@from __future__ import annotations+import contextlibimport importlib.util+import io+import jsonimport sysimport tempfileimport unittestfrom pathlib import Pathfrom unittest import mock+from peach import windows_restart+ROOT = Path(__file__).resolve().parents[1]SCRIPT = ROOT / "scripts" / "restart_windows_tray.py"-SPEC = importlib.util.spec_from_file_location("restart_windows_tray", SCRIPT)-restart_windows_tray = importlib.util.module_from_spec(SPEC)-assert SPEC.loader is not None-sys.modules[SPEC.name] = restart_windows_tray-SPEC.loader.exec_module(restart_windows_tray)+++def load_entry():+ """命令行入口只做参数解析和打印,实现在 `peach.windows_restart`。"""+ spec = importlib.util.spec_from_file_location("restart_windows_tray_entry", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return moduleclass RestartWindowsTrayTests(unittest.TestCase):@@ -38,7 +47,7 @@ class RestartWindowsTrayTests(unittest.TestCase):def test_refuses_when_the_exact_tray_window_is_not_unique(self):start = mock.Mock()- result = restart_windows_tray.restart_tray(+ result = windows_restart.restart_tray(self.target, find_windows=lambda _target: (), start=start,)self.assertFalse(result.ok)@@ -47,9 +56,9 @@ class RestartWindowsTrayTests(unittest.TestCase):def test_timeout_never_force_kills_or_starts_a_second_tray(self):start = mock.Mock()- result = restart_windows_tray.restart_tray(+ result = windows_restart.restart_tray(self.target, timeout=0.001,- find_windows=lambda _target: (restart_windows_tray.TrayWindow(10, 20),),+ find_windows=lambda _target: (windows_restart.TrayWindow(10, 20),),stop_window=lambda _handle: True, alive=lambda _pid: True,start=start, sleep=lambda _seconds: None,)@@ -59,12 +68,12 @@ class RestartWindowsTrayTests(unittest.TestCase):def test_normal_exit_restarts_and_requires_tray_owned_services(self):windows = iter((- (restart_windows_tray.TrayWindow(10, 20),),- (restart_windows_tray.TrayWindow(30, 40),),+ (windows_restart.TrayWindow(10, 20),),+ (windows_restart.TrayWindow(30, 40),),))launched = mock.Mock()launched.poll.return_value = None- result = restart_windows_tray.restart_tray(+ result = windows_restart.restart_tray(self.target,find_windows=lambda _target: next(windows),stop_window=lambda handle: handle == 20,@@ -79,6 +88,70 @@ class RestartWindowsTrayTests(unittest.TestCase):self.assertEqual(result.new_tray_pid, 30)self.assertEqual(result.service_pids, (51, 52))+ def stage(self) -> Path:+ staged = self.root / "staging" / "Peach.exe"+ staged.parent.mkdir()+ staged.write_bytes(b"new")+ return staged++ def test_the_binary_is_swapped_after_the_old_tray_exits_and_before_the_new_starts(self):+ staged = self.stage()+ launched = mock.Mock()+ launched.poll.return_value = None+ bytes_at_start = []+ windows = iter((+ (windows_restart.TrayWindow(10, 20),),+ (windows_restart.TrayWindow(30, 40),),+ ))+ result = windows_restart.restart_tray(+ self.target, swap_from=staged,+ find_windows=lambda _target: next(windows),+ stop_window=lambda _handle: True,+ alive=lambda _pid: False,+ start=lambda target: bytes_at_start.append(target.read_bytes()) or launched,+ services=lambda _pid, _executable: (51, 52),+ sleep=lambda _seconds: None,+ )+ self.assertTrue(result.ok, result.message)+ self.assertEqual(bytes_at_start, [b"new"], "新托盘启动时读到的已经是新二进制")+ self.assertEqual(self.target.read_bytes(), b"new")+ self.assertEqual(Path(result.backup).read_bytes(), b"tray")+ self.assertEqual(result.swapped_from, str(staged))++ def test_a_new_tray_that_never_owns_its_services_is_rolled_back(self):+ staged = self.stage()+ launched = mock.Mock()+ launched.poll.return_value = None+ start = mock.Mock(return_value=launched)+ result = windows_restart.restart_tray(+ self.target, timeout=0.001, swap_from=staged,+ find_windows=lambda _target: (windows_restart.TrayWindow(10, 20),),+ stop_window=lambda _handle: True,+ alive=lambda _pid: False,+ start=start,+ services=lambda _pid, _executable: (),+ sleep=lambda _seconds: None,+ )+ self.assertFalse(result.ok)+ self.assertIn("已回滚到备份并重开旧托盘", result.message)+ self.assertEqual(self.target.read_bytes(), b"tray")+ self.assertEqual(Path(result.backup).read_bytes(), b"tray",+ "备份留在原地,下一次失败还有得退")+ self.assertEqual(start.call_count, 2)+++class RestartEntryTests(unittest.TestCase):+ def test_the_entry_hands_the_package_to_swap_and_prints_the_outcome(self):+ entry = load_entry()+ finished = windows_restart.RestartResult(True, "重启完成", backup="C:/dist/backup.exe")+ with (+ mock.patch.object(entry, "restart_tray", return_value=finished) as restart,+ contextlib.redirect_stdout(io.StringIO()) as printed,+ ):+ self.assertEqual(entry.main(["--swap-from", "staged.exe"]), 0)+ self.assertEqual(restart.call_args.kwargs["swap_from"], Path("staged.exe"))+ self.assertEqual(json.loads(printed.getvalue())["backup"], "C:/dist/backup.exe")+if __name__ == "__main__":unittest.main()diff --git a/tests/test_windows_update.py b/tests/test_windows_update.pyindex 3e4071174..8ba4d2f6f 100644--- a/tests/test_windows_update.py+++ b/tests/test_windows_update.py@@ -4,13 +4,16 @@ import subprocessimport tempfileimport timeimport unittest+import unittest.mockfrom pathlib import Pathfrom unittest.mock import Mockfrom peach.windows_update import sweep_onefile_extractionsfrom peach.windows_update import (+ BACKUP_GLOB,WindowsUpdateInstaller,+ swap_tray_binary,windows_tray_rebuild_required,)@@ -263,3 +266,45 @@ class WindowsTrayReplacerTests(unittest.TestCase):self.assertEqual(paths[0].read_bytes(), b"old")self.assertTrue(paths[3].exists())self.assertEqual(start.call_count, 2)+++class SwapTrayBinaryTests(unittest.TestCase):+ def paths(self, root: Path) -> tuple[Path, Path]:+ target = root / "Peach.exe"+ staged = root / "staged" / "Peach.exe"+ staged.parent.mkdir()+ target.write_bytes(b"old")+ staged.write_bytes(b"new")+ return staged, target++ def test_the_old_binary_is_kept_under_the_name_the_sweeper_recognises(self):+ with tempfile.TemporaryDirectory() as directory:+ staged, target = self.paths(Path(directory).resolve())+ backup = swap_tray_binary(staged, target, sleep=lambda _delay: None)+ self.assertEqual(target.read_bytes(), b"new")+ self.assertEqual(backup.read_bytes(), b"old")+ self.assertEqual([backup], list(target.parent.glob(BACKUP_GLOB)))+ self.assertFalse(staged.exists(), "暂存包被原子移到生产入口")++ def test_a_target_that_is_not_the_production_entry_is_refused(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ staged, target = self.paths(root)+ with self.assertRaises(ValueError):+ swap_tray_binary(staged, root / "Other.exe")+ with self.assertRaises(FileNotFoundError):+ swap_tray_binary(root / "missing.exe", target)+ self.assertEqual(target.read_bytes(), b"old")+ self.assertEqual(list(target.parent.glob(BACKUP_GLOB)), [])++ def test_a_replacement_that_never_lands_leaves_no_orphan_backup(self):+ with tempfile.TemporaryDirectory() as directory:+ staged, target = self.paths(Path(directory).resolve())+ with unittest.mock.patch("peach.windows_update.os.replace",+ side_effect=PermissionError("held")):+ with self.assertRaises(PermissionError):+ swap_tray_binary(staged, target, timeout=0.0,+ sleep=lambda _delay: None)+ self.assertEqual(target.read_bytes(), b"old")+ self.assertEqual(list(target.parent.glob(BACKUP_GLOB)), [],+ "换不上就没有可回滚的东西,备份留着只会被当成一次成功的更新")