Peach: Local-first video metadata scraper and media manager.
feat: 独立包在线更新进度与重启确认,修复凭据焦点裁切
longmeidao83ff9f0cdcfe
diff --git a/README.en.md b/README.en.mdindex 5c40db350..f90f9a222 100644--- a/README.en.md+++ b/README.en.md@@ -27,6 +27,8 @@ Peach is a single-user, local-first media system. Search, play and organize medi## Features+Management → Configuration → Check for updates shows the current version and the latest GitHub prerelease. Windows standalone packages download and prepare updates in the app with live progress. Choose Restart now or Later when ready; the app installs the update and restores the previous version if installation fails.+| Capability | What it does || --- | --- || Browse and search | Find videos and photo collections by work, performer, studio, creator, series or tag |diff --git a/README.md b/README.mdindex ff0eca6b3..9e030cd20 100644--- a/README.md+++ b/README.md@@ -38,6 +38,7 @@ CloudDrive · 115 与 CloudDrive · PikPak 按本机文件夹接入;先在 Clo托盘管理的服务可在本机通过「管理 → 配置」调整媒体来源;使用局域网域名打开也能进入。首启页和配置页检测缺失依赖时提供下载链接,挂载驱动提示按操作系统显示。在「配置」或「数据管理」点击「扫描并补全资料」,可统一扫描文件夹、识别已有 NFO 和本地海报,并采集缺失资料。首页在处理期间提供进度入口,配置页显示当前阶段。支持同名 NFO、单影片目录的 `movie.nfo` 和单集 NFO;资料保留原始出处,在「复核资料」确认后写入馆藏。已有本地标签会保留,目录中有多部影片时不会共用 `movie.nfo`。+「管理 → 配置 → 检查更新」显示当前版本与 GitHub 最新测试版。独立 Windows 包可直接下载并准备更新,进度实时显示;完成后选择「立即重启」或「稍后」,程序自动安装,失败时恢复旧版本。首次设置可选择进入浏览器历史记录导入指南;完成导入后指南隐藏,点击「跳过」会在当前浏览器记住选择,折叠仍保留指南。需要补充记录时使用「口味」页的读取或导入按钮。设置中的「SFW 模式」会模糊、降低饱和度并压暗图片和视频,停止悬停预览,文字保持可见。数据管理中的「网盘与本地数据库」仅在配置网盘后显示;空文件夹清理也支持本地磁盘。diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex a6dc27c1d..6560014a8 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -5,6 +5,9 @@## 界面、媒体与复核的既定判据- 统一处理、NFO 兼容见 `docs/REUSE.md`;[Banner](https://vercel.com/geist/banner) 2026-09-06 实测与 hash 见 `vercel-geist-library-banner.md`。+- 凭据输入框的焦点圈在控件外延伸 3px;`.fcollapse` 裁切高度动画,内层左右各留 4px。输入框与网格项同时允许收缩,否则手机上输入框的固有宽度会撑出卡片,再被外层裁切。验收需检查全部裁切祖先;桌面和 390px 视口都要覆盖。+- 独立包更新的暂存、重启确认和回滚入口是 `standalone_update.py`。用户数据目录必须在程序目录外;助手从自己的副本运行,避免自身 DLL 占用被替换目录。Windows 进程探测复用 `PidFileLock._running`。+页面密度、控件、提示与响应式的实现门槛见 `.claude/skills/peach-web-ui/SKILL.md`,这里只留代码看不出来的判据。diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 98bc78b44..31f237a75 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -189,7 +189,7 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt- `<数据根>/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/` 都不碰,手工构建的残留自己删。- 每个包都带构建身份:`build_windows.ps1` 在调用 PyInstaller 前把 `{commit, version, built_at}` 写进 `build/windows/build-info.json`,再用 `--add-data` 放到包根,本机托盘与独立测试包两种模式共用这一行。构建机没有 git 或源码不是检出时 `commit` 写 `null`,构建照常。`peach.buildinfo.frozen_build()` 只在 `sys.frozen` 时读它;文件缺失或格式坏一律返回 `None`,托盘照常启动,只是把自己当作身份未取得。-- 本机托盘自己发现「我比检出旧」并重建:判据是构建提交与检出的差,不是与 GitHub 的差——这台机器提交先落本地再推远端,「落后远端」永远不成立。`VersionManager.build_age()` 用 `rev-list --count <构建提交>..HEAD` 数出落后多少,版本菜单显示成 `master@<HEAD> · 托盘构建 <构建提交>,落后 N 个提交`;数不出来(身份未取得、提交不在本检出历史里)按陈旧处理,重建范围退化为 `src/peach/`。「同步开发进度」在 `ahead`/`current`/`error`/`unconfigured` 下改走本地重建,健康轮询另按 5 分钟一轮读本地 HEAD 自动触发,同一个 HEAD 只自动试一次,首次设置未完成时不触发。重建走的仍是既有流程:完整测试 → 暂存构建 → 打包迁移资源检查 → 备份 → 替换助手,任一步失败都只发通知,旧托盘和服务保持运行。失败表现是托盘停在旧版本、通知里写明卡在哪一步,日志见 `<数据根>/logs/windows-source-sync.log`。独立测试包与源码运行的托盘不进这条路径,前者提示下载新版完整替换程序目录,后者提示源码已是最新。+- 本机托盘自己发现「我比检出旧」并重建:判据是构建提交与检出的差,不是与 GitHub 的差——这台机器提交先落本地再推远端,「落后远端」永远不成立。`VersionManager.build_age()` 用 `rev-list --count <构建提交>..HEAD` 数出落后多少,版本菜单显示成 `master@<HEAD> · 托盘构建 <构建提交>,落后 N 个提交`;数不出来(身份未取得、提交不在本检出历史里)按陈旧处理,重建范围退化为 `src/peach/`。「同步开发进度」在 `ahead`/`current`/`error`/`unconfigured` 下改走本地重建,健康轮询另按 5 分钟一轮读本地 HEAD 自动触发,同一个 HEAD 只自动试一次,首次设置未完成时不触发。重建走的仍是既有流程:完整测试 → 暂存构建 → 打包迁移资源检查 → 备份 → 替换助手,任一步失败都只发通知,旧托盘和服务保持运行。失败表现是托盘停在旧版本、通知里写明卡在哪一步,日志见 `<数据根>/logs/windows-source-sync.log`。独立测试包与源码运行的托盘不进这条路径,独立测试包使用配置页的在线更新流程,源码入口提示源码已是最新。- 版本号在本地集成时就动:`scripts/agent_worktree.py integrate` 合并后按 `runtime_inputs_changed()` 判断这次改动有没有碰到 `src/peach/`、`web/`、`frontend/`、`migrations/`、`resources/`、`scripts/build_app_entry.py`、`scripts/build_windows.ps1`、`pyproject.toml`,碰到就推 `__version__` 并在 master 上单独提交 `chore(release): 版本 <新版本>`。推哪一位由 `bump_part_for()` 按这批提交定:主题以 `feat` 开头或带破坏性标记 `!`、或 `migrations/` 有新增文件就推 minor,其余推 patch;1.0 手工 `--bump major` 并另立 ADR(ADR-0012 修订)。`--bump {auto,patch,minor,major,none}` 默认 `auto`,显式档位是覆盖,没碰运行时输入时哪一档都不动;输出的 `version`/`bumped` 说明这次集成后的版本号。集成不打标签:发布点仍然是 `scripts/release_tag.py --apply` 推上去的 `vX.Y.Z`,它读的正是这里推进后的 `__version__`,并且遇到同名本地标签会直接拒绝——两处都造标签只会把唯一的发布入口挡在门外。- PyInstaller 的资源直接位于 `sys._MEIPASS`,没有源码树的 `src/` 层;打包后的 `migrate`、Web 与品牌资源必须从这里解析,不能对 `config.py` 固定取 `parents[2]`。- 创建 Win32 窗口前必须启用 Per-Monitor V2 DPI;正常动作不弹模态 MessageBox,更新检查在后台线程执行并用 pystray 原生非模态通知反馈。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 9118d6d38..5e1993988 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -1,6 +1,13 @@# 复用清单首页进度 Banner 与配置页复用 `LibraryProcessing`、`watchJob` 和 `/api/library-processing`,启动只提交一次,状态查询接续托盘首次处理。首页在完成后收起,失败提供设置跳转;配置页持续读取阶段与真实计数。Geist Banner 官方 DOM/CSS 已于 2026-09-06 取得,取证与 Peach 差异见 `docs/reference-snapshots/vercel-geist-library-banner.md`。+## 独立测试包在线更新++- 版本与资产信息复用 GitHub Releases REST API,测试通道包含预发布版本;查询复用项目 HTTPX 0.28.1,下载用其流式读取,ZIP 解压使用 Python 3.12+ 标准库,互斥复用 FileLock。没有新增依赖。+- 2026-09-06 真实只读 POC:GitHub 返回 v0.16.0、Windows ZIP 35,489,963 字节和 SHA-256 digest;仅发布记录中已上传的完整独立包可进入更新。+- Peach 维护安装策略与进度:下载校验后在程序同卷暂存,用户确认重启,复制出来的包内助手等待原托盘退出,再切换完整目录;失败保留或恢复旧目录。配置、数据库与媒体不作为更新包内容写入。+- 已核对 [Velopack Windows 文档](https://docs.velopack.io/packaging/operating-systems/windows) 和 [WinSparkle 文档](https://winsparkle.org/):前者要求其安装目录与包格式,后者要求 appcast 并使用原生更新界面;现有 GitHub 产物为 PyInstaller ZIP,进度在 Web 显示,因此复用现有托盘进程与目录替换协议,未引入额外安装框架。+- Web 复用 Fieldset、Progress、confirmModal;状态由 `standalone-update.json` 保存。下载按字节计量,解压按文件数计量,替换使用阶段进度;服务重启期间保留等待状态,恢复连接后核对版本。JAV 默认封面(官方封面/预览图)与默认大小(大图/小图)独立保存,复用 localStorage、共享 Switch 和既有 `/cover`、`/poster` 接口,不新增依赖。`frontend/src/jav-artwork.ts` 负责作品身份、偏好恢复与缺图回退;首页、接着看、实体作品、详情推荐、Mix 静止与翻图、播放队列共用封面选择。小图保留所选来源,设置换图保留播放和滚动位置。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 840cf01c7..e7d633407 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -6,6 +6,8 @@- uv:`TESTING.md`。+- 配置页提供 GitHub 测试版查询;独立 Windows 包支持应用内下载、校验、进度恢复和重启确认,替换失败可回滚。源码部署保留源码更新入口。凭据输入框保留完整焦点圈并适配窄屏。+## 运行态- 测试包本机可访问;mDNS 待办。diff --git a/frontend/src/islands/configuration.tsx b/frontend/src/islands/configuration.tsxindex ef4bfd5b0..755976efd 100644--- a/frontend/src/islands/configuration.tsx+++ b/frontend/src/islands/configuration.tsx@@ -14,6 +14,7 @@ import { fieldsetTitle, noteHtml, setActionBusy, selectFieldHtml, wireSelectFielimport { ApiError, apiGet, apiSend, errorMessage } from '../api';import { AccessSettings, type AccessState } from './access-settings';import { LibraryProcessing, type LibraryProcessingData } from './library-processing';+import { ReleaseUpdates, type ReleaseState, type UpdateJob } from './release-updates';export interface ConfigurationProps {/** 保存成功后的过去时回执(遗留层的 Toast)。 */@@ -29,6 +30,8 @@ export interface ConfigurationFact {export interface ConfigurationData {processing?: LibraryProcessingData;+ updates?: ReleaseState;+ update_job?: UpdateJob;access?: AccessState;editable: boolean;/** 不能编辑时给用户看的原因,可编辑时为空。 */@@ -348,6 +351,7 @@ export function Configuration({ receipt, data, error }: ConfigurationProps & Sta<section id="libraryProcessing" class="configfieldset" data-geist-fieldset aria-labelledby="cleanupScrapingTitle"><LibraryProcessing data={data.processing || { status: 'idle' }} error="" toast={receipt} monitor /></section>+ {data.updates ? <ReleaseUpdates initial={data.updates} initialJob={data.update_job} /> : null}<Facts facts={data.facts} /><MountStatus data={data} /></div>diff --git a/frontend/src/islands/release-updates.tsx b/frontend/src/islands/release-updates.tsxnew file mode 100644index 000000000..0a690ba78--- /dev/null+++ b/frontend/src/islands/release-updates.tsx@@ -0,0 +1,112 @@+import { useEffect, useRef, useState } from 'preact/hooks';+import { fieldsetTitle, setActionBusy, progressHtml, confirmModal } from '@peach/legacy/ui';+import { apiGet, apiSend, errorMessage } from '../api';++export interface ReleaseState {+ current_version: string;+ latest_version: string | null;+ channel: string;+ installation: string;+ state: string;+ message: string;+ release_url: string;+}++export interface UpdateJob {state: string; progress: number; message?: string; downloaded?: number; total?: number; version?: string}+const active = new Set(['downloading','verifying','extracting','preparing','restarting','installing']);++export function ReleaseUpdates({ initial, initialJob }: { initial: ReleaseState; initialJob?: UpdateJob | undefined }) {+ const [data, setData] = useState(initial);+ const [job, setJob] = useState<UpdateJob>(initialJob || {state:'idle',progress:0});+ const [error, setError] = useState('');+ const request = useRef<AbortController | null>(null);+ const mounted = useRef(true);+ const prompted = useRef(false);+ const downloadButton = useRef<HTMLButtonElement>(null);+ useEffect(() => { setActionBusy(downloadButton.current,active.has(job.state)); }, [job.state]);+ useEffect(() => () => { mounted.current = false; request.current?.abort(); }, []);+ const restart = async () => {+ const result = await apiSend<UpdateJob>('/api/configuration/update-restart', {});+ if (mounted.current) setJob(result);+ };+ useEffect(() => {+ if (job.state !== 'ready' || prompted.current) return;+ prompted.current = true;+ void confirmModal({title:'更新已准备好',body:`Peach ${job.version || ''} 将在重启后安装。`,confirmLabel:'立即重启',cancelLabel:'稍后',onConfirm:restart});+ }, [job.state]);+ useEffect(() => {+ if (!active.has(job.state)) return;+ const controller = new AbortController();+ let timer: ReturnType<typeof setTimeout>;+ let failures = 0;+ const poll = async () => {+ try {+ const result = await apiGet<UpdateJob>('/api/configuration/update-status',controller.signal);+ if (!controller.signal.aborted) {+ setJob(result); failures = 0;+ if (result.state === 'complete') setData(current => ({...current,current_version:result.version || current.current_version,state:'current',message:'已是最新测试版。'}));+ }+ } catch {+ if (++failures >= 120 && !controller.signal.aborted) setError('尚未连接到 Peach,请检查托盘后刷新页面。');+ }+ if (!controller.signal.aborted && failures < 120) timer = setTimeout(poll,1000);+ };+ timer = setTimeout(poll,1000);+ return () => { controller.abort(); clearTimeout(timer); };+ }, [job.state]);+ const download = async (button: HTMLButtonElement) => {+ if (request.current || active.has(job.state)) return;+ const controller = new AbortController(); request.current = controller;+ prompted.current = false; setError(''); setActionBusy(button,true);+ try {+ const result = await apiSend<UpdateJob>('/api/configuration/update',{},'POST',controller.signal);+ if (!controller.signal.aborted) setJob(result);+ } catch (cause) { if (!controller.signal.aborted) setError(errorMessage(cause)); }+ finally { request.current = null; setActionBusy(button,false); }+ };+ const check = async (button: HTMLButtonElement) => {+ if (request.current) return;+ const controller = new AbortController();+ request.current = controller;+ setActionBusy(button, true); setError('');+ try {+ const result = await apiGet<ReleaseState>('/api/configuration/updates', controller.signal);+ if (!controller.signal.aborted) setData(result);+ } catch (cause) {+ if (!controller.signal.aborted) {+ setData({ ...initial, state: 'error' });+ setError(errorMessage(cause));+ }+ } finally {+ request.current = null;+ setActionBusy(button, false);+ }+ };+ return <section class="configfieldset" data-geist-fieldset aria-labelledby="configUpdatesTitle">+ <div class="geist-fieldset-content">+ <div dangerouslySetInnerHTML={{ __html: fieldsetTitle('configUpdatesTitle', '检查更新') }} />+ <dl class="configfacts">+ <dt>当前版本</dt><dd>{data.current_version}</dd>+ <dt>安装方式</dt><dd>{data.installation}</dd>+ <dt>更新通道</dt><dd>{data.channel}</dd>+ <dt>最新版本</dt><dd>{data.latest_version || (data.state === 'unchecked' ? '尚未检查' : '未取得')}</dd>+ </dl>+ <p class={error || data.state === 'error' ? 'configbad' : 'confighelp'} role={error || data.state === 'error' ? 'alert' : 'status'}>+ {error || data.message}+ </p>+ {job.state !== 'idle' ? <div aria-live="polite">+ <p class={job.state === 'error' ? 'configbad' : 'confighelp'}>{job.message}</p>+ {job.state !== 'error' ? <>+ <div dangerouslySetInnerHTML={{__html:progressHtml(job.state === 'downloading' ? '下载进度' : '安装进度',job.state === 'downloading' ? job.downloaded || 0 : job.progress,job.state === 'downloading' ? job.total || 1 : 100)}} />+ <p class="confighelp">{job.state === 'downloading' && job.total ? `${((job.downloaded || 0)/1048576).toFixed(1)} / ${(job.total/1048576).toFixed(1)} MB` : `${job.progress}%`}</p>+ </> : null}+ </div> : null}+ </div>+ <div class="geist-fieldset-footer" data-geist-fieldset-footer>+ <a class="geist-button" href={data.release_url} target="_blank" rel="noreferrer">查看发布页</a>+ {job.state === 'ready' ? <button type="button" class="geist-button primary" onClick={() => { void confirmModal({title:'更新已准备好',body:`Peach ${job.version || ''} 将在重启后安装。`,confirmLabel:'立即重启',cancelLabel:'稍后',onConfirm:restart}); }}>重启安装</button> : null}+ {data.state === 'available' && data.installation === '独立测试包' && job.state !== 'ready' ? <button ref={downloadButton} type="button" class="geist-button primary" onClick={(event) => download(event.currentTarget)}>下载并安装</button> : null}+ <button type="button" class="geist-button" disabled={active.has(job.state)} onClick={(event) => check(event.currentTarget)}>检查更新</button>+ </div>+ </section>;+}diff --git a/frontend/src/legacy/ui.d.ts b/frontend/src/legacy/ui.d.tsindex 4411da08e..39019a727 100644--- a/frontend/src/legacy/ui.d.ts+++ b/frontend/src/legacy/ui.d.ts@@ -16,6 +16,7 @@ export declare function emptyStateHtml(export declare function fieldsetTitle(id: string, title: string): string;export declare function loadingDotsHtml(label?: string, options?: { className?: string }): string;export declare function progressHtml(label: string, value: number, max?: number): string;+export declare function confirmModal(options: {title: string; body: string; confirmLabel: string; cancelLabel?: string; onConfirm?: () => Promise<unknown>}): Promise<{confirmed: boolean; result?: unknown}>;export declare function selectFieldHtml(items: string[][], current: string,options?: { label?: string; attr?: string; className?: string }): string;diff --git a/frontend/test/configuration.test.tsx b/frontend/test/configuration.test.tsxindex 14dbaca54..0c23e795e 100644--- a/frontend/test/configuration.test.tsx+++ b/frontend/test/configuration.test.tsx@@ -1,5 +1,6 @@import { render } from 'preact';import { afterEach, describe, expect, it, vi } from 'vitest';+import * as legacyUi from '@peach/legacy/ui';import {CONFIGURATION_URL, Configuration, PICK_FOLDER_URL, loadConfiguration,@@ -37,6 +38,8 @@ const fetchMock = (status: number, body: unknown) => vi.fn<(...call: FetchCall));afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();for (const el of [...document.body.children]) render(null, el);document.body.innerHTML = '';vi.unstubAllGlobals();@@ -68,6 +71,42 @@ it('缺失依赖提供带图标的新窗口下载链接且已安装依赖不提});describe('配置页取数', () => {+ it('刷新恢复已准备的更新并弹出重启选择,确认前不发送重启', async () => {+ vi.useFakeTimers();+ const modal = vi.spyOn(legacyUi,'confirmModal');+ const fetch = fetchMock(200,{state:'restarting',progress:0});+ vi.stubGlobal('fetch',fetch);+ const initial = {current_version:'0.9.0',latest_version:null,channel:'测试版',installation:'独立测试包',state:'unchecked',message:'尚未检查',release_url:'https://github.com/longmeidao/peach/releases'};+ const {el} = mount({updates:initial,update_job:{state:'ready',progress:100,version:'0.10.0'}});+ await vi.advanceTimersByTimeAsync(100);+ expect(el.querySelector('[role="progressbar"]')?.getAttribute('aria-valuenow')).toBe('100');+ expect(modal).toHaveBeenCalledTimes(1);+ expect(modal.mock.calls[0]?.[0]).toMatchObject({title:'更新已准备好',confirmLabel:'立即重启',cancelLabel:'稍后'});+ expect(fetch).not.toHaveBeenCalled();+ await modal.mock.calls[0]?.[0].onConfirm?.();+ expect(fetch.mock.calls[0]?.[0]).toBe('/api/configuration/update-restart');+ });+ it('版本字段组显式查询测试版,失败后可重试且保留焦点', async () => {+ const initial = {current_version:'0.9.0',latest_version:null,channel:'测试版',installation:'独立测试包',state:'unchecked',message:'尚未检查',release_url:'https://github.com/longmeidao/peach/releases'};+ const {el} = mount({updates:initial});+ const section = el.querySelector('[aria-labelledby="configUpdatesTitle"]')!;+ const button = section.querySelector('button')!;+ expect(section.textContent).toContain('当前版本0.9.0');+ const fetch = fetchMock(200, {...initial,latest_version:'0.10.0',state:'available',message:'有新版本可下载。'});+ vi.stubGlobal('fetch',fetch);+ button.focus(); button.click(); button.click();+ expect(fetch).toHaveBeenCalledTimes(1);+ await settle();+ expect(fetch.mock.calls[0]?.[0]).toBe('/api/configuration/updates');+ expect(section.textContent).toContain('最新版本0.10.0');+ expect(section.textContent).toContain('下载并安装');+ expect(document.activeElement).toBe(button);+ vi.stubGlobal('fetch',fetchMock(503,{detail:'连接失败'}));+ button.click(); await settle();+ expect(section.querySelector('[role="alert"]')?.textContent).toBe('连接失败');+ expect(section.textContent).not.toContain('0.10.0');+ expect(button.disabled).toBe(false);+ });it('首屏走 /api/configuration 并带上中止信号', async () => {const fetch = fetchMock(200, data());vi.stubGlobal('fetch', fetch);diff --git a/frontend/test/stubs/legacy-ui.ts b/frontend/test/stubs/legacy-ui.tsindex 26b505c08..49d5a15ff 100644--- a/frontend/test/stubs/legacy-ui.ts+++ b/frontend/test/stubs/legacy-ui.ts@@ -15,8 +15,9 @@ export const emptyStateHtml = (export const fieldsetTitle = (id: string, title: string): string =>`<h3 class="geist-fieldset-title" id="${id}">${title}</h3>`;export const loadingDotsHtml = (label: string): string => `<span>${label}</span>`;-export const progressHtml = (label: string, value: number, max: number): string =>- `<progress aria-label="${label}" value="${value}" max="${max}"></progress>`;+export const progressHtml = (label: string, value: number, max = 100): string =>+ `<progress role="progressbar" aria-label="${label}" value="${value}" max="${max}" aria-valuenow="${value}" aria-valuemax="${max}"></progress>`;+export const confirmModal = async (_options: unknown) => ({confirmed:false});export const MEDIA_SOURCE_ICONS: Record<string,string> = {local:'hard-drive','115':'fixture-115',pikpak:'fixture-pikpak'};export const selectOptionIconHtml = (mark?: string): string => mark ? `<i data-source-icon="${mark}"></i>` : '';diff --git a/scripts/build_app_entry.py b/scripts/build_app_entry.pyindex 0428c4d6d..b438a5e6c 100644--- a/scripts/build_app_entry.py+++ b/scripts/build_app_entry.py@@ -64,6 +64,9 @@ def wants_cli(argv: list[str]) -> bool:def main(argv: list[str] | None = None) -> int:argv = list(sys.argv if argv is None else argv)+ if len(argv) == 4 and argv[1] == "--apply-standalone-update":+ from peach.standalone_update import apply+ return apply(Path(argv[2]), int(argv[3]))if wants_cli(argv):_prepare_console()return cli_main(argv[1:])diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex ef2f2e956..eed0dd700 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -69,7 +69,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.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_windows_update.py", "test_release_updates.py", "test_standalone_update.py", "test_certs.py", "test_config.py","test_fsutil.py","test_job_status.py", "test_jobs.py", "test_reference_updates.py","test_repo_hygiene.py",diff --git a/src/peach/release_updates.py b/src/peach/release_updates.pynew file mode 100644index 000000000..6b8328b7b--- /dev/null+++ b/src/peach/release_updates.py@@ -0,0 +1,69 @@+"""GitHub 测试版查询;传输复用共享 HTTPX,安装入口指向正式发行页。"""+from __future__ import annotations++import json+import re+import httpx++from . import __version__, distribution+from .http import HttpRequest, HttpxTransport++RELEASES_URL = "https://github.com/longmeidao/peach/releases"+API_URL = "https://api.github.com/repos/longmeidao/peach/releases?per_page=100"+++def snapshot() -> dict:+ return {"current_version": __version__, "latest_version": None,+ "channel": "测试版", "installation": "独立测试包" if distribution.standalone() else "源码运行",+ "state": "unchecked", "message": "尚未检查", "release_url": RELEASES_URL}+++def _version(value: object) -> tuple[int, ...] | None:+ if not isinstance(value, str) or not re.fullmatch(r"v?\d+\.\d+\.\d+", value):+ return None+ return tuple(map(int, value.removeprefix("v").split(".")))+++def check(*, transport=None) -> dict:+ result = snapshot()+ client = transport or HttpxTransport()+ try:+ response = client(HttpRequest("GET", API_URL, {"Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28"}), 12.0, 2_000_000)+ if response.status != 200:+ message = "GitHub 请求受限,请稍后重试。" if response.status in (403, 429) else "无法连接 GitHub,请重试。"+ return dict(result, state="error", message=message)+ rows = json.loads(response.body)+ if not isinstance(rows, list):+ raise ValueError("release list required")+ releases = []+ for row in rows:+ if not isinstance(row, dict) or row.get("draft"):+ continue+ version = _version(row.get("tag_name"))+ if version is None:+ continue+ tag = row["tag_name"]+ assets = row.get("assets") or []+ expected = f"Peach-{tag.removeprefix('v')}-windows-x64.zip"+ if not any(isinstance(a, dict) and a.get("name") == expected and a.get("state") == "uploaded" for a in assets):+ continue+ asset = next(a for a in assets if a.get("name") == expected and a.get("state") == "uploaded")+ releases.append((version, tag, asset))+ if not releases:+ return dict(result, state="empty", message="暂未找到可下载的测试版。")+ version, tag, asset = max(releases, key=lambda item: item[0])+ current = _version(result["current_version"])+ if current is None:+ raise ValueError("current version required")+ state = "available" if version > current else "ahead" if version < current else "current"+ message = {"available": "有新版本可下载。", "ahead": "当前版本高于已发布测试版。", "current": "已是最新测试版。"}[state]+ return dict(result, latest_version=tag.removeprefix("v"), state=state, message=message,+ asset_url=f"{RELEASES_URL}/download/{tag}/{asset['name']}",+ asset_size=asset.get("size", 0), asset_digest=asset.get("digest"),+ release_url=f"{RELEASES_URL}/tag/{tag}")+ except (OSError, ValueError, TypeError, TimeoutError, httpx.HTTPError):+ return dict(result, state="error", message="未能取得版本信息,请重试。")+ finally:+ if transport is None:+ client.close()diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.pyindex d72b31bed..89c77f6e5 100644--- a/src/peach/routes_configuration.py+++ b/src/peach/routes_configuration.py@@ -22,6 +22,7 @@ from filelock import FileLock, Timeoutfrom . import access, distribution, folder_picker, onboarding, settings_file, media_configurationfrom .routes_auth import require_authfrom .routes_pages import runtime_fact_entries+from . import release_updates, standalone_updaterouter = APIRouter()_SAVE_LOCK = threading.Lock()@@ -82,6 +83,8 @@ def snapshot(config) -> dict[str, Any]:editable = managed_configuration()media = config.mounts.get("local") or config.locations.get("local", ())return {+ "updates": release_updates.snapshot(),+ "update_job": standalone_update.public(),"access": access.public(access.load(config.directory("secrets") / "access.json")),"editable": editable,"notice": "" if editable else FILE_MANAGED_NOTICE,@@ -105,6 +108,41 @@ def read_configuration(request: Request, _args=Depends(require_auth)):return snapshot(config)[email protected]("/api/configuration/updates")+def check_updates(request: Request, _args=Depends(require_auth)):+ local_only(request)+ return release_updates.check()++[email protected]("/api/configuration/update-status")+def update_status(request: Request, _args=Depends(require_auth)):+ local_only(request)+ return standalone_update.public()++[email protected]("/api/configuration/update")+def download_update(request: Request, _args=Depends(require_auth)):+ local_only(request)+ try:+ return standalone_update.start()+ except (ValueError, Timeout) as exc:+ raise HTTPException(409, str(exc)) from exc++[email protected]("/api/configuration/update-restart")+def restart_update(request: Request, _args=Depends(require_auth)):+ local_only(request)+ contract = request.app.state.web_contract+ from .jobs import BackgroundJob+ if any(isinstance(job, BackgroundJob) and (job.snapshot() or {}).get("status") == "running"+ for job in vars(contract).values()):+ raise HTTPException(409, "后台任务正在运行,请完成后重启安装。")+ try:+ return standalone_update.request_restart()+ except (ValueError, Timeout) as exc:+ raise HTTPException(409, str(exc)) from exc++def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, Any]]:"""逐项校验,错误按字段归位:文件夹按行、端口一句。全对时第一个返回值为空。"""errors: dict[str, Any] = {}diff --git a/src/peach/standalone_update.py b/src/peach/standalone_update.pynew file mode 100644index 000000000..2c3e07a7e--- /dev/null+++ b/src/peach/standalone_update.py@@ -0,0 +1,241 @@+"""独立 Windows 包的持久更新事务:下载准备、用户重启、目录切换与回滚。"""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import shutil+import subprocess+import sys+import threading+import time+import uuid+import zipfile++import httpx+from filelock import FileLock, Timeout++from . import distribution, release_updates+from .config import STATE_DIR+from .fsutil import atomic_write_text+from .windows_update import replace_with_retry++ACTIVE = {"downloading", "verifying", "extracting", "preparing", "restarting", "installing"}+MAX_ARCHIVE = 512 * 1024 * 1024+MAX_EXPANDED = 2 * 1024 * 1024 * 1024+++def state_path() -> Path:+ return STATE_DIR / "standalone-update.json"+++def read() -> dict:+ try:+ return json.loads(state_path().read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {"state": "idle", "progress": 0}+++def write(data: dict, **changes) -> dict:+ data.update(changes, updated_at=time.time())+ atomic_write_text(state_path(), json.dumps(data, ensure_ascii=False))+ return data+++def public() -> dict:+ data = read()+ if data.get("state") in ACTIVE and time.time() - data.get("updated_at", 0) > 180:+ data = dict(data, state="error", message="更新任务已中断,请重试。")+ return {key: value for key, value in data.items() if key in {+ "state", "progress", "message", "downloaded", "total", "version", "updated_at"}}+++def extract(archive: Path, destination: Path, progress) -> Path:+ destination = destination.resolve()+ with zipfile.ZipFile(archive) as package:+ entries = package.infolist()+ if sum(item.file_size for item in entries) > MAX_EXPANDED or len(entries) > 20000:+ raise ValueError("更新包展开体积超限")+ seen = set()+ for index, item in enumerate(entries):+ name = item.filename+ parts = PurePosixPath(name).parts+ if (not parts or parts[0] != "Peach" or "\\" in name or ":" in name+ or ".." in parts or name.startswith("/") or (item.external_attr >> 16) & 0o170000 == 0o120000):+ raise ValueError("更新包含无效路径")+ target = destination.joinpath(*parts).resolve()+ key = str(target).casefold()+ if not target.is_relative_to(destination) or key in seen:+ raise ValueError("更新包路径重复或越界")+ seen.add(key)+ package.extract(item, destination)+ progress(index + 1, len(entries))+ root = destination / "Peach"+ if not (root / "Peach.exe").is_file() or not (root / "_internal" / "standalone.txt").is_file():+ raise ValueError("更新包不是独立 Windows 版本")+ return root+++def prepare(data: dict, lock: FileLock) -> None:+ try:+ release = release_updates.check()+ if release["state"] != "available":+ raise ValueError(release["message"])+ digest = release.get("asset_digest") or ""+ if not digest.startswith("sha256:") or len(digest) != 71:+ raise ValueError("更新包缺少 SHA-256 校验信息")+ total = release.get("asset_size", 0)+ if not isinstance(total, int) or not 0 < total <= MAX_ARCHIVE:+ raise ValueError("更新包大小无效")+ target = Path(sys.executable).resolve().parent+ if STATE_DIR.resolve().is_relative_to(target):+ raise ValueError("数据目录位于程序目录内,不能自动替换")+ transaction = target.parent / f".{target.name}-update-{data['id']}"+ transaction.mkdir()+ write(data, transaction=str(transaction), target=str(target), version=release["latest_version"],+ total=total, downloaded=0, message="正在下载", state="downloading")+ archive = transaction / "package.zip"+ checksum = hashlib.sha256()+ received = 0+ with httpx.Client(follow_redirects=True, timeout=30) as client, client.stream("GET", release["asset_url"]) as response:+ response.raise_for_status()+ with archive.open("wb") as output:+ for chunk in response.iter_bytes(256 * 1024):+ received += len(chunk)+ if received > total:+ raise ValueError("下载体积与发布记录不符")+ output.write(chunk); checksum.update(chunk)+ write(data, downloaded=received, progress=round(received / total * 65, 1))+ write(data, state="verifying", progress=66, message="正在校验")+ if received != total or checksum.hexdigest() != digest[7:]:+ raise ValueError("更新包校验失败,请重新下载")+ write(data, state="extracting", message="正在解压")+ stage = extract(archive, transaction / "stage", lambda done, count: write(data, progress=67 + round(done / count * 20)))+ from .buildinfo import read_build_info+ info = read_build_info(stage / "_internal")+ if not info or info.version != release["latest_version"]:+ raise ValueError("包内版本与发布版本不符")+ write(data, state="preparing", progress=90, message="正在准备安装")+ # 助手从自己的目录运行,正式目录与暂存目录都不会被它的 DLL 句柄占用。+ helper = transaction / "helper"+ shutil.copytree(target, helper, ignore=shutil.ignore_patterns("*.log"))+ write(data, stage=str(stage), helper=str(helper), state="ready", progress=100,+ message="更新已准备好,重启后安装。")+ except Exception as exc:+ write(data, state="error", message=str(exc), progress=0)+ finally:+ lock.release()+++def start() -> dict:+ if not distribution.standalone() or sys.platform != "win32":+ raise ValueError("此安装方式不支持独立包更新")+ lock = FileLock(str(state_path()) + ".lock", thread_local=False)+ try:+ lock.acquire(timeout=0)+ except Timeout:+ return public()+ if public().get("state") in ACTIVE | {"ready"}:+ lock.release()+ return public()+ data = write({"id": uuid.uuid4().hex}, state="downloading", progress=0, message="正在连接 GitHub")+ threading.Thread(target=prepare, args=(data, lock), daemon=True, name="PeachPackageUpdate").start()+ return public()+++def request_restart() -> dict:+ if not distribution.standalone() or sys.platform != "win32":+ raise ValueError("此安装方式不支持独立包更新")+ with FileLock(str(state_path()) + ".lock", timeout=0):+ data = read()+ if data.get("state") != "ready":+ raise ValueError("更新尚未准备完成")+ write(data, state="restarting", progress=0, message="正在重启安装")+ return public()+++def poll(tray) -> None:+ if not distribution.standalone() or read().get("state") != "restarting":+ return+ if not tray._action_lock.acquire(blocking=False):+ return+ try:+ data = read()+ helper = Path(data["helper"]) / "Peach.exe"+ environment = os.environ.copy()+ environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"+ subprocess.Popen([str(helper), "--apply-standalone-update", str(state_path()), str(os.getpid())],+ cwd=str(helper.parent), env=environment, creationflags=subprocess.CREATE_NO_WINDOW)+ tray.exit()+ except Exception as exc:+ write(read(), state="error", message=f"未能重启:{exc}")+ finally:+ tray._action_lock.release()+++def apply(manifest: Path, wait_pid: int) -> int:+ """复制出来的助手等待原托盘正常退出,再在同一卷上切换两个目录。"""+ from .windows_restart import process_alive, start_tray, find_tray_windows, post_stop+ from .tray import configured_service_specs+ from .settings_file import load_config+ if manifest.resolve() != state_path().resolve():+ return 2+ data = read()+ target = Path(data["target"]).resolve()+ transaction = Path(data["transaction"]).resolve()+ stage = Path(data["stage"]).resolve()+ if (transaction.parent != target.parent or transaction.name != f".{target.name}-update-{data['id']}"+ or stage != transaction / "stage" / "Peach" or STATE_DIR.resolve().is_relative_to(target)+ or not (target / "_internal" / "standalone.txt").is_file()):+ return 2+ backup = transaction / "backup"+ moved = False+ installed = False+ try:+ deadline = time.monotonic() + 90+ while process_alive(wait_pid):+ if time.monotonic() > deadline:+ raise TimeoutError("托盘尚未退出,安装已取消")+ time.sleep(.25)+ write(data, state="installing", progress=20, message="正在保留旧版本")+ replace_with_retry(target, backup)+ moved = True+ write(data, progress=50, message="正在安装新版本")+ replace_with_retry(stage, target)+ installed = True+ write(data, progress=80, message="正在启动新版本")+ start_tray(target / "Peach.exe")+ deadline = time.monotonic() + 90+ specs = configured_service_specs(load_config())+ spec = next((s for s in specs if s.name == "https"), specs[0])+ while time.monotonic() < deadline:+ try:+ health = httpx.get(spec.health_url, verify=spec.verify, trust_env=False, timeout=3)+ ready = httpx.get(spec.health_url + "?ready=1", verify=spec.verify, trust_env=False, timeout=3)+ if (health.status_code == ready.status_code == 200 and health.json().get("version") == data["version"]+ and ready.json().get("ready") and find_tray_windows(target / "Peach.exe")):+ write(data, state="complete", progress=100, message=f"已更新至 {data['version']}")+ return 0+ except (httpx.HTTPError, ValueError):+ pass+ time.sleep(1)+ raise TimeoutError("新版本未能就绪")+ except Exception as exc:+ if moved:+ try:+ if installed:+ for window in find_tray_windows(target / "Peach.exe"):+ post_stop(window.handle)+ replace_with_retry(target, transaction / "failed")+ replace_with_retry(backup, target)+ start_tray(target / "Peach.exe")+ message = f"更新失败,已恢复旧版本:{exc}"+ except Exception as rollback:+ message = f"更新失败,回滚未完成:{rollback}"+ else:+ message = f"更新未安装:{exc}"+ if not process_alive(wait_pid):+ start_tray(target / "Peach.exe")+ write(data, state="error", progress=0, message=message)+ return 1diff --git a/src/peach/tray.py b/src/peach/tray.pyindex d67dcf291..7b2a0ed09 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -1049,6 +1049,10 @@ class PeachTray:def _monitor(self) -> None:while not self._stop_event.wait(2 if standalone() else 10):+ from .standalone_update import poll+ poll(self)+ if self._stop_event.is_set():+ return# 先看首次设置有没有完成:切换会换掉 `manager.specs`,采样必须落在换完之后。self.gate.poll()for spec in self.manager.specs:diff --git a/src/peach/versioning.py b/src/peach/versioning.pyindex 2aeabd885..f41a3e098 100644--- a/src/peach/versioning.py+++ b/src/peach/versioning.py@@ -176,7 +176,10 @@ class VersionManager:before = self.inspect()from .distribution import standaloneif standalone():- return UpdateResult("manual", "测试包请从 GitHub Releases 下载新版并完整解压替换程序目录;数据保存在用户目录。", before)+ from .release_updates import check+ release = check()+ latest = f"最新测试版:{release['latest_version']}。" if release['latest_version'] else ""+ return UpdateResult(release["state"], f"当前版本:{before.package_version}。{latest}{release['message']}", before)if not before.remote_configured:return UpdateResult("unconfigured",diff --git a/src/peach/windows_restart.py b/src/peach/windows_restart.pyindex 12ef7da05..fdb9d86b0 100644--- a/src/peach/windows_restart.py+++ b/src/peach/windows_restart.py@@ -45,11 +45,8 @@ def _normal_path(path: str | Path) -> str:def process_alive(process_id: int) -> bool:- try:- os.kill(process_id, 0)- except OSError:- return False- return True+ from .jobs import PidFileLock+ return PidFileLock._running(process_id)def _process_paths_and_parents() -> tuple[dict[int, str], dict[int, int]]:diff --git a/tests/test_onboarding.py b/tests/test_onboarding.pyindex 07d2c77d4..355ce0274 100644--- a/tests/test_onboarding.py+++ b/tests/test_onboarding.py@@ -659,6 +659,17 @@ class SetupPageTests(_Case):class StandaloneConfigurationTests(_Case):+ def test_release_update_endpoints_require_local_authenticated_access(self):+ with self.client() as client, mock.patch("peach.release_updates.check", return_value={"state": "current"}) as check:+ self.assertEqual(client.get("/api/configuration/updates").status_code, 401)+ response = client.get("/api/configuration/updates", headers={"X-Token": "test-token"})+ self.assertEqual(response.json(), {"state": "current"})+ check.assert_called_once()+ self.assertEqual(client.post("/api/configuration/update", headers={"X-Token":"test-token", "Origin":"https://evil.example"}).status_code,403)+ with self.client(address="192.0.2.9") as client:+ for path in ("updates", "update-status"):+ self.assertEqual(client.get(f"/api/configuration/{path}",headers={"X-Token":"test-token"}).status_code,403)+def test_missing_media_tools_have_download_links_in_json_and_setup_facts(self):from peach.routes_pages import runtime_fact_entries, runtime_facts_htmlfor missing_ffmpeg, missing_probe in ((True, True), (False, True), (False, False)):diff --git a/tests/test_release_updates.py b/tests/test_release_updates.pynew file mode 100644index 000000000..e7e00bf3a--- /dev/null+++ b/tests/test_release_updates.py@@ -0,0 +1,53 @@+"""发行通道、故障状态和独立托盘检查的隔离回归。"""+import json+import unittest+from unittest.mock import Mock, patch++import httpx++from peach import release_updates+from peach.http import HttpResponse+from peach.versioning import VersionManager+++def release(version, **extra):+ return dict(tag_name=f"v{version}", prerelease=True, draft=False,+ assets=[{"name": f"Peach-{version}-windows-x64.zip", "state": "uploaded"}], **extra)+++class ReleaseUpdateTests(unittest.TestCase):+ def check(self, rows, status=200):+ transport = Mock(return_value=HttpResponse(status, {}, json.dumps(rows).encode()))+ with patch.object(release_updates, "__version__", "0.9.0"):+ return release_updates.check(transport=transport)++ def test_channel_includes_prereleases_and_orders_versions_numerically(self):+ result = self.check([release("0.9.0"), release("0.10.0")])+ self.assertEqual((result["state"], result["latest_version"]), ("available", "0.10.0"))+ self.assertEqual(result["release_url"], release_updates.RELEASES_URL + "/tag/v0.10.0")++ def test_unpublished_or_incomplete_packages_are_not_offered(self):+ draft = release("8.0.0"); draft["draft"] = True+ incomplete = release("9.0.0"); incomplete["assets"] = []+ result = self.check([draft, incomplete, {"tag_name": "invalid"}, release("0.9.0")])+ self.assertEqual(result["state"], "current")+ self.assertEqual(self.check([release("0.8.0")])["state"], "ahead")+ self.assertEqual(self.check([])["state"], "empty")++ def test_failures_do_not_claim_current_or_keep_a_latest_version(self):+ self.assertEqual(self.check({}, status=429)["state"], "error")+ self.assertEqual(self.check({})["state"], "error")+ for cause in (httpx.ConnectError("offline"), httpx.ReadTimeout("timeout")):+ result = release_updates.check(transport=Mock(side_effect=cause))+ self.assertEqual(result["state"], "error")+ self.assertIsNone(result["latest_version"])++ def test_standalone_tray_checks_releases_without_git(self):+ execute = Mock(side_effect=AssertionError("Git must not run"))+ with patch("peach.distribution.standalone", return_value=True), patch.object(+ release_updates, "check", return_value=dict(state="available", latest_version="1.0.0", message="有新版本可下载。")) as check:+ result = VersionManager(execute=execute).check()+ check.assert_called_once()+ self.assertEqual(result.state, "available")+ self.assertIn("1.0.0", result.message)+ execute.assert_not_called()diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.pyindex e64b43083..be0cf192d 100644--- a/tests/test_restart_windows_tray.py+++ b/tests/test_restart_windows_tray.py@@ -27,6 +27,12 @@ def load_entry():class RestartWindowsTrayTests(unittest.TestCase):+ def test_process_probe_reuses_read_only_pid_check(self):+ with mock.patch("peach.jobs.PidFileLock._running", return_value=True) as running, mock.patch("os.kill") as kill:+ self.assertTrue(windows_restart.process_alive(123))+ running.assert_called_once_with(123)+ kill.assert_not_called()+def setUp(self):self.temp = tempfile.TemporaryDirectory()# restart_tray 第一件事就是 target.resolve(),并由它推出 .venv 里的服务入口。diff --git a/tests/test_standalone_update.py b/tests/test_standalone_update.pynew file mode 100644index 000000000..513155af6--- /dev/null+++ b/tests/test_standalone_update.py@@ -0,0 +1,83 @@+"""独立包更新使用临时目录验证路径、进度、重启确认及回滚。"""+import json+from pathlib import Path+import tempfile+import unittest+from unittest.mock import Mock, patch+import zipfile++from peach import standalone_update as update+++class StandaloneUpdateTests(unittest.TestCase):+ def setUp(self):+ temp = tempfile.TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ self.root = Path(temp.name).resolve()+ self.state = self.root / "state"+ self.state.mkdir()+ patcher = patch.object(update, "STATE_DIR", self.state)+ patcher.start(); self.addCleanup(patcher.stop)++ def archive(self, names):+ archive = self.root / "package.zip"+ with zipfile.ZipFile(archive, "w") as package:+ for name in names:+ package.writestr(name, "fixture")+ return archive++ def test_zip_requires_a_complete_standalone_layout_and_reports_progress(self):+ archive = self.archive(["Peach/Peach.exe", "Peach/_internal/standalone.txt"])+ progress = Mock()+ root = update.extract(archive, self.root / "extract", progress)+ self.assertTrue((root / "Peach.exe").is_file())+ self.assertEqual(progress.call_args.args, (2, 2))++ def test_zip_rejects_traversal_windows_streams_and_case_collisions(self):+ for name in ("../escape", "Peach/../escape", "C:/escape", "Peach/a:b", "Peach/Peach.exe"):+ with self.subTest(name=name):+ archive = self.archive(["Peach/peach.exe", name])+ with self.assertRaises(ValueError):+ update.extract(archive, self.root / "extract", Mock())++ def test_stale_progress_is_retryable_and_public_state_hides_paths(self):+ update.write({}, state="downloading", target="private-path", progress=22)+ with patch.object(update.time, "time", return_value=10**12):+ self.assertEqual(update.public()["state"], "error")+ self.assertNotIn("target", update.public())++ def test_restart_requires_ready_and_only_records_intent(self):+ with patch.object(update.distribution, "standalone", return_value=True), patch.object(update.sys, "platform", "win32"):+ with self.assertRaises(ValueError):+ update.request_restart()+ update.write({}, state="ready", version="1.0.0")+ with patch.object(update.subprocess, "Popen") as launch:+ self.assertEqual(update.request_restart()["state"], "restarting")+ launch.assert_not_called()++ def test_source_installs_cannot_start_binary_update(self):+ with patch.object(update.distribution, "standalone", return_value=False):+ with self.assertRaises(ValueError):+ update.start()++ def test_install_failure_restores_program_directory_and_preserves_data(self):+ target = self.root / "app"; target.mkdir()+ (target / "Peach.exe").write_text("old")+ (target / "_internal").mkdir()+ (target / "_internal" / "standalone.txt").touch()+ transaction = self.root / ".app-update-fixture"; transaction.mkdir()+ stage = transaction / "stage" / "Peach"; stage.mkdir(parents=True)+ (stage / "Peach.exe").write_text("new")+ update.write({"id":"fixture", "target":str(target), "transaction":str(transaction), "stage":str(stage), "version":"1.0.0"}, state="restarting")+ original = update.replace_with_retry+ def replace(source, destination):+ if source == stage:+ raise OSError("occupied")+ original(source, destination)+ with patch("peach.windows_restart.process_alive", return_value=False), patch.object(+ update, "replace_with_retry", side_effect=replace), patch("peach.windows_restart.start_tray") as start:+ self.assertEqual(update.apply(update.state_path(), 999), 1)+ self.assertEqual((target / "Peach.exe").read_text(), "old")+ self.assertEqual(update.public()["state"], "error")+ start.assert_called_once_with(target / "Peach.exe")+ self.assertTrue(self.state.is_dir())diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 6afe81635..7741db3a0 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -386,6 +386,13 @@ class WebUiSourceTests(unittest.TestCase):self.assertEqual(offenders, [],f"这些规则的 --tungsten 不在允许的焦点/链接/进度/Toggle 之列:{offenders}")+ def test_credential_collapse_reserves_space_for_outside_focus_ring(self):+ css = (Path(__file__).resolve().parents[1] / "web/css/22-followmanage.css").read_text(encoding="utf-8")+ match = re.search(r"\.fcred \.fcollapsebody\{padding:(\d+)px (\d+)px (\d+)px", css)+ self.assertIsNotNone(match)+ self.assertGreaterEqual(int(match[2]), 3)+ self.assertIn('.fcredfield input{height:32px;width:100%;min-width:0;', css)+def test_field_focus_rings_are_neutral_and_theme_aware(self):"""输入框的静止边、悬停边与聚焦环都是当前主题的中性透明色,不是蓝的。@@ -399,6 +406,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains(palette)self.assertPageContains("--field-ring:rgba(0,0,0,.08);--field-ring-hover:rgba(0,0,0,.21);")self.assertPageContains("--field-ring-focus:rgba(0,0,0,.34);--field-glow:rgba(0,0,0,.16);")+self.assertPageContains("--field-ring:rgba(255,255,255,.14);--field-ring-hover:rgba(255,255,255,.24);")self.assertPageContains("--field-ring-focus:rgba(255,255,255,.51);--field-glow:rgba(255,255,255,.24);")for selector in ('.geist-search input[type="search"]', ".geist-input", ".preference textarea"):diff --git a/web/css/22-followmanage.css b/web/css/22-followmanage.cssindex a22bee09d..b01487840 100644--- a/web/css/22-followmanage.css+++ b/web/css/22-followmanage.css@@ -265,21 +265,21 @@.fcred.none{color:var(--muted);gap:8px}/* 折叠时 .frow 让它是 flex、展开时又变 block,两种几何下 summary 的可用宽度差一个 gap,状态列就差 12px 对不齐。统一成 block:summary 自己是 flex 容器,宽度始终是整行。 */-details.fcred{display:block}+details.fcred{display:block;min-width:0}/* 展开体的内边距归 .fcollapsebody:留在 .fcred[open] 上的话,收起那一帧高度已经归零、内边距还在,行尾会跳一下。首段自己的上边距换成容器内边距,免得它跟容器外边距合并,量出来的 scrollHeight 比实际矮一截。 */-.fcred .fcollapsebody{padding:8px 0 12px}+.fcred .fcollapsebody{padding:8px 4px 12px}.fcred .fcollapsebody>p:first-child{margin-top:0}.fcred .ficonslot{flex:none;display:block;width:14px;height:14px}.fcred .ficon{margin-right:0}.fcred p{margin:8px 0 0;font-size:var(--fs-sm);line-height:1.7;color:var(--muted);overflow-wrap:anywhere}.fcred a{color:var(--tungsten)}-.fcredform{display:grid;gap:8px;margin-top:10px}-.fcredfield{display:grid;gap:4px}+.fcredform{display:grid;gap:8px;margin-top:10px;min-width:0}+.fcredfield{display:grid;gap:4px;min-width:0}.fcredfield span{font-size:var(--fs-xs);color:var(--muted)}-.fcredfield input{height:32px;box-sizing:border-box;border:1px solid var(--border-15);+.fcredfield input{height:32px;width:100%;min-width:0;box-sizing:border-box;border:1px solid var(--border-15);border-radius:var(--control-radius);background:var(--ground);color:var(--ink);padding:0 12px;font-size:var(--fs-md);font-family:inherit;transition:border-color .12s ease}.fcredfield input:focus-visible{outline:2px solid var(--tungsten);outline-offset:1px;