Peach: Local-first video metadata scraper and media manager.
feat(tray): 更新器的备份与暂存构建自带保留上限,打包脚本删掉工作目录
longmeidao8843deec473b
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 27bf82ae3..1b57c972a 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -136,6 +136,7 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt- 对外发布由 `.github/workflows/release.yml` 承担:推 `v<__version__>` 形式的 tag(`v0.7.13` ↔ `0.7.13`)就在 GitHub 上跑 `build_windows.ps1` 与 `build_macos_app.py`,产出 `Peach-<版本>-windows-x64.zip` 与 `Peach-<版本>-macos-<arch>.zip` 并挂到同名 Release;tag 与 `__version__` 不一致在构建前失败。Release 正文取附注 tag 的正文,轻量 tag 由 GitHub 按提交历史生成。`workflow_dispatch` 只上传 artifact,不发布。- 刷新源码运行态不要用 Computer Use 点托盘:`python scripts/restart_windows_tray.py` 按精确 EXE 路径找到 pystray 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务;找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。- `dist/Peach/Peach.exe` 是本机打包入口而不是可移动的独立发行版:托盘只打包了自己,服务进程仍由项目 venv 的 `peach.exe` 承担,`_peach_executable()` 从 exe 位置逐级向上找 `.venv\Scripts\peach.exe`,所以不要按「单文件绿色版」对外描述。+- 更新与打包的产物自带清退:托盘每次启动只保留最近 2 份 `dist/Peach/Peach.pre-source-sync-*.exe` 备份,并删掉 `<数据根>/state/source-sync-build/` 里不属于待应用记录的暂存构建(`WindowsUpdateInstaller.sweep_artifacts`);`build_windows.ps1` 成功后删掉 PyInstaller 工作目录 `build/windows/app`。自动边界只认这两个命名:`Peach.exe` 本体、手工放进 `dist/` 的目录、`build/release-*`、`attic/` 都不碰,手工构建的残留自己删。- PyInstaller 的资源直接位于 `sys._MEIPASS`,没有源码树的 `src/` 层;打包后的 `migrate`、Web 与品牌资源必须从这里解析,不能对 `config.py` 固定取 `parents[2]`。- 创建 Win32 窗口前必须启用 Per-Monitor V2 DPI;正常动作不弹模态 MessageBox,更新检查在后台线程执行并用 pystray 原生非模态通知反馈。- 菜单栏与托盘状态行逐个点名每个服务,例如 `HTTP 正常 · HTTPS 异常(状态码 503)`,异常附最近一次失败原因,不要改回只报「未运行」。diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex a5976fe3d..88f33e785 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -22,7 +22,7 @@5. **厂牌 Logo 补齐与持续校验**:14 个已确认社交 handle 已有内容缓存、provenance、精确/感知哈希、质量与重复门槛及健康报告;仍有 72 个厂牌没有可信 handle,必须继续从官网/公开来源取证,不能猜账号。6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;浏览器历史现可用 SQLite 一致性副本增量进入私有源库,并生成不含 URL/标题的 creator/tag candidate 与聚合报告。旧 2026-08-13 原始包已确认不在 Windows 外置盘;仍需在 Mac 开启 iCloud Safari、完成首次导入,并把两端每周刷新装成系统计划任务。AI 结论不得直接改真相字段。-## 尚未实现(24 项)+## 尚未实现(25 项)1. AI Provider 的真实调用、能力协商、Credential Manager 凭据和候选审核 UI。2. 剩余单一创作者风格板复核、无标签内容补标。@@ -48,8 +48,9 @@22. `peach doctor` 与分级 `/healthz`:`doctor`(另带 `--json`)逐项报版本、数据根可写性、配置文件合法性、数据库能否打开、schema 版本与待执行迁移、FFmpeg/ffprobe/OpenSSL 路径、挂载点可达性、端口占用、是否处在「局域网暴露但无口令」状态、后台任务最近一次失败;输出脱敏,不带口令、cookie、站点凭据和完整媒体路径。`/healthz` 相应从布尔改成分项状态(`database`/`schema`/`configured`/`ffmpeg`/`media_mounts`/`security`),与第 13 条一起做。23. 性能基准:用 SFW 合成数据生成 1k/10k/100k/500k 四档库,nightly 测冷启动到 `/healthz`、目录页与详情页 p95、两字以上搜索 p95、本地 SSD 与网盘挂载的 Range 首字节、空闲 RSS、后台扫描时前台退化倍数、备份期间读请求不失败。门槛用「相对上一次基线下降超过 20%」,不给绝对毫秒数——不同机器不可比。数据集与第 16 条的演示数据集共用。24. CI 的 Windows job 太慢,一次 push 的墙钟由它决定。同一批 2786 个用例在 `macos-latest`(arm64)上 57 秒,在 `windows-latest` 上 1475 秒,本机 Windows 是 324 秒——runner 比开发机还慢 4.6 倍。按时间戳差算,250 个用例(9%)吃掉 1119 秒,每个稳定在 4.5 秒上下,形状像每建一个临时文件被 Defender 扫一遍。两条路各自独立:一是在 Windows job 里对 runner 的临时目录加 `Add-MpPreference -ExclusionPath`,先量一轮确认是不是 Defender;二是把 `scripts/test_runner.py` 的域拆成矩阵分片并行跑,代价是每个分片重付一次装依赖的 37 秒。不要为了缩短墙钟把 Windows job 从矩阵里去掉:它是生产平台,也是唯一能拦住 Windows 独有回归的地方。+25. 托盘子服务的日志不轮转:`ServiceManager` 以追加模式打开 `logs/tray-<服务>.out.log` 与 `.err.log`,本机一周就长到 28 MB,`tray-scan.out.log` 与 `windows-source-sync.log` 同样只增不减。在起服务前按大小轮转,超过阈值改名保留一代即可;写文件的是子进程的 stdout,不经 `logging`,所以 `RotatingFileHandler` 用不上。-合计:**30 项开放需求**,其中 6 项已有骨架,24 项尚未实现。已完成的需求不在这里留痕,去 Git 历史查。+合计:**31 项开放需求**,其中 6 项已有骨架,25 项尚未实现。已完成的需求不在这里留痕,去 Git 历史查。## 待执行的操作(32 项)diff --git a/scripts/build_windows.ps1 b/scripts/build_windows.ps1index 2d6c132d7..51526f95b 100644--- a/scripts/build_windows.ps1+++ b/scripts/build_windows.ps1@@ -1,4 +1,4 @@-param(+param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\Peach'))@@ -41,9 +41,10 @@ if (-not (Test-Path -LiteralPath (Join-Path $ProjectRoot 'web\dist\peach-ui.js')}$BuildPath = Join-Path $ProjectRoot 'build\windows'+$WorkPath = Join-Path $BuildPath 'app'New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null& $Python -m PyInstaller --noconfirm --clean --onefile --windowed --name Peach `- --distpath $OutputPath --workpath (Join-Path $BuildPath 'app') --specpath $BuildPath `+ --distpath $OutputPath --workpath $WorkPath --specpath $BuildPath `--icon (Join-Path $ProjectRoot 'resources\peach.ico') `--add-data "$(Join-Path $ProjectRoot 'web');web" `--add-data "$(Join-Path $ProjectRoot 'migrations');migrations" `@@ -51,6 +52,11 @@ New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null(Join-Path $ProjectRoot 'scripts\build_app_entry.py')if ($LASTEXITCODE -ne 0) { throw 'Peach build failed.' }+# 工作目录只服务这一次构建:`--clean` 已让下一次不复用它,留着只是几十 MB 的中间产物。+if (Test-Path -LiteralPath $WorkPath) {+ Remove-Item -LiteralPath $WorkPath -Recurse -Force+}+[pscustomobject]@{Executable = Join-Path $OutputPath 'Peach.exe'Icon = Join-Path $ProjectRoot 'resources\peach.ico'diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 388a951a5..1329a78cb 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -976,6 +976,9 @@ class PeachTray:def run(self) -> None:self.manager.start_missing()+ # 上一次更新留下的备份与暂存构建在这里清退:替换助手结束时托盘已经不在,+ # 只有下一次启动能确认「新托盘已经活下来、旧备份可以少留一份」。+ self.windows_updates.sweep_artifacts()self._startup_warning = Noneif self.gate.waiting:if self.manager.wait_until_ready():diff --git a/src/peach/windows_update.py b/src/peach/windows_update.pyindex e534ddf88..2b0f1056f 100644--- a/src/peach/windows_update.py+++ b/src/peach/windows_update.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import loggingimport osimport shutilimport subprocess@@ -13,6 +14,12 @@ from typing import Callablefrom .fsutil import atomic_write_text+log = logging.getLogger(__name__)++BACKUP_GLOB = "Peach.pre-source-sync-*.exe"+STAGING_DIRNAME = "source-sync-build"+KEEP_BACKUPS = 2+WINDOWS_TRAY_INPUTS = ("src/peach/","scripts/build_app_entry.py",@@ -95,6 +102,43 @@ class WindowsUpdateInstaller:def clear_pending(self) -> None:self.pending_path.unlink(missing_ok=True)+ def sweep_artifacts(self, *, keep_backups: int = KEEP_BACKUPS) -> tuple[Path, ...]:+ """删掉更新流程留下、已经没人会读的产物,托盘每次启动调一次。++ 每次更新都会在 EXE 旁边留一份 `Peach.pre-source-sync-<时间>.exe` 备份、在+ `state/source-sync-build/<commit>/` 留一份暂存构建,两者各约 40 MB。备份只留最新+ `keep_backups` 份;暂存目录只留待应用记录指着的那个提交——替换助手要等新托盘+ 活过 3 秒才清掉待应用记录,所以刚换上来的那份到下一次启动才会被清。只认更新器+ 自己的命名,`Peach.exe` 本体和手工放进目录的任何文件一律不碰;删不掉的只记日志,+ 不影响启动。+ """+ removed: list[Path] = []+ backups = sorted(self.current_executable.parent.glob(BACKUP_GLOB))+ stale_count = max(len(backups) - max(keep_backups, 0), 0)+ for stale in backups[:stale_count]:+ try:+ stale.unlink()+ except OSError as exc:+ log.warning("旧托盘备份未能删除 %s: %s", stale, exc)+ continue+ removed.append(stale)++ pending = self.pending()+ staging_root = self.state_dir / STAGING_DIRNAME+ if staging_root.is_dir():+ for entry in sorted(staging_root.iterdir()):+ if not entry.is_dir():+ continue+ if pending is not None and entry.name == pending.commit:+ continue+ try:+ shutil.rmtree(entry)+ except OSError as exc:+ log.warning("暂存构建未能删除 %s: %s", entry, exc)+ continue+ removed.append(entry)+ return tuple(removed)+def _powershell_executable(self) -> str | None:if self._powershell:return self._powershelldiff --git a/tests/test_windows_update.py b/tests/test_windows_update.pyindex 8fbbb49f2..04b21a2a1 100644--- a/tests/test_windows_update.py+++ b/tests/test_windows_update.py@@ -118,6 +118,68 @@ class WindowsUpdateInstallerTests(unittest.TestCase):popen.assert_not_called()self.assertEqual(target.read_bytes(), b"old")+ def test_sweep_keeps_recent_backups_and_pending_staging_only(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ target, state, logs = self.make_tree(root)+ for stamp in ("20260901-090000", "20260902-090000", "20260903-090000"):+ (target.parent / f"Peach.pre-source-sync-{stamp}.exe").write_bytes(b"old")+ manual = target.parent / "Peach.pre-0.7.4-20260828-160731.exe"+ manual.write_bytes(b"manual")+ staging = state / "source-sync-build"+ for commit in ("aaaa1111", "bbbb2222"):+ (staging / commit).mkdir(parents=True)+ (staging / commit / "Peach.exe").write_bytes(b"staged")+ (staging / "windows-source-sync.log").write_text("log", encoding="ascii")+ installer = WindowsUpdateInstaller(+ root, state_dir=state, log_dir=logs,+ current_executable=target, powershell="pwsh", frozen=True,+ )+ installer.mark_pending("bbbb2222", ("src/peach/tray.py",))++ removed = installer.sweep_artifacts()++ self.assertEqual(+ sorted(path.name for path in removed),+ ["Peach.pre-source-sync-20260901-090000.exe", "aaaa1111"],+ )+ self.assertEqual(+ sorted(path.name for path in target.parent.glob("Peach.pre-source-sync-*.exe")),+ ["Peach.pre-source-sync-20260902-090000.exe",+ "Peach.pre-source-sync-20260903-090000.exe"],+ )+ self.assertEqual(target.read_bytes(), b"old", "运行中的 EXE 本体不在清退边界内")+ self.assertTrue(manual.exists(), "只认更新器自己的命名,手工放的文件不碰")+ self.assertTrue((staging / "bbbb2222" / "Peach.exe").exists(), "待应用的暂存构建保留")+ self.assertTrue((staging / "windows-source-sync.log").exists(), "只删目录,不删文件")++ installer.clear_pending()+ removed = installer.sweep_artifacts()+ self.assertEqual([path.name for path in removed], ["bbbb2222"])+ self.assertEqual(+ sorted(path.name for path in staging.iterdir()), ["windows-source-sync.log"],+ )++ def test_sweep_is_a_no_op_without_update_history(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ target, state, logs = self.make_tree(root)+ installer = WindowsUpdateInstaller(+ root, state_dir=state, log_dir=logs,+ current_executable=root / "missing" / "python.exe",+ powershell="pwsh", frozen=False,+ )+ self.assertEqual(installer.sweep_artifacts(), ())+ self.assertFalse(state.exists(), "清退不创建目录")+++class WindowsBuildScriptTests(unittest.TestCase):+ def test_build_script_removes_pyinstaller_work_directory(self):+ script = (ROOT / "scripts" / "build_windows.ps1").read_text(encoding="utf-8-sig")+ self.assertIn("--clean", script, "工作目录不复用,所以删掉它不损失任何东西")+ self.assertIn("--workpath $WorkPath", script)+ self.assertIn("Remove-Item -LiteralPath $WorkPath -Recurse -Force", script)+class WindowsTrayReplacerTests(unittest.TestCase):@classmethod