Peach: Local-first video metadata scraper and media manager.
feat: Windows 独立测试包与单机开箱配置
longmeidao95b59884e0de
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 1dd409d05..8b7e72b56 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,8 +1,5 @@name: Release-# 推 `vX.Y.Z` tag 就出 Windows 与 macOS 制品并挂到 GitHub Release;手动触发只上传-# artifact 供试跑,不发布。版本唯一来源是 `src/peach/__init__.py::__version__`-# (ADR-0012),tag 名必须等于 `v<__version__>`,不一致在构建前就失败。on:push:tags: ["v*.*.*"]@@ -11,15 +8,13 @@ on:permissions:contents: read-# 与 test.yml 同一口径:Windows runner 的 stdout 默认 cp1252,打包脚本里的中文提示-# 会抛 UnicodeEncodeError。env:PYTHONUTF8: "1"PYTHONIOENCODING: "utf-8"jobs:windows:- name: Windows x64 制品+ name: Windows x64 独立测试包runs-on: windows-latestoutputs:version: ${{ steps.version.outputs.version }}@@ -27,155 +22,75 @@ jobs:- uses: actions/checkout@v7- uses: actions/setup-python@v7with:- python-version: "3.14"- cache: pip- check-latest: true- # 打包脚本会重建 island 产物(ADR-0022),运行时没有 Node,所以这里要装。+ python-version: '3.14'- uses: actions/setup-node@v7with:- node-version: "24"- cache: npm- cache-dependency-path: frontend/package-lock.json-- - name: 核对 tag 与 __version__+ node-version: '24'+ - name: 核对发布版本id: version- shell: bash+ shell: pwshrun: |- version="$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' src/peach/__init__.py)"- if [ -z "$version" ]; then- echo "::error::src/peach/__init__.py 里读不到 __version__"- exit 1- fi- if [ "$GITHUB_REF_TYPE" = "tag" ] && [ "$GITHUB_REF_NAME" != "v$version" ]; then- echo "::error::tag $GITHUB_REF_NAME 与 __version__ $version 不一致;发布 tag 必须是 v$version"- exit 1- fi- echo "version=$version" >> "$GITHUB_OUTPUT"-- - name: 安装依赖+ $ReleaseVersion = (Select-String -Path src/peach/__init__.py -Pattern '__version__ = "(.*)"').Matches.Groups[1].Value+ if (-not $ReleaseVersion) { throw '无法读取版本' }+ if ($env:GITHUB_REF_TYPE -eq 'tag' -and $env:GITHUB_REF_NAME -ne "v${ReleaseVersion}") { throw 'Tag 与版本不一致' }+ "version=${ReleaseVersion}" >> $env:GITHUB_OUTPUT+ - name: 安装构建依赖shell: pwshrun: |python -m venv .venv- & .\.venv\Scripts\python.exe -m pip install --upgrade pip- & .\.venv\Scripts\python.exe -m pip install -e ".[build]"- & .\.venv\Scripts\python.exe -m pip check-- - name: 打包 Peach.exe+ & ./.venv/Scripts/python.exe -m pip install --no-cache-dir -e '.[build]'+ & ./.venv/Scripts/python.exe -m pip check+ - name: 构建独立目录包shell: pwsh- run: '& .\scripts\build_windows.ps1'-- - name: 压缩+ run: '& ./scripts/build_windows.ps1 -Standalone'+ - name: 压缩完整程序目录shell: pwshrun: |New-Item -ItemType Directory -Path release | Out-Null- Compress-Archive -Path dist\Peach\Peach.exe -DestinationPath "release\Peach-${{ steps.version.outputs.version }}-windows-x64.zip"-+ Copy-Item docs/TESTING_DESKTOP.md dist/Peach/开始使用.md+ Compress-Archive -Path dist/Peach -DestinationPath 'release/Peach-${{ steps.version.outputs.version }}-windows-x64.zip'+ Copy-Item scripts/smoke_desktop.py release/smoke_desktop.py- uses: actions/upload-artifact@v7with:- name: Peach-${{ steps.version.outputs.version }}-windows-x64- path: release/*.zip- if-no-files-found: error+ name: desktop-candidate+ path: release/*- macos:- name: macOS 制品- runs-on: macos-latest- outputs:- version: ${{ steps.version.outputs.version }}+ desktop-smoke:+ name: 仅下载制品验收+ needs: windows+ runs-on: windows-lateststeps:- - uses: actions/checkout@v7- - uses: actions/setup-python@v7+ - uses: actions/download-artifact@v8with:- python-version: "3.14"- cache: pip- check-latest: true- - uses: actions/setup-node@v7+ name: desktop-candidate+ - uses: actions/setup-python@v7with:- node-version: "24"- cache: npm- cache-dependency-path: frontend/package-lock.json-- - name: 核对 tag 与 __version__- id: version- shell: bash- run: |- version="$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' src/peach/__init__.py)"- if [ -z "$version" ]; then- echo "::error::src/peach/__init__.py 里读不到 __version__"- exit 1- fi- if [ "$GITHUB_REF_TYPE" = "tag" ] && [ "$GITHUB_REF_NAME" != "v$version" ]; then- echo "::error::tag $GITHUB_REF_NAME 与 __version__ $version 不一致;发布 tag 必须是 v$version"- exit 1- fi- echo "version=$version" >> "$GITHUB_OUTPUT"-- - name: 安装依赖- shell: bash- run: |- python -m venv .venv- ./.venv/bin/python -m pip install --upgrade pip- ./.venv/bin/python -m pip install -e ".[build,macos]"- ./.venv/bin/python -m pip check-- - name: 生成 Peach.app- shell: bash- run: ./.venv/bin/python scripts/build_macos_app.py-- # ditto 保留 bundle 的可执行位与资源分支;zip 会丢。- - name: 压缩- id: archive- shell: bash+ python-version: '3.14'+ - name: 在源码树外验证开箱配置与应用+ shell: pwshrun: |- arch="$(uname -m)"- mkdir -p release- ditto -c -k --keepParent dist/Peach.app "release/Peach-${{ steps.version.outputs.version }}-macos-${arch}.zip"- echo "arch=$arch" >> "$GITHUB_OUTPUT"-- - uses: actions/upload-artifact@v7- with:- name: Peach-${{ steps.version.outputs.version }}-macos-${{ steps.archive.outputs.arch }}- path: release/*.zip- if-no-files-found: error+ Expand-Archive -Path 'Peach-${{ needs.windows.outputs.version }}-windows-x64.zip' -DestinationPath candidate+ python smoke_desktop.py candidate/Peach/Peach.exe+ if ($LASTEXITCODE -ne 0) { throw '制品验收失败' }release:- name: GitHub Release+ name: GitHub 预发布if: github.ref_type == 'tag'- needs: [windows, macos]+ needs: [windows, desktop-smoke]runs-on: ubuntu-latestpermissions:contents: writesteps:- - uses: actions/checkout@v7- uses: actions/download-artifact@v8with:+ name: desktop-candidatepath: release- merge-multiple: true-- # checkout 把 tag 指向提交对象,附注 tag 的正文取不到,所以按 ref 再拉一次原 tag。- # 轻量 tag 没有正文,交给 GitHub 按提交历史生成说明。- - name: 取 tag 正文- id: notes- shell: bash- run: |- git fetch --force origin "refs/tags/$GITHUB_REF_NAME:refs/tags/$GITHUB_REF_NAME"- if [ "$(git cat-file -t "$GITHUB_REF_NAME")" = "tag" ]; then- git for-each-ref --format='%(contents:subject)%0a%0a%(contents:body)' "refs/tags/$GITHUB_REF_NAME" > notes.md- fi- if [ -s notes.md ] && [ -n "$(tr -d '[:space:]' < notes.md)" ]; then- echo "source=tag" >> "$GITHUB_OUTPUT"- else- echo "source=generated" >> "$GITHUB_OUTPUT"- fi-- - name: 创建 Release- shell: bash+ - name: 创建预发布env:GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}VERSION: ${{ needs.windows.outputs.version }}run: |- ls -l release- if [ "${{ steps.notes.outputs.source }}" = "tag" ]; then- gh release create "$GITHUB_REF_NAME" release/*.zip --verify-tag --title "Peach $VERSION" --notes-file notes.md- else- gh release create "$GITHUB_REF_NAME" release/*.zip --verify-tag --title "Peach $VERSION" --generate-notes- fi+ cd release+ sha256sum *.zip > SHA256SUMS.txt+ gh release create "$GITHUB_REF_NAME" *.zip SHA256SUMS.txt --verify-tag --prerelease --title "Peach $VERSION · Windows 测试版" --notes 'Windows x64 独立测试包。完整解压后双击 Peach.exe,选择媒体文件夹即可开始。本机使用;无需 Python、Git 或 Node。FFmpeg 需另装,未安装时不提供转码与缩略图。配置和日志入口见程序内「配置 Peach」。macOS 请按 README 使用源码安装。'diff --git a/README.en.md b/README.en.mdindex 9ecb794d9..b3eaeb000 100644--- a/README.en.md+++ b/README.en.md@@ -88,7 +88,7 @@ The repository stores no media, databases, credentials, logs, `.venv`, build out## Downloads-Every `v<version>` tag publishes two archives on GitHub Releases: `Peach-<version>-windows-x64.zip` (a single-file `Peach.exe`) and `Peach-<version>-macos-<arch>.zip` (the menu-bar `Peach.app`). They are only the tray and menu-bar entry points, not a portable build: the service process still runs from the repository's `.venv`, so complete the three steps under "Installation" first, then place the extracted `Peach.exe` somewhere inside the repository (for example `dist\Peach\`); double-clicking the macOS `Peach.app` only kicks the LaunchAgent, which is registered with `./.venv/bin/python scripts/install_macos_agent.py install`. FFmpeg is still installed by you, as listed under Prerequisites. The tray's "Check for updates" only reports the version for these archives; it downloads and installs nothing (ADR-0012).+Windows testers can download `Peach-<version>-windows-x64.zip` from [GitHub Releases](https://github.com/longmeidao/peach/releases), extract the complete folder, and double-click `Peach.exe`. Choose a media folder in the first-run page to get started. The runtime is bundled and access is local to this computer. Configuration is available from Settings and the tray menu. Install FFmpeg separately; replace the entire program folder when updating. See [Windows testing guide](docs/TESTING_DESKTOP.md). macOS users currently follow the source installation steps below.## Installationdiff --git a/README.md b/README.mdindex aa35615b1..99dcd31f7 100644--- a/README.md+++ b/README.md@@ -84,7 +84,7 @@ peach-app/## 下载制品-每个 `v<版本>` tag 在 GitHub Releases 挂两个压缩包:`Peach-<版本>-windows-x64.zip`(单文件 `Peach.exe`)与 `Peach-<版本>-macos-<arch>.zip`(菜单栏 `Peach.app`)。它们只是托盘与菜单栏的入口,不是免安装的绿色版:服务进程仍由仓库的 `.venv` 承担,所以先按下面「安装」完成三步,再把解压出的 `Peach.exe` 放进仓库目录下(例如 `dist\Peach\`);macOS 的 `Peach.app` 双击只是唤起 LaunchAgent,先 `./.venv/bin/python scripts/install_macos_agent.py install` 注册。FFmpeg 仍按前置条件自装。托盘「检查更新」对制品只报告版本,不下载也不安装更新(ADR-0012)。+Windows 调试用户下载 [GitHub Releases](https://github.com/longmeidao/peach/releases) 的 `Peach-<版本>-windows-x64.zip`,完整解压后双击 `Peach.exe`,在首次设置页选择媒体文件夹即可开始。程序自带运行环境,支持本机访问;配置入口在页面「设置」和托盘菜单。FFmpeg 另装,更新时完整替换程序目录。详细步骤见 [Windows 测试版](docs/TESTING_DESKTOP.md)。macOS 当前按下面的源码安装流程使用。## 安装diff --git a/docs/FRONTEND.md b/docs/FRONTEND.mdindex a10fe61a3..25a7f3991 100644--- a/docs/FRONTEND.md+++ b/docs/FRONTEND.md@@ -23,7 +23,7 @@ Vite + TypeScript + Preact。迁移方式是 strangler:**遗留路由继续拥首次运行页(未配置时的 `GET /` 与 `POST /setup`)不在这张表里:它是 SPA 外壳之外的一张独立页面,HTML 与样式都自包含在 `src/peach/routes_pages.py`,不引 `web/` 的任何资产,也不是island。原因是那一套一上来就打 `/api/items`,而未配置的机器还没有数据库;它也没有客户端-状态,原生 `<form method="post">` 不写一行 JS 就能工作。+状态,原生 `<form method="post">` 不写一行 JS 就能工作。本机 `/configuration` 复用同一套服务端表单和主题 token,设置成功以浏览器 cookie 登录并跳入馆藏。产物名字不带内容哈希:引用它的 `web/app.js` 不经过构建,构建时改不了那里的路径。缓存由服务端兜住:`/dist/` 与 `/app.js`、`/app.css`、`/js/` 同一档,回diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex ec1a7fe83..b31833801 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -129,7 +129,7 @@ React 渲染的规格页、用户截图这类给不出可重抓字节的实测命令、顺序、失败表现和踩过的坑见 `docs/OPERATIONS.md`,这里只留边界。-- Windows 日常入口是当前用户 Startup 里唯一的 `Peach.lnk`,指向项目内打包的托盘 EXE;它不是可移动发行版,服务进程仍由项目 venv 的 `peach.exe` 承担。刷新源码运行态走 `scripts/restart_windows_tray.py`。+- 源码部署由项目 venv 持有服务,刷新入口为 `scripts/restart_windows_tray.py`。独立测试包自带运行环境,数据在用户目录;配置更改由托盘消费标记并重启子服务。- 「同步开发进度」(GitHub)和「同步 Ledger」(SMB 共享)是两条独立通道,任一方不可达都不该拖住另一方;服务只观察角色不自动复制。- 两台机器可以同时跑服务,但同时写入会很快冲突转只读;「接管 Ledger 写入」的短路与拒绝条件见 OPERATIONS。- `src/peach/__init__.py::__version__` 是版本唯一来源;自动更新只做 `merge --ff-only`,不 stash、不 rebase、不 `--force`,工作区脏或两边分叉就原样报出来交给人——并行工作树和主检出共用同一个对象库。diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 1b57c972a..5f8a7436a 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -133,7 +133,7 @@ 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` 承担:推 `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,不发布。+- 对外测试包由 `.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 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务;找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。- `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/` 都不碰,手工构建的残留自己删。diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex 88f33e785..f38784ce9 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -38,7 +38,7 @@12. 非 editable 安装的跨平台验收:wheel 资源与 Windows 基础依赖、仓库外 CLI 冒烟已就绪,仍需取得 macOS、Python 3.12 消费任务结果。13. 健康检查生产验收:`db` 区分 missing、empty、available、unavailable,`?ready=1` 检查 schema 校验和;待部署后用项目 CA 验证 HTTPS 与损坏/未初始化状态。14. 界面国际化:界面目前只有中文,先补英文。-15. 制品对下载者可用与更新渠道:Release 工作流已按 tag 产出 Windows 与 macOS 压缩包,但两者都只是托盘/菜单栏入口,服务仍由仓库 `.venv` 承担,下载者仍要先完成源码安装;要做成不依赖检出的独立发行版,并让托盘「检查更新」对下载的制品也成立(目前只对 git 检出成立)。+15. 制品与更新渠道:Windows 独立测试包、首次引导与本机配置表单已实现,Release 消费任务只下载制品验收。剩余为 macOS 独立包、代码签名、自动更新、局域网配对和更完整的配置管理。测试包更新采用退出程序后完整解压新版,数据目录保持独立。16. 「第一个小时」教程与故障排查文档:init → 声明来源根 → scan → 打开页面 → 手机信任 CA → 托盘/菜单栏自启动,每一步写清失败表现与对应的排查动作;截图用一套小的 SFW 演示数据集生成,不取自真实馆藏。17. 项目网站:一页说明是什么、截图、安装入口与文档链接。18. 口味导入引导:`/taste` 上传(Takeout ZIP、browserexport 兼容文件)与 `scripts/taste_history.py` 直读本机浏览器库两条路都能用,但没有面向陌生人的文档。需要一页「各浏览器怎么导出、多台设备怎么各自刷新」教程,把脚本折进 `peach` CLI(见第 7 条),并写明定时刷新的安装方式。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 27875be6c..65b7b12e9 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -5,6 +5,8 @@## 复用决策门槛+- 独立 Windows 测试包复用 PyInstaller 6.22.2(GPL-2.0-or-later,带分发 bootloader 例外)的 [onedir 与自启动子进程](https://pyinstaller.org/en/stable/common-issues-and-pitfalls.html);使用已有精确固定的 build 依赖。Python 3.14 / Windows x64 在清除开发工具 PATH、隔离数据目录下实测初始化、页面与 API。保留 Peach 的进程所有权、数据目录、配置和扫描策略;onefile 的托盘入口只用于既有源码部署,独立包采用完整目录以共享资源并避免重复解包。没有新增运行时依赖。+- 运行一致性复评:复用 `LedgerDatabase.write_transaction` 的提交边界和标准库 `OrderedDict`;HTTP 导航复用 FastAPI/Starlette,图片复验复用 `StaticFiles.is_not_modified` 与 `FileResponse` 的 ETag。列表使用 SQLite 的 IN/UNION 保留隐藏标签与多标签组合,不引入查询框架。- wheel 资源复用 setuptools 84.0.0 的 `build_py.copy_tree`,资源位置遵循[官方包内数据建议](https://setuptools.pypa.io/en/stable/userguide/datafiles.html)。自定义钩子仅复制三个既有资源目录,因为源码、桌面构建和前端产物仍共用其维护位置;Windows 基础依赖全新安装及仓库外 API 冒烟已验证。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 2cd0abe4f..d0e7c521c 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -2,11 +2,12 @@最后核验:2026-09-04-本文件写「现在是什么样」,不按批次累积:待办去 `docs/PRODUCT_BACKLOG.md`,长期规则去-`docs/HANDOFF.md` 与 `docs/REUSE.md`,已完成批次与事故由 Git 历史保存。+本文件记录当前状态;待办见 `docs/PRODUCT_BACKLOG.md`,长期知识见 `docs/HANDOFF.md`。## 运行态+- Windows 测试包 `0.7.14` 待发布,生产未替换。+- Windows 是当前 ledger writer,入口 `dist\Peach\Peach.exe`;代码、`peach-data`、worktree 和共享传输点同在一个顶层目录,外置盘只提供 `R:\media`。- 托盘必须以普通权限启动:提升权限后的令牌看不到 CloudDrive 的 `A:` / `B:`,会把 PikPak 和 115 误报为脱盘。- Windows HTTP 为 `0.0.0.0:80`,HTTPS 为当前 LAN IPv4 的 443,mDNS 名见 `[server].mdns_name`;线上版本 `0.7.13`、`ledger_sync=writer`。diff --git a/docs/TESTING_DESKTOP.md b/docs/TESTING_DESKTOP.mdnew file mode 100644index 000000000..f50433603--- /dev/null+++ b/docs/TESTING_DESKTOP.md@@ -0,0 +1,24 @@+# Windows 测试版++1. 下载 `Peach-<版本>-windows-x64.zip`,右键「全部解压」。保留整个 `Peach` 文件夹。+2. 双击 `Peach.exe`。浏览器会打开首次设置页。+3. 填入已有媒体文件夹的完整路径,选择是否立即扫描,提交。设置完成后自动进入馆藏。++测试包仅在这台电脑访问,不需要安装 Python、Git、Node 或 OpenSSL。+数据保存在当前用户的 `%LOCALAPPDATA%\Peach\peach-data`,和程序目录分开。++## 配置与反馈++- 页面右上角「设置」→「媒体文件夹与服务配置」,或托盘「配置 Peach」,可以修改媒体文件夹、端口并请求扫描。+- 保存配置会重新启动本机服务,正在播放的视频会中断;已有配置备份为 `config.previous.toml`。+- 配置页列出版本、数据目录和日志目录。反馈问题时写上版本、操作步骤、预期结果和实际结果;日志请先检查并移除个人路径与来源网址,不发送 `secrets` 目录或账本。+- 端口被占用时,退出占用该端口的其他程序后重试;修改端口时界面会检查冲突。+- 测试包没有代码签名。如果 Windows 提示未识别应用,请核对下载来自本项目 Release,并与 `SHA256SUMS.txt` 对照后再决定是否运行。++## 播放与更新++浏览器支持的 MP4 可以直接播放。转码、抽帧和缩略图需要 FFmpeg 与 ffprobe:安装后加入 PATH,或把两个程序放到数据目录下的 `tools\ffmpeg\bin`,退出并重新启动 Peach。++更新时先在托盘退出 Peach,再完整解压新版到新的程序目录。不要只替换 EXE;`_internal` 是程序的一部分。数据目录保留不动,重新启动会使用已有配置。++macOS 独立桌面包仍在开发,当前按 README 的源码安装流程使用。diff --git a/scripts/build_app_entry.py b/scripts/build_app_entry.pyindex 332ab5c3a..bed352d29 100644--- a/scripts/build_app_entry.py+++ b/scripts/build_app_entry.py@@ -67,4 +67,6 @@ def main(argv: list[str] | None = None) -> int:if __name__ == "__main__":+ import multiprocessing+ multiprocessing.freeze_support()raise SystemExit(main())diff --git a/scripts/build_windows.ps1 b/scripts/build_windows.ps1index 51526f95b..326f0d5cf 100644--- a/scripts/build_windows.ps1+++ b/scripts/build_windows.ps1@@ -1,10 +1,15 @@param(- [string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\Peach')+ [string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\Peach'),+ [switch]$Standalone)$ErrorActionPreference = 'Stop'$ProjectRoot = Split-Path -Parent $PSScriptRoot$Python = Join-Path $ProjectRoot '.venv\Scripts\python.exe'+if (-not (Test-Path -LiteralPath $Python)) {+ $BuildCommonGit = (& git -C $ProjectRoot rev-parse --path-format=absolute --git-common-dir).Trim()+ $Python = Join-Path (Split-Path -Parent $BuildCommonGit) '.venv\Scripts\python.exe'+}$OutputPath = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) {[System.IO.Path]::GetFullPath($OutputDirectory)} else {@@ -43,14 +48,29 @@ 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 $WorkPath --specpath $BuildPath `+$BuildMode = @('--onefile')+$BuildDestination = $OutputPath+if ($Standalone) {+ $BuildMode = @('--onedir', '--add-data', "$(Join-Path $PSScriptRoot 'standalone.txt');.")+ $BuildDestination = Split-Path -Parent $OutputPath+}+& $Python -m PyInstaller --noconfirm --clean @BuildMode --windowed --name Peach `+ --distpath $BuildDestination --workpath $WorkPath --specpath $BuildPath `+ --paths (Join-Path $ProjectRoot 'src') `+ --collect-all curl_cffi --collect-all resvg_py `+ --hidden-import uvicorn.logging --hidden-import uvicorn.loops.auto `+ --hidden-import uvicorn.protocols.http.auto --hidden-import uvicorn.protocols.websockets.auto `+ --hidden-import uvicorn.lifespan.on `--icon (Join-Path $ProjectRoot 'resources\peach.ico') `--add-data "$(Join-Path $ProjectRoot 'web');web" `--add-data "$(Join-Path $ProjectRoot 'migrations');migrations" `--add-data "$(Join-Path $ProjectRoot 'resources');resources" `(Join-Path $ProjectRoot 'scripts\build_app_entry.py')if ($LASTEXITCODE -ne 0) { throw 'Peach build failed.' }+if ($Standalone) {+ Copy-Item -LiteralPath (Join-Path $ProjectRoot 'docs/TESTING_DESKTOP.md') -Destination (Join-Path $OutputPath '开始使用.md')+ Copy-Item -LiteralPath (Join-Path $ProjectRoot 'LICENSE') -Destination (Join-Path $OutputPath 'LICENSE.txt')+}# 工作目录只服务这一次构建:`--clean` 已让下一次不复用它,留着只是几十 MB 的中间产物。if (Test-Path -LiteralPath $WorkPath) {diff --git a/scripts/smoke_desktop.py b/scripts/smoke_desktop.pynew file mode 100644index 000000000..50c087e2a--- /dev/null+++ b/scripts/smoke_desktop.py@@ -0,0 +1,96 @@+"""仅用标准库在临时目录验证桌面制品,不读取真实馆藏。"""+from __future__ import annotations++import argparse+import json+import http.cookiejar+import os+import re+from pathlib import Path+import socket+import subprocess+import tempfile+import time+import urllib.error+import urllib.request+import urllib.parse+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("executable", type=Path)+ args = parser.parse_args()+ executable = args.executable.resolve(strict=True)+ with tempfile.TemporaryDirectory(prefix="peach-desktop-") as directory:+ root = Path(directory).resolve()+ data = root / "data"+ media = root / "media"+ media.mkdir()+ environment = dict(os.environ, PEACH_DATA_ROOT=str(data), PYTHONIOENCODING="utf-8")+ environment.pop("PYTHONPATH", None)+ # 制品不得借助用户安装的 Python、Git、Node、FFmpeg 或 OpenSSL。+ environment["PATH"] = os.environ.get("SystemRoot", "/usr") + ("/System32" if os.name == "nt" else "/bin")+ with (root / "runtime.log").open("wb") as log:+ with socket.socket() as reservation:+ reservation.bind(("127.0.0.1", 0))+ port = reservation.getsockname()[1]+ command = [str(executable), "serve", "--host", "127.0.0.1", "--port", str(port),+ "--no-ledger-sync", "--no-mdns"]+ process = subprocess.Popen(command + ["--setup"], cwd=root, env=environment, stdout=log, stderr=log)+ try:+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),+ urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))+ base = f"http://127.0.0.1:{port}"+ deadline = time.monotonic() + 40+ while True:+ try:+ with opener.open(base + "/healthz", timeout=1) as response:+ health = json.load(response)+ break+ except (OSError, urllib.error.URLError):+ if process.poll() is not None or time.monotonic() > deadline:+ raise RuntimeError((root / "runtime.log").read_text(errors="replace"))+ time.sleep(.25)+ with opener.open(base + "/", timeout=5) as response:+ assert 'action="/setup"' in response.read().decode("utf-8")+ form = {"media_dir": str(media), "port": str(port)}+ request = urllib.request.Request(base + "/setup",+ data=urllib.parse.urlencode(form).encode(), headers={"Origin": base})+ with opener.open(request, timeout=60) as response:+ assert "设置完成" in response.read().decode("utf-8")+ assert (data / "database" / "ledger.db").is_file()+ process.terminate()+ process.wait(timeout=15)+ process = subprocess.Popen(command, cwd=root, env=environment, stdout=log, stderr=log)+ deadline = time.monotonic() + 40+ while True:+ try:+ with opener.open(base + "/healthz", timeout=1) as response:+ health = json.load(response)+ break+ except (OSError, urllib.error.URLError):+ if process.poll() is not None or time.monotonic() > deadline:+ raise RuntimeError((root / "runtime.log").read_text(errors="replace"))+ time.sleep(.25)+ for path in ("/", "/app.css", "/app.js", "/dist/peach-ui.js", "/api/items"):+ with opener.open(base + path, timeout=10) as response:+ assert response.status == 200, path+ with opener.open(base + "/configuration", timeout=5) as response:+ page = response.read().decode("utf-8")+ revision = re.search(r'name="revision" value="([a-f0-9]+)"', page).group(1)+ request = urllib.request.Request(base + "/configuration",+ data=urllib.parse.urlencode({**form, "revision": revision}).encode(), headers={"Origin": base})+ with opener.open(request, timeout=10) as response:+ assert "配置已保存" in response.read().decode("utf-8")+ assert (data / "config.previous.toml").is_file()+ assert (data / "state" / "configuration-reload.request").is_file()+ print(json.dumps({"ok": True, "version": health.get("version"),+ "checks": ["oobe", "migrations", "serve", "automatic-login", "pages", "island", "items", "configuration"]}))+ finally:+ process.terminate()+ process.wait(timeout=15)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/standalone.txt b/scripts/standalone.txtnew file mode 100644index 000000000..97d8b5a6d--- /dev/null+++ b/scripts/standalone.txt@@ -0,0 +1 @@+Peach standalone desktop distributiondiff --git a/scripts/vendor_web_dependencies.mjs b/scripts/vendor_web_dependencies.mjsindex 9ea997fe4..434a04a5b 100644--- a/scripts/vendor_web_dependencies.mjs+++ b/scripts/vendor_web_dependencies.mjs@@ -61,6 +61,7 @@ copyPackageFiles({});const lucideIcons = new Map([+ ["building", "building"], ["briefcase", "briefcase"],["home", "home"], ["sliders-horizontal", "sliders-horizontal"], ["search", "search"],["layout-grid", "layout-grid"], ["square-check-big", "square-check-big"],["refresh-cw", "refresh-cw"], ["user-round", "user-round"], ["tags", "tags"],diff --git a/src/peach/__init__.py b/src/peach/__init__.pyindex d14798995..8ab6a5fde 100644--- a/src/peach/__init__.py+++ b/src/peach/__init__.py@@ -1,3 +1,3 @@"""Peach application package."""-__version__ = "0.7.13"+__version__ = "0.7.14"diff --git a/src/peach/api.py b/src/peach/api.pyindex fac0eca2b..3a47e6cc3 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -31,7 +31,7 @@ from fastapi.staticfiles import StaticFilesfrom starlette.middleware.gzip import DEFAULT_EXCLUDED_CONTENT_TYPES, GZipMiddlewarefrom . import __version__, web_contract, web_follow-from . import routes_api, routes_auth, routes_media, routes_pages+from . import routes_api, routes_auth, routes_configuration, routes_media, routes_pagesfrom .config import PeachSettingsfrom .ffmpeg import FFmpegResolverfrom .follow_scheduler import FollowUpdateScheduler@@ -292,6 +292,7 @@ def create_app(# `/api/stream-cancel` 两条具名 API,所以它也要排在 `routes_api` 之前。app.include_router(routes_auth.router)app.include_router(routes_pages.router)+ app.include_router(routes_configuration.router)app.include_router(routes_media.router)app.include_router(routes_api.router)return appdiff --git a/src/peach/distribution.py b/src/peach/distribution.pynew file mode 100644index 000000000..3055421d1--- /dev/null+++ b/src/peach/distribution.py@@ -0,0 +1,18 @@+"""独立测试包的资源标记与用户数据目录。"""+from __future__ import annotations++import sys+from pathlib import Path+++def standalone() -> bool:+ return bool(getattr(sys, "frozen", False) and+ (Path(getattr(sys, "_MEIPASS", "")) / "standalone.txt").is_file())+++def user_data_root(environ: dict[str, str]) -> Path:+ if sys.platform == "win32":+ base = Path(environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")+ else:+ base = Path.home() / "Library" / "Application Support"+ return base / "Peach" / "peach-data"diff --git a/src/peach/onboarding.py b/src/peach/onboarding.pyindex 100b6e7ca..5e38fbb7d 100644--- a/src/peach/onboarding.py+++ b/src/peach/onboarding.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport osimport re+import socketfrom collections.abc import Callablefrom dataclasses import dataclass, replacefrom pathlib import Path@@ -47,6 +48,7 @@ MIGRATIONS_DIR = settings_file.PROJECT_ROOT / "migrations"#: 「现在扫描」的一次性标记,落在 `<数据根>/state/`。设置页写它、托盘消费它:#: 设置页所在的引导服务在设置完成的那一刻就会被托盘停掉,扫描不能跑在它的进程里。SCAN_REQUEST_NAME = "first-scan.request"+RELOAD_NAME = "configuration-reload.request"#: 监听范围的两个选项:(提交值, 说明)。题目文本和设置页的下拉都由它生成,#: 所以两处永远是同一批选项,改一个不会漏掉另一个。@@ -127,6 +129,16 @@ def validate_port(raw: str) -> int:return int(text)+def check_available_port(port: int, current: int) -> None:+ if port == current:+ return+ try:+ with socket.socket() as candidate:+ candidate.bind(("127.0.0.1", port))+ except OSError as exc:+ raise ValueError("这个端口已被占用,请换一个端口") from exc++def validate_mdns_name(raw: str) -> str:text = raw.strip()if not _DNS_LABEL.match(text):diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.pynew file mode 100644index 000000000..7daf62039--- /dev/null+++ b/src/peach/routes_configuration.py@@ -0,0 +1,126 @@+"""本机配置表单:读取、校验、原子保存与托盘应用请求。"""+from __future__ import annotations++from dataclasses import replace+import hashlib+from html import escape+import os+import shutil+import threading+from urllib.parse import parse_qs++from fastapi import APIRouter, Depends, HTTPException, Request+from fastapi.responses import HTMLResponse++from . import __version__, distribution, onboarding, settings_file+from .routes_auth import require_page_auth+from .routes_pages import _document, _field_html+from .ffmpeg import FFmpegResolver++router = APIRouter()+_SAVE_LOCK = threading.Lock()+RELOAD_NAME = onboarding.RELOAD_NAME+++def revision(config) -> str:+ return hashlib.sha256(config.path.read_bytes()).hexdigest()+++def page(config, *, values=None, errors=None, saved=False) -> str:+ values, errors = values or {}, errors or {}+ media = config.mounts.get("local") or config.locations.get("local", "")+ body = '<a href="/">返回馆藏</a><h1>配置 Peach</h1>'+ if saved:+ url = f"http://127.0.0.1:{config.server.port}/"+ body += ('<p role="status">配置已保存,正在重新启动服务。</p>'+ f'<p><a href="{url}">进入馆藏</a></p>'+ f'<meta http-equiv="refresh" content="8;url={url}">')+ else:+ body += '<p>管理这台电脑的媒体文件夹和访问端口。</p>'+ if distribution.standalone() and not saved:+ body += '<form method="post" action="/configuration">'+ body += f'<input type="hidden" name="revision" value="{revision(config)}">'+ for question in onboarding.questions(config, windows=os.name == "nt"):+ if question.key not in {"media_dir", "port"}:+ continue+ default = media if question.key == "media_dir" else str(config.server.port)+ body += _field_html(question, values.get(question.key, default),+ errors.get(question.key, ""), "")+ body += ('<label class="check"><input type="checkbox" name="scan_now" value="y">'+ '保存后扫描媒体文件夹</label><button type="submit">保存配置</button></form>')+ elif not distribution.standalone():+ body += '<p>此部署通过配置文件管理服务,请在本机编辑下方文件。</p>'+ available = FFmpegResolver(config.directory("tools") / "ffmpeg").ffmpeg() is not None+ body += ('<h2>运行信息</h2><dl>'+ f'<dt>版本</dt><dd>{escape(__version__)}</dd>'+ f'<dt>数据目录</dt><dd>{escape(str(config.data_root))}</dd>'+ f'<dt>配置文件</dt><dd>{escape(str(config.path))}</dd>'+ f'<dt>日志目录</dt><dd>{escape(str(config.directory("logs")))}</dd>'+ f'<dt>FFmpeg</dt><dd>{"可用" if available else "未安装;MP4 可直接播放,转码和缩略图需要安装 FFmpeg。"}</dd></dl>')+ return _document("Peach · 配置", body)+++def local_only(request):+ if not request.client or request.client.host not in {"127.0.0.1", "::1"}:+ raise HTTPException(403, "请在运行 Peach 的电脑上打开配置")+ if distribution.standalone() and request.url.hostname not in {"127.0.0.1", "localhost", "::1"}:+ raise HTTPException(403, "请使用本机地址打开配置")++[email protected]("/configuration", response_class=HTMLResponse)+def configuration(request: Request, _args=Depends(require_page_auth)):+ local_only(request)+ config = settings_file.load_config()+ if not config.present:+ raise HTTPException(409, "请先完成首次设置")+ return HTMLResponse(page(config), headers={"Cache-Control": "no-store"})++[email protected]("/configuration", response_class=HTMLResponse)+async def save_configuration(request: Request, _args=Depends(require_page_auth)):+ local_only(request)+ if not distribution.standalone():+ raise HTTPException(409, "此部署通过配置文件管理服务")+ origin = request.headers.get("origin")+ if origin and origin.rstrip("/") != str(request.base_url).rstrip("/"):+ raise HTTPException(403, "请从 Peach 配置页提交")+ form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)+ values = {key: value[0] for key, value in form.items()}+ with _SAVE_LOCK:+ config = settings_file.load_config()+ if values.get("revision") != revision(config):+ raise HTTPException(409, "配置已变更,请刷新后再保存")+ errors, validated = {}, {}+ validators = {"media_dir": onboarding.media_dir_validator(windows=os.name == "nt"),+ "port": onboarding.validate_port}+ for key, validator in validators.items():+ try:+ validated[key] = validator(values.get(key, ""))+ except ValueError as exc:+ errors[key] = str(exc)+ if errors:+ return HTMLResponse(page(config, values=values, errors=errors), status_code=400)+ try:+ onboarding.check_available_port(validated["port"], config.server.port)+ except ValueError as exc:+ return HTMLResponse(page(config, values=values, errors={"port": str(exc)}), status_code=400)+ locations, mounts = dict(config.locations), dict(config.mounts)+ if os.name == "nt":+ locations["local"] = str(validated["media_dir"])+ else:+ locations["local"] = onboarding.POSIX_LOCAL_DECLARED_ROOT+ mounts["local"] = str(validated["media_dir"])+ prepared = replace(config, locations=locations, mounts=mounts,+ server=replace(config.server, port=validated["port"]))+ temporary = config.path.with_suffix(".pending.toml")+ try:+ shutil.copy2(config.path, config.path.with_suffix(".previous.toml"))+ temporary.write_text(settings_file.render(prepared), encoding="utf-8")+ os.replace(temporary, config.path)+ if "scan_now" in form:+ onboarding.request_first_scan(prepared)+ config.directory("state").mkdir(parents=True, exist_ok=True)+ (config.directory("state") / RELOAD_NAME).write_text("reload", encoding="utf-8")+ except OSError as exc:+ raise HTTPException(500, f"配置保存失败:{exc}") from exc+ return HTMLResponse(page(prepared, saved=True), headers={"Cache-Control": "no-store"})diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.pyindex ee7838402..c0e92f85a 100644--- a/src/peach/routes_pages.py+++ b/src/peach/routes_pages.py@@ -32,7 +32,7 @@ from fastapi.responses import (Response,)-from . import onboarding, settings_file+from . import auth, distribution, onboarding, settings_filefrom .config import PROJECT_ROOTfrom .routes_auth import require_asset_auth, require_page_auth, set_auth_cookiefrom .web_state import FAVICON@@ -46,29 +46,34 @@ _LOOPBACK = frozenset({"127.0.0.1", "::1", "localhost"})#: `/api/items`,而未配置的机器还没有数据库,页面只会是一屏红色报错。这一页因此#: 落在 SPA 外壳之外,不是一个 `frontend/` island(ADR-0022、docs/FRONTEND.md)。_SETUP_STYLE = """<style>-body{margin:0;padding:3rem 1.5rem;background:#141216;color:#f2eef5;-font:16px/1.7 system-ui,-apple-system,"Segoe UI","Microsoft YaHei",sans-serif}-main{max-width:36rem;margin:0 auto}h1{font-size:1.5rem;margin:0 0 1rem}-code{background:#231f27;border-radius:.3rem;padding:.15rem .4rem}-dt{color:#b9aec4;font-size:.9rem}dd{margin:0 0 .6rem;word-break:break-all}-label{display:block;margin:1.4rem 0 .35rem;color:#e7dff0}-input[type=text],input[type=number],select{width:100%;box-sizing:border-box;height:2.6rem;-padding:0 .7rem;border:1px solid #3a3340;border-radius:.5rem;background:#0f0d12;-color:#f2eef5;font:inherit}-input:focus,select:focus{outline:none;border-color:#ff8b70}-.note{margin:.35rem 0 0;color:#b9aec4;font-size:.88rem}-.bad{margin:.35rem 0 0;color:#ff9a9a;font-size:.9rem}-.check{display:flex;align-items:center;gap:.6rem;margin:1.6rem 0 0;color:#e7dff0}-.check input{width:1.1rem;height:1.1rem;margin:0}-button{margin-top:1.8rem;width:100%;height:2.8rem;border:0;border-radius:.6rem;-cursor:pointer;background:linear-gradient(135deg,#ff9a76,#f2557b);color:#130609;-font:700 15px system-ui,sans-serif}-button:hover{filter:brightness(1.06)}+*{box-sizing:border-box}+body{margin:0;padding:48px 24px;background:var(--ground);color:var(--ink);+font:16px/1.6 system-ui,-apple-system,"Segoe UI","Microsoft YaHei",sans-serif}+main{max-width:560px;margin:0 auto}h1{font-size:28px;font-weight:600;margin:24px 0 8px}+h2{font-size:18px;font-weight:600;margin-top:32px;padding-top:24px;border-top:1px solid var(--line)}+p{color:var(--ink-2)}a{color:var(--tungsten);text-underline-offset:3px}+code{background:var(--surface);border-radius:var(--badge-radius);padding:2px 6px}+dt{color:var(--muted);font-size:14px}dd{margin:0 0 12px;overflow-wrap:anywhere}+label{display:block;margin:24px 0 8px;color:var(--ink)}+input[type=text],input[type=number],select{width:100%;height:44px;+padding:0 12px;border:1px solid var(--line);border-radius:var(--control-radius);+background:var(--ground);color:var(--ink);font:inherit}+:focus-visible{outline:2px solid var(--tungsten);outline-offset:3px}+.note{margin:8px 0 0;color:var(--ink-2);font-size:14px}+details{margin-top:24px}summary{cursor:pointer;min-height:44px;display:list-item}+.bad{margin:8px 0 0;color:var(--drop);font-size:14px}+.check{display:flex;align-items:center;gap:12px;min-height:44px;margin:24px 0 0}+.check input{width:18px;height:18px;margin:0}+button{margin-top:24px;width:100%;min-height:44px;border:1px solid var(--ink);+border-radius:var(--control-radius);cursor:pointer;background:var(--ink);color:var(--ground);+font:500 16px system-ui,sans-serif}+button:hover{background:color-mix(in srgb,var(--ink) 88%,var(--ground));color:var(--ground)}+@media(max-width:440px){body{padding:24px 20px}h1{font-size:24px}}</style>"""_SETUP_HEAD = ('<!doctype html>\n<html lang="zh-CN"><head><meta charset="utf-8">''<meta name="viewport" content="width=device-width,initial-scale=1">'- '<meta name="color-scheme" content="dark">')+ '<meta name="color-scheme" content="light">')#: 键 -> 输入控件类型。题目、默认值与顺序全部来自 `onboarding.questions()`,#: 这里只决定同一道题在浏览器里长什么样,不另抄一份字段清单。@@ -76,7 +81,9 @@ _SETUP_WIDGETS = {"host": "select", "port": "number"}def _document(title: str, body: str) -> str:- return (f"{_SETUP_HEAD}<title>{title}</title>{_SETUP_STYLE}"+ base = (PROJECT_ROOT / "web" / "css" / "01-base.css").read_text(encoding="utf-8")+ tokens = re.search(r":root\s*\{[^}]+\}", base).group(0)+ return (f"{_SETUP_HEAD}<title>{title}</title><style>{tokens}</style>{_SETUP_STYLE}"f"</head><body><main>{body}</main></body></html>\n")@@ -84,7 +91,10 @@ def _field_html(question, value: str, error: str, note: str,) -> str:key = escape(question.key, quote=True)- label = f'<label for="f-{key}">{escape(question.prompt)}</label>'+ prompt = question.prompt+ if distribution.standalone():+ prompt = {"media_dir": "媒体文件夹", "port": "本机访问端口"}.get(question.key, prompt)+ label = f'<label for="f-{key}">{escape(prompt)}</label>'if _SETUP_WIDGETS.get(question.key) == "select":options = "".join(f'<option value="{escape(choice, quote=True)}"'@@ -94,7 +104,8 @@ def _field_html(control = f'<select id="f-{key}" name="{key}">{options}</select>'else:kind = _SETUP_WIDGETS.get(question.key, "text")- control = (f'<input id="f-{key}" name="{key}" type="{kind}" required '+ control = (f'<input id="f-{key}" name="{key}" type="{kind}" required autocomplete="off" '+ f'aria-invalid="{"true" if error else "false"}" 'f'value="{escape(value, quote=True)}">')tail = f'<p class="note">{escape(note)}</p>' if note else ""tail += f'<p class="bad" role="alert">{escape(error)}</p>' if error else ""@@ -114,19 +125,31 @@ def setup_page(errors = errors or {}asked = onboarding.questions(config, windows=windows)fields = []+ if errors.get("data_root"):+ fields.append(f'<p class="bad" role="alert">{escape(errors["data_root"])}</p>')for question in asked:value = values.get(question.key, question.default)+ if distribution.standalone() and question.key in {"data_root", "host", "mdns_name"}:+ value = {"data_root": str(config.data_root), "host": "1",+ "mdns_name": config.server.mdns_name}[question.key]+ fields.append(f'<input type="hidden" name="{question.key}" value="{escape(value, quote=True)}">')+ continuenote = ""if question.key == "media_dir" and not windows:note = onboarding.mounts_explanation(value or "你在上面填的目录")- fields.append(_field_html(question, value, errors.get(question.key, ""), note))+ field = _field_html(question, value, errors.get(question.key, ""), note)+ if distribution.standalone() and question.key == "port":+ opened = " open" if errors.get("port") else ""+ field = f'<details{opened}><summary>高级设置</summary>{field}</details>'+ fields.append(field)media_value = values.get("media_dir") or next((q.default for q in asked if q.key == "media_dir"), "") or "这个目录"scan_label = onboarding.SCAN_PROMPT.format(target=media_value)+ if distribution.standalone():+ scan_label = "完成设置后扫描媒体文件夹"body = ("<h1>欢迎使用 Peach</h1>"- "<p>这台机器还没有数据根和设置文件。填完下面几项就能开始用;"- "每一项都已经填好默认值,不确定就直接提交。</p>"+ "<p>选择一个媒体文件夹,开始整理你的馆藏。</p>"'<form method="post" action="/setup">'+ "".join(fields)+ f'<label class="check"><input type="checkbox" name="scan_now" value="y"'@@ -142,6 +165,13 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool) -> str:"""成功页:接下来会自动发生什么,以及口令在哪。口令本身不显示在页面上。"""tree = applied.treeconfig = applied.config+ if distribution.standalone():+ destination = escape(_normal_url(config), quote=True)+ scan = "首次扫描已排队。" if scan_requested else "你可以稍后在配置界面开始扫描。"+ return _document("Peach · 设置完成",+ '<h1>设置完成</h1><p>正在启动你的馆藏。' + scan + '</p>'+ f'<p><a href="{destination}">进入 Peach</a></p>'+ f'<meta http-equiv="refresh" content="8;url={destination}">')ledger = (f"账本已存在,没有动它:{tree.database}" if tree.ledger_existedelse f"账本:{tree.database}(已应用 {tree.migrations} 个迁移)")ca = (f"本机 CA:{tree.ca_cert}" if tree.ca_cert is not None@@ -277,6 +307,11 @@ async def setup_submit(request: Request):host = request.client.host if request.client else ""if host not in _LOOPBACK:raise HTTPException(status_code=403, detail="setup is loopback-only")+ if distribution.standalone() and request.url.hostname not in _LOOPBACK:+ raise HTTPException(status_code=403, detail="请使用本机地址打开设置")+ origin = request.headers.get("origin")+ if origin and origin.rstrip("/") != str(request.base_url).rstrip("/"):+ raise HTTPException(status_code=403, detail="请从 Peach 设置页提交")windows = os.name == "nt"form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)@@ -284,7 +319,15 @@ async def setup_submit(request: Request):scan_now = "scan_now" in formconfig = settings_file.active()+ if distribution.standalone():+ submitted.update(data_root=str(config.data_root), host="1",+ mdns_name=config.server.mdns_name)answers, errors = _read_answers(config, submitted, windows=windows)+ if distribution.standalone() and answers is not None:+ try:+ onboarding.check_available_port(answers.port, request.url.port or 80)+ except ValueError as exc:+ errors["port"] = str(exc)if errors:return HTMLResponse(setup_page(config, windows=windows, values=submitted, errors=errors,@@ -296,11 +339,19 @@ async def setup_submit(request: Request):resolved, _broken = onboarding.resolve_config(answers.data_root)if resolved.path.exists():raise HTTPException(status_code=409, detail="settings file already exists")- applied = onboarding.apply(resolved, answers, windows=windows)+ try:+ applied = onboarding.apply(resolved, answers, windows=windows)+ except (OSError, RuntimeError) as exc:+ return HTMLResponse(setup_page(config, windows=windows, values=submitted,+ errors={"data_root": str(exc)}, scan_now=scan_now), status_code=400)if scan_now:onboarding.request_first_scan(applied.config)- return HTMLResponse(- setup_done_page(applied, windows=windows, scan_requested=scan_now))+ response = HTMLResponse(setup_done_page(applied, windows=windows, scan_requested=scan_now))+ if distribution.standalone():+ response.set_cookie("tok", auth.read_token(applied.config.directory("secrets")),+ httponly=True, samesite="strict", max_age=31536000)+ response.headers["Cache-Control"] = "no-store"+ return responsedef _read_answers(diff --git a/src/peach/settings_file.py b/src/peach/settings_file.pyindex 0a8009f09..3047e4a2a 100644--- a/src/peach/settings_file.py+++ b/src/peach/settings_file.py@@ -28,6 +28,8 @@ from dataclasses import dataclass, field, replacefrom functools import lru_cachefrom pathlib import Path+from . import distribution+#: 设置文件名。位置固定为数据根下,不做多候选路径搜索。SETTINGS_FILENAME = "config.toml"DATA_ROOT_ENV = "PEACH_DATA_ROOT"@@ -90,6 +92,9 @@ def discover_data_root(explicit = (environ.get(DATA_ROOT_ENV) or "").strip()if explicit:return Path(explicit), True+ if distribution.standalone():+ candidate = distribution.user_data_root(environ)+ return candidate, (candidate / SETTINGS_FILENAME).is_file()for parent in project_root.parents[:_SEARCH_DEPTH]:candidate = parent / DATA_ROOT_DIRNAMEif candidate.is_dir():diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 1329a78cb..ec3b19fa3 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -21,6 +21,7 @@ from PIL import Imagefrom . import onboarding, settings_filefrom .appid import MACOS_LAUNCH_AGENT_LABELfrom .certs import ensure_certificate+from .distribution import standalonefrom .config import (DATABASE_PATH, LOG_DIR, MDNS_HOSTNAME, PROJECT_ROOT, REPLICATION_ENABLED,SECRETS_DIR, SHARED_DATABASE_PATH, SHARED_SMB_HOST, SHARED_SMB_SHARE,@@ -53,7 +54,7 @@ def ledger_menu_items(make_item, sync_ledger, take_ownership) -> list:然后回一句「盘不可达」——那不是状态,是这台机器根本不做复制(ADR-0023 第 3 阶段)。标签在两个平台上共用这一处定义,`make_item` 负责套上各自的菜单项类型。"""- if not REPLICATION_ENABLED:+ if not REPLICATION_ENABLED or standalone():return []return [make_item("同步 Ledger", sync_ledger),@@ -451,6 +452,9 @@ _EXECUTABLE = "peach.exe" if os.name == "nt" else "peach"def _peach_executable() -> Path:+ from .distribution import standalone+ if standalone():+ return Path(sys.executable).resolve()if getattr(sys, "frozen", False):# 打包出来的托盘不是可移动的独立发行版:它仍然把服务进程的所有权交给项目 venv,# 因为 one-file bootloader 在本 Python 构建上再拉起一个 one-file 进程并不安全。@@ -585,6 +589,8 @@ def needs_setup(config) -> bool:认为这台机器已经配置好,然后照旧倒在缺 TLS 材料上。反过来,还没生成过`config.toml` 的老部署账本是在的,不能被拖进首次设置。"""+ if standalone():+ return not config.presentif config.present:return Falsereturn not (config.directory("database") / "ledger.db").is_file()@@ -629,9 +635,26 @@ def normal_url(config) -> str:"""正常服务的固定地址。macOS 上 80/443 由 pf 转到高位端口(scripts/setup_macos_port80.sh)。"""+ from .distribution import standalone+ if standalone():+ return setup_url(config)return f"https://{normal_hostname(config)}/"+def configured_service_specs(config) -> tuple[ServiceSpec, ...]:+ """独立测试包按设置文件启动本机服务;源码入口沿用其生命周期。"""+ from .distribution import standalone+ if not standalone():+ return build_service_specs(tls_dir=config.directory("secrets") / "tls",+ mdns_hostname=normal_hostname(config))+ if config.server.host != "127.0.0.1":+ raise ValueError("独立测试包仅支持本机访问,请在配置中选择仅本机")+ return (ServiceSpec("http", setup_url(config) + "healthz",+ (str(_peach_executable()), "serve", "--host", "127.0.0.1",+ "--port", str(config.server.port), "--no-mdns", "--no-ledger-sync"),+ True),)++class SetupGate:"""首次设置期间的服务切换。Windows 托盘与 macOS 菜单栏共用这一层。@@ -686,16 +709,15 @@ class SetupGate:还没齐就原地等下一轮,而不是拿一组缺文件的规格去启动。mDNS 名同理由这里传进规格:明文口的跳转目标必须是人刚填的那个名字。"""- if not self._waiting:+ from .distribution import standalone+ reload_path = self.config.directory("state") / onboarding.RELOAD_NAME+ if not self._waiting and not (standalone() and reload_path.is_file()):return Falseconfig = self._load()if needs_setup(config):return Falsetry:- specs = build_service_specs(- tls_dir=config.directory("secrets") / "tls",- mdns_hostname=normal_hostname(config),- )+ specs = configured_service_specs(config)except FileNotFoundError:return False # CA 还没生成完(或没有 openssl),下一轮再看self._waiting = False@@ -705,6 +727,7 @@ class SetupGate:extra_env={"PEACH_DATA_ROOT": str(config.data_root)},)self.manager.start_missing()+ reload_path.unlink(missing_ok=True)self.notify(f"首次设置完成,正在启动服务:{normal_url(config)}", "Peach")self.start_first_scan(config)return True@@ -821,9 +844,11 @@ class PeachTray:"Peach · 蜜桃",pystray.Menu(pystray.MenuItem(lambda _item: self.gate.open_label(), self.open, default=True),+ pystray.MenuItem("配置 Peach", lambda *_: webbrowser.open(self.gate.open_url() + "configuration")),pystray.MenuItem(lambda _item: f"状态:{self.gate.status_line()}", None, enabled=False),pystray.Menu.SEPARATOR,- pystray.MenuItem("同步开发进度", self.sync_source),+ pystray.MenuItem("同步开发进度", self.sync_source,+ visible=lambda _: not standalone()),*ledger_menu_items(pystray.MenuItem, self.sync_ledger, self.take_ownership),pystray.MenuItem("重启服务", self.restart),@@ -959,7 +984,7 @@ class PeachTray:(icon or self.icon).stop()def _monitor(self) -> None:- while not self._stop_event.wait(10):+ while not self._stop_event.wait(2 if standalone() else 10):# 先看首次设置有没有完成:切换会换掉 `manager.specs`,采样必须落在换完之后。self.gate.poll()for spec in self.manager.specs:@@ -1259,7 +1284,7 @@ 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 build_service_specs()+ 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":diff --git a/src/peach/versioning.py b/src/peach/versioning.pyindex e0cbfc399..beee0127e 100644--- a/src/peach/versioning.py+++ b/src/peach/versioning.py@@ -98,6 +98,9 @@ class VersionManager:def inspect(self) -> VersionSnapshot:package_version = __version__+ from .distribution import standalone+ if standalone():+ return VersionSnapshot(package_version, "测试包", "release", False, False, None)commit = self._text("rev-parse", "--short=8", "HEAD") or "unknown"branch = self._text("branch", "--show-current") or "detached"dirty = bool(self._text("status", "--porcelain"))@@ -111,6 +114,9 @@ class VersionManager:def check(self) -> UpdateResult:before = self.inspect()+ from .distribution import standalone+ if standalone():+ return UpdateResult("manual", "测试包请从 GitHub Releases 下载新版并完整解压替换程序目录;数据保存在用户目录。", before)if not before.remote_configured:return UpdateResult("unconfigured",diff --git a/src/peach/web_settings.py b/src/peach/web_settings.pyindex f0f2c7042..79ab71ae3 100644--- a/src/peach/web_settings.py+++ b/src/peach/web_settings.py@@ -22,7 +22,7 @@ DEFAULT_PROFILE_ID = "local-default"#: 默认就在侧栏里的入口,顺序即默认顺序。DEFAULT_SIDEBAR_ORDER = (- "", "performers", "tags", "jav", "flagged", "playlists", "follow", "immerse", "manage",+ "", "performers", "studios", "tags", "jav", "flagged", "playlists", "follow", "immerse", "manage",)#: 可以加进侧栏、但默认不在的入口。OPTIONAL_SIDEBAR_KEYS = (diff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex f0199f3b5..9df4629b5 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -432,5 +432,75 @@ class SetupPageTests(_Case):self.assertEqual(self._loaded().server.port, 8900, "第二次提交不得改掉已写好的设置")+class StandaloneConfigurationTests(_Case):+ def setUp(self):+ super().setUp()+ from dataclasses import replace+ self.config = replace(self.config, locations={"local": str(self.media)},+ mounts={}, server=settings_file.ServerSettings(port=9123))+ settings_file.write(self.config)+ self.config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.config.data_root)})+ self.addCleanup(mock.patch.stopall)+ mock.patch("peach.distribution.standalone", return_value=True).start()+ mock.patch("peach.settings_file.load_config", side_effect=lambda: settings_file._merge(+ self.config.data_root, self.config.path, True, True,+ settings_file._read_document(self.config.path), {})).start()++ def client(self, *, token="test-token", address="127.0.0.1"):+ from fastapi.testclient import TestClient+ from peach.api import create_app+ from peach.config import PeachSettings+ return TestClient(create_app(PeachSettings(configured=True, token=token,+ db_path=self.config.data_root / "database" / "ledger.db")),+ client=(address, 12345), base_url="http://localhost")++ def test_authenticated_configuration_preserves_values_and_requests_reload(self):+ from peach.routes_configuration import RELOAD_NAME, revision+ with self.client() as client:+ headers = {"X-Token": "test-token"}+ page = client.get("/configuration", headers=headers)+ self.assertEqual(page.status_code, 200)+ self.assertIn("媒体", page.text)+ self.config.directory("state").mkdir(parents=True, exist_ok=True)+ response = client.post("/configuration", headers=headers, data={+ "revision": revision(self.config), "media_dir": str(self.media), "port": "9124"})+ self.assertEqual(response.status_code, 200, response.text)+ self.assertEqual(settings_file.load_config().server.port, 9124)+ self.assertTrue(self.config.path.with_suffix(".previous.toml").is_file())+ self.assertTrue((self.config.directory("state") / RELOAD_NAME).is_file())+ self.assertFalse((self.config.directory("database") / "ledger.db").exists())++ def test_settings_reject_unauthenticated_remote_cross_origin_and_stale_forms(self):+ from peach.routes_configuration import revision+ data = {"revision": revision(self.config), "media_dir": str(self.media), "port": "9124"}+ before = self.config.path.read_bytes()+ with self.client() as client:+ self.assertEqual(client.get("/configuration", follow_redirects=False).status_code, 303)+ response = client.post("/configuration", headers={"X-Token": "test-token", "Origin": "https://example.org"}, data=data)+ self.assertEqual(response.status_code, 403)+ response = client.post("/configuration", headers={"X-Token": "test-token"}, data={**data, "revision": "stale"})+ self.assertEqual(response.status_code, 409)+ with self.client(address="192.0.2.1") as client:+ self.assertEqual(client.get("/configuration", headers={"X-Token": "test-token"}).status_code, 403)+ self.assertEqual(before, self.config.path.read_bytes())++ def test_standalone_tray_uses_its_own_binary_and_configured_loopback_port(self):+ import sys+ from peach.tray import _peach_executable, configured_service_specs, normal_url+ self.assertEqual(_peach_executable(), Path(sys.executable).resolve())+ spec, = configured_service_specs(self.config)+ self.assertEqual(spec.health_url, "http://127.0.0.1:9123/healthz")+ self.assertIn("9123", spec.command)+ self.assertEqual(normal_url(self.config), "http://127.0.0.1:9123/")++ def test_standalone_version_inspection_does_not_execute_git(self):+ from peach.versioning import VersionManager+ execute = mock.Mock(side_effect=AssertionError("Git must not run"))+ manager = VersionManager(execute=execute)+ self.assertEqual(manager.inspect().branch, "测试包")+ self.assertEqual(manager.check().state, "manual")+ execute.assert_not_called()++if __name__ == "__main__":unittest.main()diff --git a/tests/test_tray.py b/tests/test_tray.pyindex 6b4a51d60..7d154c465 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -642,7 +642,8 @@ class SourceSyncTests(unittest.TestCase):def test_windows_tray_lists_source_sync_next_to_ledger(self):source = inspect.getsource(PeachTray.__init__)- self.assertIn('MenuItem("同步开发进度", self.sync_source)', source)+ self.assertIn('MenuItem("同步开发进度", self.sync_source,', source)+ self.assertIn('visible=lambda _: not standalone()', source)self.assertLess(source.index("同步开发进度"), source.index("ledger_menu_items"))self.assertLess(source.index("ledger_menu_items"), source.index("重启服务"))diff --git a/web/index.html b/web/index.htmlindex adaa22157..f5415c830 100644--- a/web/index.html+++ b/web/index.html@@ -186,6 +186,7 @@<div class="settingscard"><div class="settingshead"><h2 id="settingsTitle">设置</h2><button id="settingsClose" aria-label="关闭设置"><svg viewBox="0 0 24 24"><use href="#i-x"/></svg></button></div><div class="settingsscroll">+ <section class="settinggroup"><h3>这台电脑</h3><a class="settingrow" href="/configuration">媒体文件夹与服务配置</a></section><section class="settinggroup"><h3>浏览</h3><label class="settingrow"><span><b>每批作品</b><small>首页每次加载的作品数量。</small></span><select id="batchSizeSetting"><option value="30">30 个</option><option value="60">60 个</option><option value="90">90 个</option></select></label><label class="settingrow"><span><b>默认排序</b><small>打开首页时使用的排序。</small></span><select id="defaultSortSetting"><option value="seed">随机</option><option value="rating">评分</option><option value="o">高潮计数</option><option value="plays">观看次数</option><option value="dur">时长</option><option value="size">体积</option><option value="new">入库时间</option><option value="played">观看时间</option></select></label>