Peach: Local-first video metadata scraper and media manager.
feat(tray): 菜单栏加「同步开发进度」;同步 Ledger 不再为没事干的判定停服务
Peach local maintenance00b6ea31a80b
diff --git a/README.md b/README.mdindex 95169f14d..a641d0b4c 100644--- a/README.md+++ b/README.md@@ -78,8 +78,10 @@ worktree 目录。跨机器继续任务时 push 分支,在另一台按分支- 「同步 Ledger」是唯一复制入口;「接管 Ledger 写入」只有在本地/共享完全一致时才切换写入端。- **两边都动过就拒绝自动合并**,由人选一边。- 共享目录不可达时本地照常运行,恢复连接后再同步;媒体外置盘是否插入与账本同步无关。-- macOS 菜单栏和 Windows 托盘都有「同步 Ledger」:它只停止当前托盘拥有的 HTTP/HTTPS,- 完成一次安全推送或拉取后再恢复服务;发现端口由别的进程占用时拒绝接管。+- macOS 菜单栏和 Windows 托盘都有「同步 Ledger」:它先只读判定这次会不会真的复制,+ 会复制才停止当前托盘拥有的 HTTP/HTTPS,完成一次安全推送或拉取后再恢复服务;+ 共享盘没挂、两侧已经一致或本机不是写入端时直接回话,不动服务。+ 发现端口由别的进程占用时拒绝接管。世代号只表示血缘先后,不表示时间:时钟在两台机器上不可靠。血缘记在库文件旁边的 `ledger.db.sync.json` 里,不进 Git,也不需要改表结构。@@ -212,6 +214,12 @@ macOS 日常运行走菜单栏项,而不是留一个终端窗口:菜单中的「同步 Ledger」会先安全停止本菜单栏项创建的服务,再同步和恢复,不需要退出应用。+「同步开发进度」和它是两回事,所以是两个按钮:前者走 GitHub 把本地检出快进到+`origin/master` 再让新代码跑起来,后者走共享盘搬账本。两条链路互不兜底——共享盘没挂+不该挡住拉代码,拉代码失败也不该被说成账本出了事。它只做 `merge --ff-only`:工作区有+未提交修改或两边分叉时原样报出来,不会 stash 也不会改写历史。拉到的改动动了菜单栏项+自己的代码时,光重启子服务追不上,它会用 `launchctl kickstart -k` 把菜单栏项一起重启。+**菜单栏项没有跨平台的轮子。** pystray 名义上支持 darwin,但它的后端漏了三件事:`setActivationPolicy_(Accessory)`、`NSImage.setSize_(18,18)`(菜单栏按 18pt 画,直接塞64px 位图会被裁掉)和 `setTemplate_`(不设就不会跟着浅色/深色菜单栏反色)。补齐等于diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex e66486a71..0aa177cfc 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -181,9 +181,9 @@ Claude 的 `.claude/settings.json` 已配置 Stop、StopFailure、SessionEnd hoo- Windows 日常入口是当前用户 Startup 中的唯一 `Peach.lnk`,指向 `C:\Users\longm\Desktop\peach\peach-app\dist\Peach\Peach.exe`。`R:\peach-app` 是迁移前的旧位置,不再用作运行入口。- Windows 发布入口使用 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 从原始附件生成正方形 `resources/peach-logo.png` 和多尺寸 `resources/peach.ico`,再构建单一 `dist/Peach/Peach.exe`。无参数运行托盘,`serve`/`migrate` 运行 CLI;桌面快捷方式由 `scripts/create_desktop_shortcut.ps1` 创建,图标使用 `Peach.exe,0`,行为与 FlowLens 的快捷方式一致;Startup 安装仍由 `scripts/manage_tray_startup.ps1` 负责。- `dist/Peach/Peach.exe` 是本机打包入口,不是可移动的独立发行版:托盘只打包了自己,服务进程仍由项目 venv 的 `peach.exe` 承担(`_peach_executable()` 从 exe 位置逐级向上找 `.venv\Scripts\peach.exe`)。脱离同一台机器的项目 `.venv` 复制不会工作,不要按「单文件绿色版」对外描述。PyInstaller 的资源直接位于 `sys._MEIPASS`,没有源码树的 `src/` 层;打包后的 `migrate`、Web 与品牌资源必须从这里解析,不能再对 `config.py` 固定取 `parents[2]`。-- 托盘单击打开 HTTPS;macOS/Windows 菜单都提供「同步 Ledger」「接管 Ledger 写入」、状态、重启、日志和退出。HTTP/HTTPS 服务只观察角色,不自动复制;手动同步先停止自己创建的服务,再用 SQLite backup API 与原子替换复制,最后恢复服务。共享源在 macOS smbfs 上必须以 immutable 已关闭快照读取;共享目标不能由 SQLite 直接打开事务连接。健康端口不归本托盘时拒绝接管。+- 托盘单击打开 HTTPS;macOS/Windows 菜单都提供「同步 Ledger」「接管 Ledger 写入」、状态、重启、日志和退出,macOS 另有「同步开发进度」。**这两个「同步」不能合并成一个按钮**:一个走 GitHub、一个走 SMB 共享,任一方不可达都不该拖住另一方(本机常态就是共享盘没挂而 GitHub 正常),而且失败的含义完全不同——快进失败什么都没变,账本同步失败牵涉唯一写入端和数据取舍。HTTP/HTTPS 服务只观察角色,不自动复制;手动同步先用 `sync.resolve()` 只读判定这次会不会真的复制:`offline`/`conflict`/`in-sync` 一律直接回话,**不停服务**——停一停再启回来换不到任何东西,只换来一次十几秒的断网页和一条「同步失败」。会复制时才停止自己创建的服务,用 SQLite backup API 与原子替换复制,最后恢复服务。「接管 Ledger 写入」只在共享盘不可达时短路,因为 `in-sync` 对它正是要做的那一次。共享源在 macOS smbfs 上必须以 immutable 已关闭快照读取;共享目标不能由 SQLite 直接打开事务连接。健康端口不归本托盘时拒绝接管。- 创建 Win32 窗口前必须启用 Per-Monitor V2 DPI。正常动作不弹模态 MessageBox;更新检查在后台线程执行,用 pystray 原生非模态通知反馈。-- `src/peach/__init__.py::__version__` 是版本唯一来源;采用 pre-1.0 SemVer。Git commit 是构建标识,`vX.Y.Z` 是本地发布点。更新检查只 fetch/比较,并行 worktree 模式下不自动覆盖安装。+- `src/peach/__init__.py::__version__` 是版本唯一来源;采用 pre-1.0 SemVer。Git commit 是构建标识,`vX.Y.Z` 是本地发布点。「检查更新」只 fetch/比较;「同步开发进度」只做 `merge --ff-only`,不 stash、不 rebase、不 `--force`——并行工作树和主检出共用同一个对象库与 reflog,任何改写历史的「顺手解决」都会把别的分支一起拖下去。工作区脏或两边分叉时原样报出来交给人。快进动到 `tray.py`/`menubar.py`/`versioning.py`/`certs.py`/`netwatch.py`/`config.py`/`pyproject.toml` 时**只重启子服务追不上**,托盘要靠 `launchctl kickstart -k` 重启自己,顺序必须是先 `stop_owned()` 再 kickstart(反过来,新托盘会看到一组健康但 `_owned` 为空的服务,此后每次同步都被自己的归属检查挡掉)。kickstart 的前提是 launchd 报的 pid 等于自己的 pid,不是「plist 存在」——从终端跑起来的托盘 kickstart 会在旁边**再**起一个。- `scripts/manage_tray_startup.ps1` 是唯一自启动管理入口。托盘管理 HTTP `0.0.0.0:80` 和当前路由选出的 LAN IPv4 上的 HTTPS 443;显式参数、`PEACH_LAN_ADDRESS`、`lan_ipv4()` 依次覆盖。服务日志写入本机 `peach-data/logs`。- `peach serve` 按平台发布固定主机名:macOS 为 `peach.local`,Windows 为 `peach-win.local`。Windows 不在源码钉家庭 IP,仍保留 `Zeroconf()` 全合格网卡监听。mDNS 验收必须包含单元测试、运行态 health、DNS-SD、主机名解析和真实 LAN 客户端。- `.local` 使用本地 CA,不使用 Let's Encrypt。证书/私钥保存在本机 `peach-data/secrets`。TLS 私钥禁用 ACL 继承,只允许实际服务身份、SYSTEM、Administrators;当前 Windows 服务身份是 `longm`。macOS/iOS 只安装并信任 `peach-local-ca.crt`,不得分发 CA key 或服务器 key。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex a944e4849..3004d647c 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -1,6 +1,6 @@# Peach 当前状态-最后核验:2026-08-26+最后核验:2026-08-27## 运行态@@ -24,7 +24,11 @@验收均为 200;当时连续 120 秒浏览观测 local/shared generation 均保持29。- mDNS 使用 Python zeroconf 的全合格网卡监听;生产显式固定发布地址,避免隧道网卡误选。没有发布 `lmd-dst.local`。- macOS 菜单栏已按同一重构上线为 `0.6.2` reader,管理 `8900/8443` 并由 pf 提供- `peach.local:80/443`。菜单提供「同步 Ledger」和「接管 Ledger 写入」;GET 正常、POST 返回409。+ `peach.local:80/443`。菜单提供「同步开发进度」「同步 Ledger」和「接管 Ledger 写入」;+ GET 正常、POST 返回409。2026-08-27 实测:服务进程跑的是当前 `master`(`/healthz` 报+ `0.6.4`),但菜单栏进程本身是 08-26 22:21 拉起来的旧代码——托盘只重启子服务追不上自己,+ 这正是「同步开发进度」在改到托盘层文件时要 `launchctl kickstart -k` 的原因。+ 新菜单项要生效,得先手动退出菜单栏项再从 `.app` 或 `launchctl kickstart` 拉起一次。- Stash 仍运行于 `127.0.0.1:9999`,只作为过渡期可替换适配器。- Python:3.14.7;FFmpeg/ffprobe 由`C:\Users\longm\Desktop\peach\peach-data\tools\ffmpeg` 管理,不再依赖 Stash 私有目录。@@ -44,6 +48,15 @@- `local_dirty` 的判据已按 ADR-0020 改成三层。原先只看 `(size, mtime_ns)`,实测既会**误报**(内容中性的 checkpoint、碰时间戳)也会**漏报**(已提交但还在 WAL 里的事务完全不改主库文件,`copy_database` 会连同 `-wal` 一起删掉,静默丢数据)。+- **2026-08-27 复核:Mac 与共享副本的内容其实一模一样,dirty 是物理层面的。**+ 当天 `/Volumes/peach-sync` 未挂载(`plan=offline`),挂上后 `plan=local-ahead`、+ `writer=host-88053062`,所以「同步 Ledger」必然报 conflict。但逐表比对的结论是两边+ **完全一致**:32 张表行数全同,按 rowid 顺序对每张表算内容哈希也全同,两侧+ `schema_migration` 都到 `0018`。差的只有文件字节(local/shared/marker 三个 SHA-256+ 互不相同,主库大小 127340544 未变)——page 布局、freelist、checkpoint 这类内容中性的+ 改动,`local_dirty` 的摘要层分不出来。**因此这个 conflict 没有数据在风险中**,+ 照 STATUS 原定的「取 Windows 那一份」执行不会丢东西。恢复到 `in-sync` 只需要一次+ `pull`(或按共享 marker 重写本地 marker),但这属于 ledger 写入,要显式授权后再做。- **历史记录**:Mac 本地副本自 2026-08-24 起就是 dirty 的(marker 记的是第 29 代、`mtime_ns=1787332506518044766`,实际库已是 `1787504652787227090`,大小未变),而共享传输点`/Volumes/peach-sync` 当前不可达。下次恢复同步时 `plan()` 会因「共享更新且本地有未回写改动」diff --git a/src/peach/sync.py b/src/peach/sync.pyindex ed5290b70..8eff1804a 100644--- a/src/peach/sync.py+++ b/src/peach/sync.py@@ -280,6 +280,10 @@ def copy_database(source: Path, target: Path, *, source_immutable: bool = False)transfer.unlink(missing_ok=True)+#: `synchronize_now` 里真的会复制数据库的那几个判定;其余都是「没什么可做」。+COPY_ACTIONS = ("pull", "push", "local-ahead")++def plan(local: Path, shared: Path) -> SyncPlan:"""只读判定,不碰任何文件。"""if local == shared or local.resolve() == shared.resolve():@@ -328,6 +332,25 @@ def plan(local: Path, shared: Path) -> SyncPlan:return SyncPlan("in-sync", "两侧一致", local_generation, shared_generation)+def resolve(local: Path, shared: Path, device: str) -> SyncPlan:+ """`synchronize_now` 将要照着做的那个判定,但不碰任何文件。++ 比 `plan()` 多的一层是写入端:本机不是写入端时,`push` / `local-ahead` 会被拒,+ 真跑一次的结果只能是 conflict。调用方要先知道「这次到底会不会复制」才能决定要不要+ 停服务——共享盘没挂、两侧已经一致、或本机根本推不动的时候,停一遍服务再启回来+ 是白白一次停机,还会把「没什么可做」报成同步失败。+ """+ decision = plan(local, shared)+ owner = writer_device(local, shared)+ if (decision.action in ("push", "local-ahead")+ and owner is not None and owner != device):+ return SyncPlan(+ "conflict", f"当前写入端是 {owner},本机不能推送",+ decision.local_generation, decision.shared_generation,+ )+ return decision++class LedgerSync:"""启动判定、周期回写和只读闸门。"""@@ -410,14 +433,7 @@ class LedgerSync:def synchronize_now(self) -> SyncPlan:"""重新判定并完成一次安全同步,供服务停机后的手动同步使用。"""- decision = plan(self.local, self.shared)- owner = writer_device(self.local, self.shared)- if (decision.action in ("push", "local-ahead")- and owner is not None and owner != self.device):- decision = SyncPlan(- "conflict", f"当前写入端是 {owner},本机不能推送",- decision.local_generation, decision.shared_generation,- )+ decision = resolve(self.local, self.shared, self.device)self.status, self.detail = decision.action, decision.reasonif decision.action == "pull":self.pull()diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 4a499ce5d..29a4587fb 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport ctypesimport loggingimport os+import reimport subprocessimport sysimport threading@@ -23,7 +24,8 @@ from .config import ()from .mdns import lan_ipv4from .netwatch import NetworkChangeWatcher-from .versioning import VersionManager+from .sync import COPY_ACTIONS, SyncPlan, device_id, resolve+from .versioning import VersionManager, VersionSnapshotLOGGER = logging.getLogger(__name__)@@ -39,6 +41,26 @@ MACOS_TLS_PORT = 8443#:(scripts/setup_macos_port80.sh)。OPEN_URL = f"https://{MDNS_HOSTNAME}/"+#: LaunchAgent 的标签,和 `scripts/install_macos_agent.py` 里那个必须一致。+LAUNCH_AGENT_LABEL = "gg.lmd.peach.tray"++#: 改到这些路径就得重启托盘进程本身。托盘启动那一刻就把它们装进了内存,重启子服务+#: 追不上——「同步开发进度」之后菜单还是旧的,正是这个原因。+TRAY_SOURCES = (+ "src/peach/tray.py",+ "src/peach/menubar.py",+ "src/peach/versioning.py",+ "src/peach/certs.py",+ "src/peach/netwatch.py",+ "src/peach/config.py",+ "pyproject.toml",+)+++def tray_restart_required(changed_paths: tuple[str, ...]) -> bool:+ """这次更新动没动托盘自己的代码。"""+ return any(path in TRAY_SOURCES for path in changed_paths)+def enable_hidpi() -> str:"""Enable native sharp Win32 menus before pystray creates any windows."""@@ -148,11 +170,13 @@ class ServiceManager:popen: Callable[..., subprocess.Popen] = subprocess.Popen,health_get: Callable[..., httpx.Response] = httpx.get,run: Callable[..., subprocess.CompletedProcess] = subprocess.run,+ ledger_plan: Callable[[], SyncPlan] | None = None,) -> None:self.specs = specsself._popen = popenself._health_get = health_getself._run = run+ self._ledger_plan = ledger_plan or self._current_ledger_planself._owned: dict[str, subprocess.Popen] = {}self._logs: list[object] = []self._last_health: dict[str, tuple[bool, str]] = {@@ -262,10 +286,42 @@ class ServiceManager:self.start_missing()return self.wait_until_ready()+ @staticmethod+ def _current_ledger_plan() -> SyncPlan:+ return resolve(DATABASE_PATH, SHARED_DATABASE_PATH, device_id(STATE_DIR))++ def _ledger_shortcut(self, *, take_ownership: bool) -> tuple[bool, str] | None:+ """这次同步会不会真的复制?不会就别停服务。++ 原来的做法是无条件停服务、跑一遍 CLI、再启回来。共享盘没挂(`offline`)或者+ 本机压根不是写入端(`conflict`)时,那一停一启换来的只有一次白白的停机和一条+ 「同步失败」通知——实测就是本机的日常状态:`/Volumes/peach-sync` 没挂时,+ 点一次「同步 Ledger」网页就断十几秒,然后告诉你盘不可达。++ 「接管 Ledger 写入」只在共享盘不可达时短路:它要求两侧 `in-sync`,而 `in-sync`+ 对同步是无事可做、对接管却正是要做的那一次。+ """+ try:+ decision = self._ledger_plan()+ except OSError as exc: # 判定本身失败也不该拖着服务停机+ return False, f"未同步:无法判定账本状态({exc})"+ if take_ownership:+ if decision.action == "offline":+ return False, f"未接管:{decision.reason};先挂上共享副本所在的盘。"+ return None+ if decision.action in COPY_ACTIONS:+ return None+ if decision.action in ("offline", "conflict", "missing"):+ return False, f"未同步:{decision.reason}"+ return True, f"账本同步:{decision.action} · {decision.reason}"+def sync_ledger(self, executable: Path | None = None, *, take_ownership: bool = False,) -> tuple[bool, str]:"""停掉本托盘拥有的服务,单次同步后恢复;不碰别的进程拥有的服务。"""+ shortcut = self._ledger_shortcut(take_ownership=take_ownership)+ if shortcut is not None:+ return shortcutwith self._lock:external = []for spec in self.specs:@@ -592,6 +648,40 @@ class PeachTray:self._stop_event.set()+def launchd_owns_this_process(+ run: Callable[..., subprocess.CompletedProcess] = subprocess.run,+) -> bool:+ """本进程是不是 LaunchAgent 拉起的那一个。++ 判据是 launchd 报的 pid 等于自己的 pid,不是「plist 存在」。`kickstart -k` 只重启+ launchd 名下那一份;托盘要是从终端跑起来的,kickstart 会在旁边**再**起一个,+ 菜单栏上就出现两个桃子,而旧的那个还占着单实例锁。+ """+ result = run(+ ["launchctl", "print", f"gui/{os.getuid()}/{LAUNCH_AGENT_LABEL}"],+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,+ )+ if result.returncode != 0:+ return False+ match = re.search(r"^\s*pid\s*=\s*(\d+)", result.stdout or "", re.MULTILINE)+ return match is not None and int(match.group(1)) == os.getpid()+++def restart_tray_process(+ run: Callable[..., subprocess.CompletedProcess] = subprocess.run,+) -> subprocess.CompletedProcess:+ """让 launchd 杀掉并重新拉起托盘。调用方必须先停掉自己拥有的服务。++ 顺序不能反:先重启服务再 kickstart,新托盘会看到一组健康但不属于自己的服务,+ `_owned` 是空的,之后每次「同步 Ledger」都被自己的归属检查挡成+ 「服务不归本托盘管理」。+ """+ return run(+ ["launchctl", "kickstart", "-k", f"gui/{os.getuid()}/{LAUNCH_AGENT_LABEL}"],+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,+ )++def run_macos_menu_bar(manager: "ServiceManager") -> None:"""macOS 走原生菜单栏项。@@ -601,9 +691,12 @@ def run_macos_menu_bar(manager: "ServiceManager") -> None:from .menubar import MenuBarAppversions = VersionManager()- snapshot = versions.inspect()+ # 「同步开发进度」会把版本行写旧,所以标题读这个可变快照而不是闭包里那一份。+ # 不在标题里直接调 `inspect()`:它要开四次 git,而标题每 5 秒刷新一次。+ state: dict[str, VersionSnapshot] = {"snapshot": versions.inspect()}app: dict[str, object] = {}- sync_lock = threading.Lock()+ # 开发进度和账本共用一把锁:两者都会停服务,同时跑等于让两条路径抢同一组进程。+ action_lock = threading.Lock()def restart() -> None:manager.stop_owned()@@ -615,21 +708,65 @@ def run_macos_menu_bar(manager: "ServiceManager") -> None:if holder is not None:holder.stop()+ def notify(message: str, title: str) -> None:+ holder = app.get("app")+ if holder is not None:+ holder.notify(message, title)++ def sync_source() -> None:+ """把本地检出快进到更新通道,再让新代码真的跑起来。++ 和「同步 Ledger」分成两个按钮,因为它们除了名字里都有「同步」之外没有共同点:+ 走的是 GitHub 而不是 SMB 共享,任一方不可达都不该拖住另一方(本机常态就是+ 共享盘没挂而 GitHub 正常);快进失败什么都没变,账本同步失败却牵涉唯一写入端+ 和可能的数据取舍。合成一个按钮只会让「失败了」这句话失去意义。+ """+ if not action_lock.acquire(blocking=False):+ return++ def work() -> None:+ released = False+ try:+ notify("正在检查更新通道…", "Peach 开发进度")+ result = versions.update()+ state["snapshot"] = result.snapshot+ if result.state != "updated":+ notify(result.message, "Peach 开发进度")+ return+ if tray_restart_required(result.changed_paths):+ if launchd_owns_this_process():+ notify(f"{result.message}正在重启菜单栏项…", "Peach 开发进度")+ manager.stop_owned()+ action_lock.release() # kickstart 之后本进程就没了+ released = True+ restart_tray_process()+ return+ notify(+ f"{result.message}服务已重启;菜单栏项本身要手动退出重开才会生效。",+ "Peach 开发进度",+ )+ manager.restart()+ return+ manager.restart()+ notify(f"{result.message}服务已重启。", "Peach 开发进度")+ finally:+ if not released:+ action_lock.release()++ threading.Thread(target=work, name="PeachSourceSync", daemon=True).start()+def run_ledger_action(*, take_ownership: bool) -> None:- if not sync_lock.acquire(blocking=False):+ if not action_lock.acquire(blocking=False):returndef work() -> None:try:- holder = app.get("app")- if holder is not None:- action = "接管写入" if take_ownership else "同步"- holder.notify(f"正在安全停止服务并{action}…", "Peach Ledger")+ action = "接管写入" if take_ownership else "同步"+ notify(f"正在判定账本状态并{action}…", "Peach Ledger")ok, message = manager.sync_ledger(take_ownership=take_ownership)- if holder is not None:- holder.notify(message, "Peach Ledger" if ok else "Peach Ledger 同步失败")+ notify(message, "Peach Ledger" if ok else "Peach Ledger 同步失败")finally:- sync_lock.release()+ action_lock.release()threading.Thread(target=work, name="PeachLedgerSync", daemon=True).start()@@ -647,11 +784,13 @@ def run_macos_menu_bar(manager: "ServiceManager") -> None:(lambda: f"状态:{manager.status()}", None),(f"地址:{OPEN_URL}", None),(None, None),+ ("同步开发进度", sync_source),("同步 Ledger", sync_ledger),("接管 Ledger 写入", take_ownership),("重启服务", restart),("查看日志", lambda: subprocess.run(["open", str(LOG_DIR)], check=False)),- (lambda: f"版本 {snapshot.package_version} · {snapshot.build_label}", None),+ (lambda: f"版本 {state['snapshot'].package_version}"+ f" · {state['snapshot'].build_label}", None),(None, None),("退出 Peach", quit_now),],diff --git a/src/peach/versioning.py b/src/peach/versioning.pyindex f31266e5a..e0cbfc399 100644--- a/src/peach/versioning.py+++ b/src/peach/versioning.py@@ -59,6 +59,9 @@ class UpdateResult:snapshot: VersionSnapshotahead: int = 0behind: int = 0+ #: 这次快进改动了哪些仓库相对路径。只有 `updated` 会非空,调用方据此判断+ #: 光重启子服务够不够。+ changed_paths: tuple[str, ...] = ()class VersionManager:@@ -141,3 +144,44 @@ class VersionManager:state = "current"message = f"Peach {current.package_version} 已是当前更新通道的最新版本。"return UpdateResult(state, message, current, ahead=ahead, behind=behind)++ def update(self) -> UpdateResult:+ """把本地检出快进到更新通道,只做快进。++ 不 stash、不 rebase、不 `--force`:并行工作树和主检出共用同一个对象库与+ reflog,任何一种改写历史的「顺手解决」都会把别的分支一起拖下水。凡是快进+ 做不到的,一律原样报出来交给人。++ `check()` 已经 fetch 过并给出了状态,这里只在 `available` 时才动工作区;+ 其余状态(未配置、无跟踪分支、已最新、本地领先、两边分叉)直接透传,+ 调用方不需要再分一次类。+ """+ checked = self.check()+ if checked.state != "available":+ return checked+ snapshot = checked.snapshot+ if snapshot.dirty:+ return UpdateResult(+ "blocked",+ f"更新通道有 {checked.behind} 个新提交,但本地检出有未提交修改;"+ "先处理掉再同步。",+ snapshot, behind=checked.behind,+ )+ before = self._text("rev-parse", "HEAD")+ merged = self._git("merge", "--ff-only", str(snapshot.upstream), timeout=60)+ if merged.returncode != 0:+ return UpdateResult(+ "blocked",+ f"无法快进到 {snapshot.upstream};本地检出未改变,需要人工处理。",+ snapshot, behind=checked.behind,+ )+ current = self.inspect()+ changed = tuple(+ line for line in self._text("diff", "--name-only", f"{before}..HEAD").splitlines()+ if line+ )+ return UpdateResult(+ "updated",+ f"已同步 {checked.behind} 个提交:{before[:8]} → {current.commit}。",+ current, behind=checked.behind, changed_paths=changed,+ )diff --git a/tests/test_sync.py b/tests/test_sync.pyindex 2fab40716..2d95e2650 100644--- a/tests/test_sync.py+++ b/tests/test_sync.py@@ -10,6 +10,7 @@ from peach.sync import (local_dirty,plan,read_marker,+ resolve,writer_device,write_marker,)@@ -167,6 +168,60 @@ class PlanTests(unittest.TestCase):self.assertEqual(plan(self.local, self.shared).action, "local-ahead")+class ResolveTests(unittest.TestCase):+ """`resolve` 必须和 `synchronize_now` 得出同一个结论,且一个文件都不碰。++ 托盘拿它决定要不要停服务。判错的代价不是报错而是停机:`plan()` 说 `local-ahead`+ 但本机不是写入端时,真跑一次只会得到 conflict,那次停机纯属白停。+ """++ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.root = Path(self._tmp.name)+ self.local = self.root / "local" / "ledger.db"+ self.shared = self.root / "shared" / "ledger.db"+ self.addCleanup(self._tmp.cleanup)++ def test_a_reader_with_local_writes_resolves_to_conflict_not_a_push(self):+ make_db(self.local, 2)+ make_db(self.shared, 2)+ write_marker(self.local, Marker(7, "win", "", 0, 0))+ write_marker(self.shared, Marker(7, "win", "", 0, 0))+ make_db(self.local, 3)++ self.assertEqual(plan(self.local, self.shared).action, "local-ahead")+ decision = resolve(self.local, self.shared, "mac")+ self.assertEqual(decision.action, "conflict")+ self.assertIn("win", decision.reason)++ def test_the_writer_still_resolves_to_a_push(self):+ make_db(self.local, 2)+ make_db(self.shared, 2)+ write_marker(self.local, Marker(7, "mac", "", 0, 0))+ write_marker(self.shared, Marker(7, "mac", "", 0, 0))+ make_db(self.local, 3)+ self.assertEqual(resolve(self.local, self.shared, "mac").action, "local-ahead")++ def test_resolve_matches_what_synchronize_now_does_and_copies_nothing(self):+ make_db(self.local, 2)+ make_db(self.shared, 5)+ write_marker(self.local, Marker(7, "win", "", 0, 0))+ write_marker(self.shared, Marker(8, "win", "", 0, 0))++ decision = resolve(self.local, self.shared, "mac")+ self.assertEqual(decision.action, "pull")+ self.assertEqual(count(self.local), 2) # 只读判定,没复制++ applied = LedgerSync(self.local, self.shared, "mac", interval=0).synchronize_now()+ self.assertEqual(applied.action, decision.action)+ self.assertEqual(count(self.local), 5)++ def test_an_unreachable_share_resolves_to_offline(self):+ make_db(self.local, 1)+ self.assertEqual(+ resolve(self.local, self.root / "gone" / "ledger.db", "mac").action, "offline")++class LedgerSyncTests(unittest.TestCase):def setUp(self):self._tmp = tempfile.TemporaryDirectory()diff --git a/tests/test_tray.py b/tests/test_tray.pyindex 1c1746e88..acd296ed8 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -1,4 +1,5 @@import importlib.util+import inspectimport osimport plistlibimport sys@@ -24,7 +25,9 @@ from peach.config import SECRETS_DIRfrom peach.tray import (AlreadyRunning, PeachTray, ServiceManager, ServiceSpec, SingleInstance,apply_macos_template, build_service_specs, create_icon, enable_hidpi,+ launchd_owns_this_process, restart_tray_process, tray_restart_required,)+from peach.sync import SyncPlanfrom peach.versioning import UpdateResult, VersionSnapshot@@ -204,7 +207,10 @@ class ServiceStatusTests(unittest.TestCase):process = Mock()process.poll.return_value = Nonecompleted = Mock(returncode=0, stdout="账本同步:in-sync · 两侧已经一致\n", stderr="")- manager = ServiceManager((spec,), popen=Mock(return_value=process), run=Mock(return_value=completed))+ manager = ServiceManager(+ (spec,), popen=Mock(return_value=process), run=Mock(return_value=completed),+ ledger_plan=lambda: SyncPlan("pull", "共享副本更新"),+ )manager._owned["http"] = processwith patch.object(manager, "healthy", return_value=True), patch.object(manager, "start_missing"@@ -224,9 +230,12 @@ class ServiceStatusTests(unittest.TestCase):)def test_take_ownership_is_an_explicit_ledger_command(self):- manager = ServiceManager(tuple(), run=Mock(return_value=Mock(- returncode=0, stdout="账本同步:take-ownership\n", stderr="",- )))+ manager = ServiceManager(+ tuple(),+ run=Mock(return_value=Mock(+ returncode=0, stdout="账本同步:take-ownership\n", stderr="")),+ ledger_plan=lambda: SyncPlan("in-sync", "两侧一致"),+ )with patch.object(manager, "start_missing"), patch.object(manager, "wait_until_ready", return_value=True,):@@ -237,12 +246,122 @@ class ServiceStatusTests(unittest.TestCase):def test_manual_sync_refuses_a_healthy_unowned_service(self):spec = ServiceSpec("http", "http://127.0.0.1/healthz", ("peach", "serve"), True)runner = Mock()- manager = ServiceManager((spec,), health_get=lambda *args, **kwargs: Response(), run=runner)+ manager = ServiceManager(+ (spec,), health_get=lambda *args, **kwargs: Response(), run=runner,+ ledger_plan=lambda: SyncPlan("pull", "共享副本更新"),+ )ok, message = manager.sync_ledger(Path("/venv/peach"))self.assertFalse(ok)self.assertIn("不归本托盘管理", message)runner.assert_not_called()+ def test_an_unreachable_share_never_stops_the_services(self):+ """共享盘没挂时,停一遍服务再启回来换不到任何东西,只换来一次断网页。"""+ spec = ServiceSpec("http", "http://127.0.0.1/healthz", ("peach", "serve"), True)+ process = Mock()+ process.poll.return_value = None+ runner = Mock()+ manager = ServiceManager(+ (spec,), run=runner,+ ledger_plan=lambda: SyncPlan("offline", "共享副本所在的盘不可达,本地照常读写"),+ )+ manager._owned["http"] = process++ ok, message = manager.sync_ledger(Path("/venv/peach"))++ self.assertFalse(ok)+ self.assertIn("盘不可达", message)+ runner.assert_not_called()+ process.terminate.assert_not_called()++ def test_a_reader_that_cannot_push_is_reported_without_an_outage(self):+ """本机不是写入端时结论已经定了,跑一遍 CLI 也只会得到同一个 conflict。"""+ spec = ServiceSpec("http", "http://127.0.0.1/healthz", ("peach", "serve"), True)+ process = Mock()+ process.poll.return_value = None+ runner = Mock()+ manager = ServiceManager(+ (spec,), run=runner,+ ledger_plan=lambda: SyncPlan("conflict", "当前写入端是 host-88053062,本机不能推送"),+ )+ manager._owned["http"] = process++ ok, message = manager.sync_ledger(Path("/venv/peach"))++ self.assertFalse(ok)+ self.assertIn("不能推送", message)+ runner.assert_not_called()+ process.terminate.assert_not_called()++ def test_take_ownership_still_runs_when_the_two_sides_are_in_sync(self):+ """`in-sync` 对同步是无事可做,对接管却正是要做的那一次;短路不能一视同仁。"""+ manager = ServiceManager(+ tuple(),+ run=Mock(return_value=Mock(+ returncode=0, stdout="账本同步:take-ownership\n", stderr="")),+ ledger_plan=lambda: SyncPlan("in-sync", "两侧一致"),+ )+ with patch.object(manager, "start_missing"), patch.object(+ manager, "wait_until_ready", return_value=True,+ ):+ ok, _message = manager.sync_ledger(Path("/venv/peach"), take_ownership=True)+ self.assertTrue(ok)+ manager._run.assert_called_once()++ def test_take_ownership_refuses_early_when_the_share_is_unreachable(self):+ runner = Mock()+ manager = ServiceManager(+ tuple(), run=runner,+ ledger_plan=lambda: SyncPlan("offline", "共享副本所在的盘不可达,本地照常读写"),+ )+ ok, message = manager.sync_ledger(Path("/venv/peach"), take_ownership=True)+ self.assertFalse(ok)+ self.assertIn("先挂上共享副本所在的盘", message)+ runner.assert_not_called()+++class SourceSyncTests(unittest.TestCase):+ """「同步开发进度」这条路径:拉到的代码要真的跑起来,托盘不能自己骗自己。"""++ def test_only_tray_owned_modules_demand_a_tray_restart(self):+ self.assertFalse(tray_restart_required(("src/peach/web.py", "docs/STATUS.md")))+ self.assertTrue(tray_restart_required(("src/peach/web.py", "src/peach/menubar.py")))+ self.assertTrue(tray_restart_required(("pyproject.toml",)))+ self.assertFalse(tray_restart_required(()))++ def test_launchd_ownership_requires_a_matching_pid_not_just_a_loaded_job(self):+ """只看「作业已加载」会在终端启动的托盘上 kickstart 出第二个菜单栏图标。"""+ loaded_elsewhere = Mock(returncode=0, stdout="\tpid = 1\n\tstate = running\n")+ self.assertFalse(launchd_owns_this_process(Mock(return_value=loaded_elsewhere)))++ mine = Mock(returncode=0, stdout=f"\tpid = {os.getpid()}\n\tstate = running\n")+ self.assertTrue(launchd_owns_this_process(Mock(return_value=mine)))++ self.assertFalse(launchd_owns_this_process(+ Mock(return_value=Mock(returncode=113, stdout=""))))++ def test_the_menu_lists_source_sync_next_to_the_ledger_actions(self):+ """标签和位置是语义契约:菜单只有一条,写错了没有第二处会报错。"""+ from peach import tray as tray_module++ source = inspect.getsource(tray_module.run_macos_menu_bar)+ labels = [+ line.split('"')[1]+ for line in source.splitlines()+ if line.strip().startswith('("') and '",' in line+ ]+ self.assertIn("同步开发进度", labels)+ self.assertLess(labels.index("同步开发进度"), labels.index("同步 Ledger"))+ self.assertIn("sync_source", source)++ def test_tray_restart_asks_launchd_to_kill_and_relaunch_this_label(self):+ runner = Mock(return_value=Mock(returncode=0, stdout="", stderr=""))+ restart_tray_process(runner)+ self.assertEqual(+ runner.call_args.args[0],+ ["launchctl", "kickstart", "-k", f"gui/{os.getuid()}/gg.lmd.peach.tray"],+ )+@unittest.skipUnless(sys.platform == "darwin", "菜单栏图标与服务规格是 macOS 专属")class MacMenuBarTests(unittest.TestCase):diff --git a/tests/test_versioning.py b/tests/test_versioning.pyindex e2321aa4f..9162d48d5 100644--- a/tests/test_versioning.py+++ b/tests/test_versioning.py@@ -1,3 +1,4 @@+import contextlibimport osimport subprocessimport tempfile@@ -25,6 +26,32 @@ def initialize_repo(path: Path) -> None:class VersionManagerTests(unittest.TestCase):+ @contextlib.contextmanager+ def tracking_clone(self):+ """一个跟踪 origin/master 的检出,外加一份用来代表「另一台机器」的克隆。"""+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ remote, repo, other = root / "remote.git", root / "repo", root / "other"+ config = root / "gitconfig"+ config.write_text(+ "[safe]\n"+ + "".join(f"\tdirectory = {path.as_posix()}\n"+ for path in (repo, remote, other)),+ encoding="utf-8",+ )+ git_env = {"GIT_CONFIG_GLOBAL": str(config), "GIT_CONFIG_NOSYSTEM": "1"}+ with mock.patch.dict(os.environ, git_env):+ subprocess.run(["git", "init", "--bare", str(remote)],+ capture_output=True, check=True)+ initialize_repo(repo)+ git(repo, "remote", "add", "origin", str(remote))+ git(repo, "push", "-u", "origin", "master")+ subprocess.run(["git", "clone", str(remote), str(other)],+ capture_output=True, check=True)+ git(other, "config", "user.name", "Peach Tests")+ git(other, "config", "user.email", "[email protected]")+ yield repo, other, git_env+def test_repository_discovery_prefers_source_resource_root(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory)@@ -112,6 +139,67 @@ class VersionManagerTests(unittest.TestCase):self.assertEqual(result.behind, 1)self.assertEqual(before, after)+ def test_update_fast_forwards_and_reports_what_changed(self):+ with self.tracking_clone() as (repo, other, git_env):+ with mock.patch.dict(os.environ, git_env):+ (other / "feature.txt").write_text("new\n", encoding="utf-8")+ git(other, "add", "feature.txt")+ git(other, "commit", "-m", "remote feature")+ git(other, "push", "origin", "master")++ result = VersionManager(repo).update()++ self.assertEqual(result.state, "updated")+ self.assertEqual(result.behind, 1)+ self.assertEqual(result.changed_paths, ("feature.txt",))+ self.assertTrue((repo / "feature.txt").is_file())++ def test_update_is_a_no_op_when_already_current(self):+ with self.tracking_clone() as (repo, _other, git_env):+ with mock.patch.dict(os.environ, git_env):+ before = git(repo, "rev-parse", "HEAD").stdout.strip()+ result = VersionManager(repo).update()+ self.assertEqual(result.state, "current")+ self.assertEqual(result.changed_paths, ())+ self.assertEqual(git(repo, "rev-parse", "HEAD").stdout.strip(), before)++ def test_update_refuses_to_touch_a_dirty_checkout(self):+ """有未提交修改就停手。stash 会把别人正在改的东西卷进来,而托盘没人看着。"""+ with self.tracking_clone() as (repo, other, git_env):+ with mock.patch.dict(os.environ, git_env):+ (other / "feature.txt").write_text("new\n", encoding="utf-8")+ git(other, "add", "feature.txt")+ git(other, "commit", "-m", "remote feature")+ git(other, "push", "origin", "master")+ (repo / "version.txt").write_text("dirty\n", encoding="utf-8")++ before = git(repo, "rev-parse", "HEAD").stdout.strip()+ result = VersionManager(repo).update()++ self.assertEqual(result.state, "blocked")+ self.assertIn("未提交修改", result.message)+ self.assertEqual(git(repo, "rev-parse", "HEAD").stdout.strip(), before)+ self.assertEqual((repo / "version.txt").read_text(encoding="utf-8"), "dirty\n")++ def test_update_never_rewrites_history_when_the_branches_diverged(self):+ """两边分叉时只报,不 rebase 也不 reset:并行工作树共用同一个对象库。"""+ with self.tracking_clone() as (repo, other, git_env):+ with mock.patch.dict(os.environ, git_env):+ (other / "feature.txt").write_text("new\n", encoding="utf-8")+ git(other, "add", "feature.txt")+ git(other, "commit", "-m", "remote feature")+ git(other, "push", "origin", "master")+ (repo / "local.txt").write_text("mine\n", encoding="utf-8")+ git(repo, "add", "local.txt")+ git(repo, "commit", "-m", "local work")++ before = git(repo, "rev-parse", "HEAD").stdout.strip()+ result = VersionManager(repo).update()++ self.assertEqual(result.state, "diverged")+ self.assertEqual(git(repo, "rev-parse", "HEAD").stdout.strip(), before)+ self.assertFalse((repo / "feature.txt").exists())+if __name__ == "__main__":unittest.main()