Skip to content

armgit / peach

Public Imported from GitHub
0

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

add safe Windows tray restart control

longmeidao0d18d4fcb818
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index c1e4ef8ec..60f16cfe7 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -132,7 +132,7 @@ Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 U
## 运行与部署
-- Windows 日常入口是当前用户 Startup 中的唯一 `Peach.lnk`,指向 `C:\Users\longm\Desktop\peach\peach-app\dist\Peach\Peach.exe`。`R:\peach-app` 是迁移前的旧位置,不再用作运行入口。智能体刷新源码运行态时不得用 Computer Use 点托盘,只能走与“重启服务”等价、且保持或重新建立托盘子服务所有权的项目命令;直接强杀/另启 `peach.exe` 不等价,命令缺失时先补安全入口。
+- Windows 日常入口是当前用户 Startup 中的唯一 `Peach.lnk`,指向 `C:\Users\longm\Desktop\peach\peach-app\dist\Peach\Peach.exe`。`R:\peach-app` 是迁移前的旧位置,不再用作运行入口。智能体刷新源码运行态时不得用 Computer Use 点托盘;运行 `python scripts/restart_windows_tray.py` 会按精确 EXE 路径找到 pystray 隐藏窗口、发送其正常停止消息、等待托盘自行关闭子服务,再静默启动托盘并核对新托盘重新拥有两个服务。找不到唯一窗口或正常退出超时就拒绝,绝不强杀后另启。
- Windows 发布入口使用 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 从原始附件生成正方形 `resources/peach-logo.png` 和多尺寸 `resources/peach.ico`,再构建单一 `dist/Peach/Peach.exe`。无参数运行托盘,`serve`/`migrate` 运行 CLI;桌面快捷方式由 `scripts/create_desktop_shortcut.ps1` 创建,图标使用 `Peach.exe,0`,行为与 FlowLens 的快捷方式一致;Startup 安装仍由 `scripts/manage_tray_startup.ps1` 负责。
- `dist/Peach/Peach.exe` 是本机打包入口,不是可移动的独立发行版:托盘只打包了自己,服务进程仍由项目 venv 的 `peach.exe` 承担(`_peach_executable()` 从 exe 位置逐级向上找 `.venv\Scripts\peach.exe`)。脱离同一台机器的项目 `.venv` 复制不会工作,不要按「单文件绿色版」对外描述。PyInstaller 的资源直接位于 `sys._MEIPASS`,没有源码树的 `src/` 层;打包后的 `migrate`、Web 与品牌资源必须从这里解析,不能再对 `config.py` 固定取 `parents[2]`。
- 托盘单击打开 HTTPS;macOS/Windows 菜单都提供「同步开发进度」「同步 Ledger」「接管 Ledger 写入」、状态、重启、日志和退出。**两个「同步」不能合并成一个按钮**:一个走 GitHub、一个走 SMB 共享,任一方不可达都不该拖住另一方。Windows 开发同步先快进并跑正式测试;服务代码通过后才重启,打包输入变更时另构建新 EXE、检查迁移资源,再由独立助手等旧托盘退出后替换,启动失败自动恢复备份;失败保留待应用标记供下次点击重试。HTTP/HTTPS 服务只观察角色,不自动复制;手动同步先用 `sync.resolve()` 只读判定这次会不会真的复制:`offline` 不是结论——macOS 重启后 SMB 共享不会自己挂回来,托盘按 `SHARED_SMB_HOST`/`SHARED_SMB_SHARE`/`SHARED_SMB_USER` 补挂一次再重判,真挂不上才回话。挂载走 `osascript` 的 `mount volume`(同样经 NetFS 自建挂载点、取钥匙串,但不像 `open smb://` 那样弹 Finder 窗口),并且**先查一次钥匙串**:没有对应记录时 NetFS 不报错,而是弹认证框一直等,于是一次后台点击既卡到超时又在用户面前推出一个密码框。钥匙串记录按主机名存,同一台机器的 IP 和 mDNS 名是两条不同的记录。补挂后仍是 `offline`,以及 `conflict`/`in-sync`,一律直接回话,**不停服务**——停一停再启回来换不到任何东西,只换来一次十几秒的断网页和一条「同步失败」。会复制时才停止自己创建的服务,用 SQLite backup API 与原子替换复制,最后恢复服务。「接管 Ledger 写入」只在共享盘不可达时短路,因为 `in-sync` 对它正是要做的那一次。共享源在 macOS smbfs 上必须以 immutable 已关闭快照读取;共享目标不能由 SQLite 直接打开事务连接。健康端口不归本托盘时拒绝接管。
diff --git a/scripts/restart_windows_tray.py b/scripts/restart_windows_tray.py
new file mode 100644
index 000000000..1476c4876
--- /dev/null
+++ b/scripts/restart_windows_tray.py
@@ -0,0 +1,234 @@
+from __future__ import annotations
+
+import argparse
+import ctypes
+import json
+import os
+import subprocess
+import time
+from ctypes import wintypes
+from dataclasses import asdict, dataclass
+from 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)
+
+ 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)
+
+
+def 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")
+ parser.add_argument("--timeout", type=float, default=25.0)
+ args = parser.parse_args(argv)
+ result = restart_tray(args.target, timeout=max(1.0, args.timeout))
+ print(json.dumps(asdict(result), ensure_ascii=False))
+ return 0 if result.ok else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 14fe5793a..477dc62c4 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -37,6 +37,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_entity_link_install.py", "test_studio_site_harvest.py",
"test_performer_link_harvest.py"),
"tooling": ("test_scripts.py", "test_agent_worktree.py", "test_dependency_policy.py",
+ "test_restart_windows_tray.py",
"test_versioning.py",
"test_windows_update.py", "test_certs.py", "test_config.py",
"test_job_status.py", "test_jobs.py", "test_reference_updates.py",
diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.py
new file mode 100644
index 000000000..2cecd55fc
--- /dev/null
+++ b/tests/test_restart_windows_tray.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import importlib.util
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+
+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)
+
+
+class RestartWindowsTrayTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.root = Path(self.temp.name)
+ self.target = self.root / "dist" / "Peach" / "Peach.exe"
+ self.service = self.root / ".venv" / "Scripts" / "peach.exe"
+ self.target.parent.mkdir(parents=True)
+ self.service.parent.mkdir(parents=True)
+ self.target.write_bytes(b"tray")
+ self.service.write_bytes(b"service")
+
+ def tearDown(self):
+ self.temp.cleanup()
+
+ def test_refuses_when_the_exact_tray_window_is_not_unique(self):
+ start = mock.Mock()
+ result = restart_windows_tray.restart_tray(
+ self.target, find_windows=lambda _target: (), start=start,
+ )
+ self.assertFalse(result.ok)
+ self.assertIn("唯一", result.message)
+ start.assert_not_called()
+
+ def test_timeout_never_force_kills_or_starts_a_second_tray(self):
+ start = mock.Mock()
+ result = restart_windows_tray.restart_tray(
+ self.target, timeout=0.001,
+ find_windows=lambda _target: (restart_windows_tray.TrayWindow(10, 20),),
+ stop_window=lambda _handle: True, alive=lambda _pid: True,
+ start=start, sleep=lambda _seconds: None,
+ )
+ self.assertFalse(result.ok)
+ self.assertIn("未强杀、未另启", result.message)
+ start.assert_not_called()
+
+ 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),),
+ ))
+ launched = mock.Mock()
+ launched.poll.return_value = None
+ result = restart_windows_tray.restart_tray(
+ self.target,
+ find_windows=lambda _target: next(windows),
+ stop_window=lambda handle: handle == 20,
+ alive=lambda _pid: False,
+ start=lambda _target: launched,
+ services=lambda tray_pid, executable: (51, 52)
+ if tray_pid == 30 and executable == self.service else (),
+ sleep=lambda _seconds: None,
+ )
+ self.assertTrue(result.ok)
+ self.assertEqual(result.old_tray_pid, 10)
+ self.assertEqual(result.new_tray_pid, 30)
+ self.assertEqual(result.service_pids, (51, 52))
+
+
+if __name__ == "__main__":
+ unittest.main()