From 4e4c027a6ca691b00df5dcb861765f023cd411be Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 16 Sep 2026 19:01:16 +0800 Subject: [PATCH 1/2] feat: offer updates in a window, and install without cutting anyone off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Checking for updates is now on by default. When there is a newer version, a small window says so instead of a notification that disappears; what it offers depends on how the app was installed. Downloaded from the web: one press installs. The app downloads, verifies the signature, waits for the gateway's in-flight requests to finish, replaces itself, and restarts, then says which version it came from. Waiting is the point: a restart cuts every stream still producing output, so a Claude Code task mid-response would lose that output and have to send the request again. The count comes from core 0.1.1's `in_flight`, is polled until it reaches zero, and is capped at three minutes so an update still happens under continuous load. The download comes first and the bundle is replaced last, so the files on disk never belong to a different version than the one running while it waits. Installed with Homebrew: the window gives the command and copies it, and the app never replaces itself. It asks the tap rather than the release page whether there is something newer, because the release page knows first — prompting then would give a `brew upgrade` with nothing to install. The command starts with `brew update`, since `brew upgrade` refreshes taps at most once a day on its own. The copy happens in Rust: the web clipboard API is refused in some webviews, and refused means a copy button that silently does nothing. A dismissed version is offered again after a day, not at the next six-hour check. A newer version is offered immediately. Development builds do not check on their own. Closing the update window no longer turns the app back into a menu-bar accessory while the main window is still open. Co-Authored-By: Claude Opus 5 --- README.md | 34 ++- README.zh-CN.md | 24 +- src-tauri/Cargo.lock | 346 ++++++++++++++++++++++- src-tauri/Cargo.toml | 10 +- src-tauri/capabilities/default.json | 6 +- src-tauri/src/lib.rs | 409 ++++++++++++++++++++++++---- src-tauri/src/update.rs | 176 +++++++++++- src/Update.tsx | 168 ++---------- src/UpdateWindow.tsx | 234 ++++++++++++++++ src/main.tsx | 19 +- src/ui/icons.tsx | 4 +- src/update.test.ts | 33 --- src/updateFlow.test.ts | 45 +++ src/updateFlow.ts | 77 ++++++ 14 files changed, 1311 insertions(+), 274 deletions(-) create mode 100644 src/UpdateWindow.tsx delete mode 100644 src/update.test.ts create mode 100644 src/updateFlow.test.ts create mode 100644 src/updateFlow.ts diff --git a/README.md b/README.md index cf16abdd..29468164 100644 --- a/README.md +++ b/README.md @@ -43,15 +43,31 @@ copying the app out of the disk image. ### Updates -Off by default. Turn it on under Settings and the app checks for a new version -every six hours, reading a manifest and downloading nothing else. A version it -does download is verified against a key compiled into the app before it -replaces anything. - -An app Homebrew installed does not replace itself — Homebrew records which -version it put in `/Applications`, and an app that overwrote that would be -written back over by the next `brew upgrade`. It says a new version exists and -leaves `brew upgrade --cask thinkwatch-lite` to do it. +The app looks for a new version two minutes after it starts and every six hours +after that, reading a small manifest and nothing else. It can be turned off +under Settings. + +When there is one, a small window says so, and what happens next depends on how +the app was installed. + +**Downloaded from the releases page:** one press on the install button does the +rest. The app downloads the update, verifies it against a key compiled into +itself, waits for the requests the gateway is serving to finish — up to three +minutes — then replaces itself and restarts. A Claude Code task in the middle +of a response is not cut off to make room for the update. + +**Installed with Homebrew:** the window gives the command to copy, and the app +never replaces itself. Homebrew records which version it put in `/Applications`; +an app that overwrote it would be written back over by the next `brew upgrade`. +The window only appears once the tap carries the new version, so the command +always has something to install: + +```bash +brew update && brew upgrade --cask thinkwatch-lite +``` + +`brew update` comes first because `brew upgrade` refreshes taps at most once a +day on its own. Or run it from source: diff --git a/README.zh-CN.md b/README.zh-CN.md index b036fea2..76603e69 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -41,13 +41,25 @@ xattr -dr com.apple.quarantine "/Applications/ThinkWatch Lite.app" ### 更新 -默认不开。在「设置」里打开之后,每六小时检查一次,只读取一份版本清单,不 -下载其他任何内容。真去下载的那个包,在替换任何东西之前会先用编译进应用里 -的那把公钥验签。 +应用启动两分钟后检查一次有没有新版本,此后每六小时一次,只读取一份很小的 +版本清单。可以在「设置」里关闭。 -Homebrew 装的实例不自己替换:Homebrew 记着它放进 `/Applications` 的是哪一 -版,应用把它盖掉之后,下一次 `brew upgrade` 会把旧的那版写回来。这种情况下 -应用只提示有新版本,升级交给 `brew upgrade --cask thinkwatch-lite`。 +有新版本时会弹出一个小窗口,接下来怎么做取决于应用是怎么装上来的。 + +**从 release 页面下载安装的:**按一次安装按钮,剩下的全部自动完成 —— 下载 +更新包,用编译进应用里的公钥验签,等网关手上的请求结束(最多三分钟),然后 +替换并重新启动。正在输出的 Claude Code 任务不会为了更新被掐断在半截。 + +**用 Homebrew 安装的:**窗口给出更新命令和复制按钮,应用不会替换自己。 +Homebrew 记着它放进 `/Applications` 的是哪一版,应用把它盖掉之后,下一次 +`brew upgrade` 会把旧的那版写回来。这个窗口只在 tap 已经有新版本时才弹出, +所以给出的命令执行下去一定有东西可装: + +```bash +brew update && brew upgrade --cask thinkwatch-lite +``` + +前面要先 `brew update`:`brew upgrade` 自己最多一天才刷新一次 tap。 也可以从源码跑: diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 75b9adcf..aef59c03 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -56,6 +56,27 @@ dependencies = [ "derive_arbitrary", ] +[[package]] +name = "arboard" +version = "3.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "parking_lot", + "percent-encoding", + "windows-sys 0.60.2", + "wl-clipboard-rs", + "x11rb", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -345,6 +366,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -476,6 +503,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + [[package]] name = "combine" version = "4.6.8" @@ -588,6 +624,12 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -830,13 +872,19 @@ checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89" dependencies = [ "bit-set", "cssparser", - "foldhash", + "foldhash 0.2.0", "html5ever", "precomputed-hash", "selectors", "tendril", ] +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "dpi" version = "0.1.2" @@ -971,6 +1019,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "event-listener" version = "5.4.2" @@ -997,6 +1051,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -1032,6 +1092,12 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flate2" version = "1.1.10" @@ -1049,6 +1115,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -1284,6 +1356,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link 0.2.1", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1466,12 +1548,32 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -1753,6 +1855,20 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6506c6c10786659413faa717ceebcb8f70731c0a60cbae39795fdf114519c1a" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2140,6 +2256,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "muda" version = "0.19.3" @@ -2191,6 +2317,15 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "notify-rust" version = "4.17.0" @@ -2271,6 +2406,7 @@ dependencies = [ "block2", "objc2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation", ] @@ -2582,6 +2718,17 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap 2.14.2", +] + [[package]] name = "phf" version = "0.13.1" @@ -2666,7 +2813,7 @@ checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" dependencies = [ "base64 0.22.1", "indexmap 2.14.2", - "quick-xml", + "quick-xml 0.38.4", "serde", "time", ] @@ -2803,6 +2950,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.38.4" @@ -2812,6 +2971,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3908,6 +4076,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "tauri-plugin-clipboard-manager" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4136fb69d967753d000423d7e5f863f89bf949efbdfbecb43a580426a01a0194" +dependencies = [ + "arboard", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.20", +] + [[package]] name = "tauri-plugin-notification" version = "2.4.0" @@ -4123,11 +4306,15 @@ dependencies = [ "hyper", "hyper-util", "libc", + "reqwest", + "rustls", + "semver", "serde", "serde_json", "tauri", "tauri-build", "tauri-plugin-autostart", + "tauri-plugin-clipboard-manager", "tauri-plugin-notification", "tauri-plugin-shell", "tauri-plugin-updater", @@ -4187,6 +4374,20 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tiff" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.45" @@ -4526,6 +4727,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -4534,8 +4746,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.1.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.1.0#1a5641512d00add7fd9a1a98e679eeaf56a3865a" +version = "0.1.1" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.1.1#84c3435bafbfc35f3964a43e1909799a1c0a5eb3" dependencies = [ "serde", "serde_json", @@ -4806,6 +5018,76 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.1", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "563a85523cade2429938e790815fd7319062103b9f4a2dc806e9b53b95982d8f" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml 0.41.0", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + [[package]] name = "web-sys" version = "0.3.105" @@ -4917,6 +5199,12 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "winapi" version = "0.3.9" @@ -5414,6 +5702,24 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +[[package]] +name = "wl-clipboard-rs" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9651471a32e87d96ef3a127715382b2d11cc7c8bb9822ded8a7cc94072eb0a3" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix", + "thiserror 2.0.20", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "writeable" version = "0.6.4" @@ -5485,6 +5791,23 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + [[package]] name = "xattr" version = "1.6.1" @@ -5683,6 +6006,21 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "5.9.2" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f0f477a1..46f67ae2 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -23,7 +23,7 @@ tauri-plugin-shell = "2" # 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制 # 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从 # 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。 -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.1.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.1.1" } anyhow = "1" libc = "0.2" @@ -38,6 +38,14 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } tauri-plugin-notification = "2.4.0" tauri-plugin-updater = "2" +# Homebrew 那一档要去读 tap 里的 cask。**和更新器插件同一套 HTTP 与 TLS** +# —— 版本、特性都对齐它,所以这里不多编译任何东西;系统代理也跟着一起认。 +reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "system-proxy"] } +rustls = { version = "0.23", default-features = false, features = ["ring"] } +semver = "1" +# Homebrew 那一档的「复制命令」。**在 Rust 这边写剪贴板**,理由见 +# `update_copy_command`。 +tauri-plugin-clipboard-manager = "2" [profile.release] lto = "thin" diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index b16b922d..80294a8a 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,9 +1,10 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "\u4e3b\u7a97\u53e3\u7684\u80fd\u529b\u3002Tauri v2 \u7684 capability \u6f0f\u914d\u662f\u9759\u9ed8\u5931\u8d25 \u2014\u2014 \u52a0\u4e00\u4e2a\u65b0\u547d\u4ee4\u5c31\u8981\u56de\u6765\u786e\u8ba4\u8fd9\u91cc\u6709\u5b83\u3002start-dragging \u662f\u540c\u4e00\u4e2a\u5751\u7684\u5b9e\u4f8b\uff1a\u6807\u9898\u680f\u662f Overlay\uff0c\u6ca1\u6709\u4e00\u6761\u771f\u7684\u6807\u9898\u680f\u53ef\u4ee5\u6293\uff0c\u7a97\u53e3\u5168\u9760 data-tauri-drag-region \u79fb\u52a8\uff0c\u800c\u90a3\u6761\u6743\u9650\u4e0d\u5728 core:window \u7684\u9ed8\u8ba4\u96c6\u5408\u91cc\u3002\u5c11\u4e86\u5b83\u62d6\u62fd\u533a\u6beb\u65e0\u53cd\u5e94\uff0c\u4e5f\u4e0d\u62a5\u9519\u3002", + "description": "主窗口的能力。Tauri v2 的 capability 漏配是静默失败 —— 加一个新命令就要回来确认这里有它。start-dragging 是同一个坑的实例:标题栏是 Overlay,没有一条真的标题栏可以抓,窗口全靠 data-tauri-drag-region 移动,而那条权限不在 core:window 的默认集合里。少了它拖拽区毫无反应,也不报错。更新窗口(update)和主窗口共用这一份:它要按内容高度调自己的尺寸,所以多一条 set-size。", "windows": [ - "main" + "main", + "update" ], "permissions": [ "core:default", @@ -12,6 +13,7 @@ "core:window:allow-close", "core:window:allow-set-focus", "core:window:allow-start-dragging", + "core:window:allow-set-size", "core:app:allow-app-hide", "core:event:default", "core:tray:default", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 033a7653..3c7191bd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -833,27 +833,26 @@ fn app_info(app: tauri::AppHandle) -> serde_json::Value { /// 更新这件事的当前状态,一次说完。 /// /// 界面要问的从来不是「有没有新版本」一个问题,而是「我这一份是怎么装 -/// 上来的、它能不能自己更新、自动检查开着吗」—— 分成三个命令去问,界面 -/// 就得自己把三个答案拼成一句话,而拼错了没有东西会发现。 +/// 上来的、自动检查开着吗、手上有没有一个查到了还没装的版本」—— 分成几个 +/// 命令去问,界面就得自己把答案拼成一句话,而拼错了没有东西会发现。 #[derive(serde::Serialize)] struct UpdateView { /// 现在跑的是哪一版 version: String, /// 这一份是怎么装上来的 install: update::Install, - /// 它能不能自己把自己换掉 - can_self_update: bool, /// 自动检查开着吗 check_updates: bool, + /// 查到了、还没装的那一版 + offer: Option, } fn update_view(app: &tauri::AppHandle) -> UpdateView { - let install = update::kind(); UpdateView { version: app.package_info().version.to_string(), - install, - can_self_update: install.can_self_update(), + install: update::kind(), check_updates: update::load_prefs(&data_dir()).check_updates, + offer: app.state::().offer.lock().unwrap().clone(), } } @@ -876,10 +875,32 @@ struct Found { notes: Option, } -/// 去看有没有新版本。 +/// 更新在内存里的那点状态。 +#[derive(Default)] +struct Updates { + /// 查到了、还没装的那一版。更新窗口打开时读它,设置页也读它。 + offer: std::sync::Mutex>, + /// 上一次把更新窗口推到用户面前,是为哪一版、在什么时候。 + prompted: std::sync::Mutex>, + /// 正在装。**连点两下不能下载两份、替换两次。** + installing: std::sync::atomic::AtomicBool, +} + +/// 更新窗口要画的东西。 +#[derive(serde::Serialize)] +struct OfferView { + version: String, + notes: Option, + current: String, + install: update::Install, + /// Homebrew 那一档要执行的命令。**由这里给出,界面上不再写一遍** —— + /// 两处各写一份,改了其中一处,弹窗里复制出去的就是另一条。 + command: Option<&'static str>, +} + +/// 读发布页上的清单:最新的那一版比现在新吗。 /// -/// **这一步对所有安装方式都做。**读的是一份几百字节的清单,不下载任何 -/// 东西 —— Homebrew 装的那一份也该知道有新版本了,它只是不自己去装。 +/// 读的是一份几百字节的 JSON,不下载任何别的东西。 async fn look(app: &tauri::AppHandle) -> Result, String> { use tauri_plugin_updater::UpdaterExt; let u = app.updater().map_err(|e| e.to_string())?; @@ -890,46 +911,321 @@ async fn look(app: &tauri::AppHandle) -> Result, String> { })) } +/// 从网上读一段文本。 +/// +/// **和更新器插件同一套 TLS。**插件在它的第一次请求之前,把 ring 装成进程 +/// 默认的加密实现;这里做同样的事 —— 谁先跑到都一样,装过之后再装是空 +/// 操作。 +async fn fetch_text(url: &str) -> Result { + if rustls::crypto::CryptoProvider::get_default().is_none() { + let _ = rustls::crypto::ring::default_provider().install_default(); + } + let client = reqwest::Client::builder() + .user_agent("ThinkWatch-Lite") + .timeout(std::time::Duration::from_secs(30)) + .build() + .map_err(|e| e.to_string())?; + client + .get(url) + .send() + .await + .and_then(|r| r.error_for_status()) + .map_err(|e| e.to_string())? + .text() + .await + .map_err(|e| e.to_string()) +} + +/// 这一份现在有没有该装的新版本。 +/// +/// **Homebrew 那一档问的是 tap,不是发布页。**发版那一刻 latest.json 就有 +/// 了新版本,而 cask 要等 tap 的定时任务跟上;在那之前提示用户执行 +/// `brew upgrade`,他照做只会看到「已经是最新」。所以那一档以 cask 里的 +/// 版本为准;发布说明只在清单和 cask 说的是同一版时才带上。 +async fn find(app: &tauri::AppHandle) -> Result, String> { + if update::kind() != update::Install::Homebrew { + return look(app).await; + } + let current = app.package_info().version.to_string(); + let cask = fetch_text(update::CASK_URL).await?; + let Some(version) = update::cask_version(&cask) else { + return Err("cask 里读不出版本号".into()); + }; + if !update::newer(version, ¤t) { + return Ok(None); + } + let notes = look(app) + .await + .ok() + .flatten() + .filter(|f| f.version == version) + .and_then(|f| f.notes); + Ok(Some(Found { + version: version.to_string(), + notes, + })) +} + +const UPDATE_WINDOW: &str = "update"; + +/// 更新窗口。 +/// +/// **一个单独的小窗,不是主窗口里的一个对话框。**这是菜单栏应用:查到新 +/// 版本的那一刻,主窗口多半根本不存在 —— 为了说一句话把 1100×720 的整个 +/// 界面拉起来,用户点完「稍后」还得再去关一次主窗口。 +/// +/// **建出来先不显示。**页面画好、量出内容的高度之后,由前端自己亮出来; +/// 否则会先闪一下白窗,再跳一下尺寸。 +fn show_update_window(app: &tauri::AppHandle) -> tauri::Result<()> { + if let Some(w) = app.get_webview_window(UPDATE_WINDOW) { + w.show()?; + w.set_focus()?; + return Ok(()); + } + WebviewWindowBuilder::new(app, UPDATE_WINDOW, WebviewUrl::default()) + .title("软件更新") + // 宽度和前端 UpdateWindow.tsx 里的 WIDTH 是同一个数;高度由前端量完内容再定 + .inner_size(480.0, 220.0) + .resizable(false) + .minimizable(false) + .maximizable(false) + .center() + .visible(false) + .build()?; + Ok(()) +} + +/// 把查到的版本交给用户。 +/// +/// `asked` 表示是用户自己点的「立即检查」—— 那时不管上一次是什么时候提 +/// 的,都要给他看;自动检查才受「一天最多一次」的节制。 +fn present(app: &tauri::AppHandle, found: Found, asked: bool) { + let hub = app.state::(); + *hub.offer.lock().unwrap() = Some(found.clone()); + let _ = app.emit("update-found", found.clone()); + let now = std::time::Instant::now(); + let show = { + let mut last = hub.prompted.lock().unwrap(); + let show = asked || update::due(last.as_ref(), &found.version, now); + if show { + *last = Some(update::Prompted { + version: found.version, + at: now, + }); + } + show + }; + if show && let Err(e) = show_update_window(app) { + tracing::error!("更新窗口打不开:{e}"); + } +} + +/// 「立即检查」。查到了就把更新窗口拉起来。 #[tauri::command] async fn update_check(app: tauri::AppHandle) -> Result, String> { - look(&app).await + let found = find(&app).await?; + if let Some(f) = &found { + present(&app, f.clone(), true); + } + Ok(found) +} + +/// 更新窗口打开时来读:要画的是哪一版、这一份该怎么装。 +#[tauri::command] +fn update_pending(app: tauri::AppHandle) -> Option { + let found = app.state::().offer.lock().unwrap().clone()?; + let install = update::kind(); + Some(OfferView { + version: found.version, + notes: found.notes, + current: app.package_info().version.to_string(), + install, + command: (install == update::Install::Homebrew).then_some(update::BREW_UPGRADE), + }) +} + +/// 把 Homebrew 的更新命令放进剪贴板。 +/// +/// **在 Rust 这边写,不用网页的剪贴板接口。**后者要看 webview 给不给写入 +/// 权限,给不给、什么时候给,各个平台和版本不一样;被拒的时候它什么都不 +/// 做 —— 而对一个「一键复制」的按钮,点了没反应是它唯一不能有的表现。 +/// +/// 命令由这里给出,不从界面传进来:webview 只能复制这一条,拿不到一个 +/// 往剪贴板里写任意内容的口子。 +#[tauri::command] +fn update_copy_command(app: tauri::AppHandle) -> Result<(), String> { + use tauri_plugin_clipboard_manager::ClipboardExt; + app.clipboard() + .write_text(update::BREW_UPGRADE) + .map_err(|e| e.to_string()) +} + +/// 重启之前在数据目录里留一句「从哪一版换过来的」,起来之后读它。 +const UPDATED_FROM: &str = ".updated-from"; + +/// 等手上的请求结束,最多等多久。 +/// +/// 一次带长思考的回答流上一两分钟是常事;等得比这更久,多半是一直有新 +/// 请求接上来 —— 那时候不重启,更新就永远不会发生,而用户按过「下载并 +/// 安装」,他要的是它发生。 +const DRAIN_LIMIT: std::time::Duration = std::time::Duration::from_secs(180); + +/// 更新走到了哪一步。更新窗口按它换文案。 +#[derive(Clone, serde::Serialize)] +#[serde(tag = "step", rename_all = "snake_case")] +enum Step { + Downloading, + Waiting { in_flight: usize }, + Installing, + Restarting, } -/// 下载、验签、替换,然后重启。 +/// 等网关手上的请求都结束。 +/// +/// **重启会掐断所有还没结束的流**:一个正在吐字的 Claude Code 任务,那段 +/// 输出就没了,那个请求得从头再发一次。等计数归零,重启就落在两个请求 +/// 之间的空档里。 +/// +/// 问不到(core 不在跑、控制面没答应)就不等 —— 没有网关,也就没有要保护 +/// 的请求。 +async fn wait_for_quiet(app: &tauri::AppHandle, control: &ControlClient) { + let started = std::time::Instant::now(); + let mut waited = false; + loop { + let s = match control.status().await { + Ok(s) => s, + Err(e) => { + tracing::info!("更新:问不到网关的状态,不等({e:#})"); + return; + } + }; + if s.in_flight == 0 { + if waited { + tracing::info!("更新:请求都结束了,等了 {:?}", started.elapsed()); + } + return; + } + if started.elapsed() >= DRAIN_LIMIT { + tracing::warn!( + "更新:等了 {DRAIN_LIMIT:?} 还有 {} 个请求没结束,照常重启", + s.in_flight + ); + return; + } + if !waited { + tracing::info!( + "更新:网关手上还有 {} 个请求,等它们结束再重启", + s.in_flight + ); + waited = true; + } + let _ = app.emit( + "update-step", + Step::Waiting { + in_flight: s.in_flight, + }, + ); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } +} + +/// 下载、等手上的请求结束、替换、重启。**按一次之后不再问任何问题。** /// /// **Homebrew 装的一律拒绝。**理由在 `update` 模块开头。这里再挡一次,是 -/// 因为这是一条策略 —— 让它只靠界面上那个按钮不显示来维持,等于让一次 -/// 渲染的疏忽去降级用户的安装。 +/// 因为这是一条策略 —— 只靠界面上那个按钮不显示来维持,等于让一次渲染的 +/// 疏忽去降级用户的安装。 +/// +/// **先下载,再等,最后才替换。**反过来的话,磁盘上的包在等待的那几分钟 +/// 里已经是新版本了 —— 这期间 core 万一退出,守护会从磁盘上拉起一个和 +/// 正在运行的界面不是同一版的网关。 #[tauri::command] -async fn update_install(app: tauri::AppHandle) -> Result<(), String> { +async fn update_install( + app: tauri::AppHandle, + state: tauri::State<'_, AppState>, + hub: tauri::State<'_, Updates>, +) -> Result<(), String> { + use std::sync::atomic::Ordering; + use tauri_plugin_updater::UpdaterExt; + let install = update::kind(); if !install.can_self_update() { return Err(match install { update::Install::Homebrew => { - "这一份由 Homebrew 管理,更新请执行 brew upgrade --cask thinkwatch-lite".into() + format!("这一份由 Homebrew 管理,请执行:{}", update::BREW_UPGRADE) } - _ => "开发构建不自更新".into(), + _ => "开发构建不执行自动更新".into(), }); } - use tauri_plugin_updater::UpdaterExt; - let u = app.updater().map_err(|e| e.to_string())?; - let Some(up) = u.check().await.map_err(|e| e.to_string())? else { - return Err("已经是最新版本".into()); - }; + if hub.installing.swap(true, Ordering::SeqCst) { + return Err("更新已经在进行中".into()); + } + // 中途失败要把标记放回去,否则再点一次会被当成「已经在进行中」 + struct Release<'a>(&'a std::sync::atomic::AtomicBool); + impl Drop for Release<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::SeqCst); + } + } + let _release = Release(&hub.installing); + + let up = app + .updater() + .map_err(|e| e.to_string())? + .check() + .await + .map_err(|e| e.to_string())? + .ok_or_else(|| "已经是最新版本".to_string())?; + + let _ = app.emit("update-step", Step::Downloading); let h = app.clone(); - up.download_and_install( - move |chunk, total| { - let _ = h.emit("update-progress", (chunk, total)); - }, - || {}, - ) - .await - .map_err(|e| e.to_string())?; - // 换完就重启 —— 旧的那份代码还在内存里跑着,留着它只会让下一个问题 - // 变成「我到底在用哪一版」。 + let bytes = up + .download( + move |chunk, total| { + let _ = h.emit("update-progress", (chunk, total)); + }, + || {}, + ) + .await + .map_err(|e| format!("下载失败:{e}"))?; + + wait_for_quiet(&app, &state.control).await; + + let _ = app.emit("update-step", Step::Installing); + up.install(&bytes).map_err(|e| format!("安装失败:{e}"))?; + + // 起来之后说一声换到了哪一版。写不进去不影响更新本身。 + let _ = std::fs::write( + data_dir().join(UPDATED_FROM), + app.package_info().version.to_string(), + ); + let _ = app.emit("update-step", Step::Restarting); app.restart() } +/// 上一次是被更新重启的话,说一声换到了哪一版。 +/// +/// **只在版本真的变了时说。**标记是重启之前写下的;替换没成功、起来的 +/// 还是原来那一版的话,这句话就是假的。 +fn announce_update(app: &tauri::AppHandle) { + use tauri_plugin_notification::NotificationExt; + let marker = data_dir().join(UPDATED_FROM); + let Ok(from) = std::fs::read_to_string(&marker) else { + return; + }; + let _ = std::fs::remove_file(&marker); + let now = app.package_info().version.to_string(); + let from = from.trim(); + if from.is_empty() || from == now { + return; + } + let _ = app + .notification() + .builder() + .title(format!("已更新到 {now}")) + .body(format!("ThinkWatch Lite 已从 {from} 更新到 {now}。")) + .show(); +} + /// 开机自启现在是开着的吗。 /// /// **默认是关的,而且这不是「还没实现」,是产品决定。**一个装完就自己 @@ -1005,6 +1301,7 @@ pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_notification::init()) .plugin(tauri_plugin_updater::Builder::new().build()) + .plugin(tauri_plugin_clipboard_manager::init()) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_autostart::init( // LaunchAgent 模式:往 ~/Library/LaunchAgents 写一个 plist。 @@ -1044,6 +1341,8 @@ pub fn run() { update_state, set_update_check, update_check, + update_pending, + update_copy_command, update_install, autostart_enabled, set_autostart, @@ -1083,6 +1382,10 @@ pub fn run() { )); let supervising = Arc::new(std::sync::atomic::AtomicBool::new(false)); + app.manage(Updates::default()); + // 上一次是被更新重启的话,现在说一声 + announce_update(&handle); + app.manage(AppState { control: ControlClient::new(socket), supervisor: sup.clone(), @@ -1198,11 +1501,17 @@ pub fn run() { if let tauri::WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); let app = window.app_handle().clone(); + let closing = window.label().to_string(); let _ = window.destroy(); + // **只有最后一个窗口关掉时才退回菜单栏应用。**更新窗口关掉 + // 的时候主窗口可能还开着 —— 那时把 Dock 图标收掉,用户就没法 + // 用 ⌘Tab 切回那个窗口了。 #[cfg(target_os = "macos")] - become_accessory(&app); + if app.webview_windows().keys().all(|l| *l == closing) { + become_accessory(&app); + } #[cfg(not(target_os = "macos"))] - let _ = &app; + let _ = (&app, &closing); } }) .build(tauri::generate_context!()) @@ -1325,38 +1634,18 @@ async fn bridge_events(socket: PathBuf, app: tauri::AppHandle) { const UPDATE_FIRST_LOOK: std::time::Duration = std::time::Duration::from_secs(120); const UPDATE_EVERY: std::time::Duration = std::time::Duration::from_secs(6 * 60 * 60); -/// 开着自动检查的话,隔一阵看一次。 +/// 自动检查。查到了就把更新窗口推到用户面前。 /// -/// **同一个版本只提醒一次。**每六小时弹一次同样的通知,用户学会的是忽略 -/// 通知 —— 包括那些真该看的(和高危工具调用那条同一个理由)。 +/// **开发构建不自己去查。**每次 `tauri dev` 之后两分钟弹一个窗,写代码的 +/// 人学会的只是把它关掉。「立即检查」在开发构建里照样能用。 async fn update_loop(app: tauri::AppHandle) { - use tauri_plugin_notification::NotificationExt; - let mut told: Option = None; tokio::time::sleep(UPDATE_FIRST_LOOK).await; loop { // 每一轮都重读设置 —— 用户可能在跑着的时候把它关了,那时这个 // 循环要立刻听话,而不是等到下次启动。 - if update::load_prefs(&data_dir()).check_updates { - match look(&app).await { - Ok(Some(f)) => { - let _ = app.emit("update-found", f.clone()); - if told.as_deref() != Some(f.version.as_str()) { - told = Some(f.version.clone()); - let body = match update::kind() { - update::Install::Homebrew => { - "执行 brew upgrade --cask thinkwatch-lite 更新。" - } - update::Install::Standalone => "在「设置」中安装。", - update::Install::Dev => "这是开发构建,不自更新。", - }; - let _ = app - .notification() - .builder() - .title(format!("ThinkWatch Lite {} 可用", f.version)) - .body(body) - .show(); - } - } + if update::kind() != update::Install::Dev && update::load_prefs(&data_dir()).check_updates { + match find(&app).await { + Ok(Some(f)) => present(&app, f, false), Ok(None) => {} // 查不到就下次再说。**不告诉用户** —— 网络不通不是他此刻 // 要处理的事,而一句「检查更新失败」只会打断他在做的事。 diff --git a/src-tauri/src/update.rs b/src-tauri/src/update.rs index bea1ea68..2fabb1d9 100644 --- a/src-tauri/src/update.rs +++ b/src-tauri/src/update.rs @@ -20,6 +20,24 @@ const CASK: &str = "thinkwatch-lite"; /// Intel 时代的位置;自定义前缀装不了 cask,也就不会出现在这里。 const BREW_PREFIXES: [&str; 2] = ["/opt/homebrew", "/usr/local"]; +/// tap 里的 cask 文件。**Homebrew 那一档以它为准,不以 latest.json 为准。** +/// +/// 发版的那一刻 latest.json 就有了新版本,而 tap 要等它自己的定时任务把 +/// cask 跟上。在那之前告诉 Homebrew 的用户「有新版本,去 brew upgrade」, +/// 他照做之后 brew 只会回一句已经是最新 —— 一个弹窗给出的命令,执行下去 +/// 必须真的有用。 +pub const CASK_URL: &str = "https://raw.githubusercontent.com/ThinkWatchProject/homebrew-tap/main/Casks/thinkwatch-lite.rb"; + +/// Homebrew 的用户要执行的那一条。 +/// +/// **前面必须有 `brew update`。**`brew upgrade` 只在距离上次更新超过 +/// `HOMEBREW_AUTO_UPDATE_SECS`(默认 86400,一天)时才自己去拉 tap;在那 +/// 之前本地的 tap 还是旧的,它一样会回「已经是最新」。 +pub const BREW_UPGRADE: &str = "brew update && brew upgrade --cask thinkwatch-lite"; + +/// 同一个版本被「稍后」之后,隔多久再提。 +pub const REMIND_AFTER: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60); + /// 应用自己的设置文件,放在数据目录里。 /// /// **不是网关的配置。**`config.yaml` 有版本、有历史、能回滚,因为改错一行 @@ -113,16 +131,74 @@ pub fn kind() -> Install { } /// 应用自己的设置。 -#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +/// +/// 缺字段时取 [`Prefs::default`] 里的值,不是类型的零值 —— 对一个布尔来说 +/// 两者恰好相反。 +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(default)] pub struct Prefs { - /// 启动时以及此后每隔一段时间,去看有没有新版本。 + /// 启动之后以及此后每隔一段时间,去看有没有新版本。 /// - /// **出厂是关的。**一个装完就开始往外发请求的工具,用户没同意过 —— - /// 而这件事对它自己有好处,对用户只是「有人知道我装了这个」。 + /// **出厂是开的。**这个应用坐在每一个 AI 请求的必经之路上:脱敏规则、 + /// 工具调用的检查、对上游的兼容,修好一处都要用户换到那一版才生效,而 + /// 一个停在旧版本上的网关,用户自己是看不出来的。检查本身只读一份版本 + /// 清单,不带任何本机的内容;不需要的话在「设置」里关掉。 pub check_updates: bool, } +impl Default for Prefs { + fn default() -> Self { + Self { + check_updates: true, + } + } +} + +/// 从 cask 文件里读出版本号。 +/// +/// 只认 `version "x"` 这一种写法。`version :latest` 之类不带具体版本的 +/// 写法读出来是 `None` —— 那种 cask 没法比新旧,也就不该弹窗。 +pub fn cask_version(text: &str) -> Option<&str> { + text.lines().find_map(|l| { + let rest = l.trim_start().strip_prefix("version \"")?; + rest.split('"').next().filter(|v| !v.is_empty()) + }) +} + +/// `candidate` 比 `current` 新吗。 +/// +/// **按语义化版本比,不按字符串比** —— 按字符串,2026.9.10 比 2026.9.9 旧。 +/// 任何一边解析不了都算「不新」:拿不准的时候不弹窗。 +pub fn newer(candidate: &str, current: &str) -> bool { + match ( + semver::Version::parse(candidate), + semver::Version::parse(current), + ) { + (Ok(a), Ok(b)) => a > b, + _ => false, + } +} + +/// 上一次弹窗是为哪个版本、在什么时候。 +#[derive(Debug, Clone)] +pub struct Prompted { + pub version: String, + pub at: std::time::Instant, +} + +/// 这一次该不该把更新窗口推到用户面前。 +/// +/// **新版本立刻提,同一个版本一天最多一次。**用户点过「稍后」,六小时后 +/// 下一轮检查又把同一个窗口推到他面前,那是在跟他较劲;而一直不再提, +/// 一个开着几周不重启的菜单栏应用就永远停在旧版本上。 +pub fn due(last: Option<&Prompted>, version: &str, now: std::time::Instant) -> bool { + match last { + None => true, + Some(p) if p.version != version => true, + Some(p) => now.saturating_duration_since(p.at) >= REMIND_AFTER, + } +} + fn prefs_path(dir: &Path) -> PathBuf { dir.join(PREFS_FILE) } @@ -237,9 +313,28 @@ mod tests { } #[test] - fn with_no_settings_file_the_check_is_off() { + fn with_no_settings_file_the_check_is_on() { let dir = tmp(); + assert!(load_prefs(&dir).check_updates); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// 关掉之后存得住。**这一条防的是 `#[serde(default)]` 的一个坑**: + /// 默认值改成开之后,缺字段时取的是 `Default` 而不是布尔的零值,而 + /// 用户写下的 `false` 必须照样被读成 `false`。 + #[test] + fn turning_the_check_off_is_remembered() { + let dir = tmp(); + save_prefs( + &dir, + &Prefs { + check_updates: false, + }, + ) + .unwrap(); assert!(!load_prefs(&dir).check_updates); + std::fs::write(prefs_path(&dir), b"{}").unwrap(); + assert!(load_prefs(&dir).check_updates, "缺字段取默认值,也就是开"); std::fs::remove_dir_all(&dir).unwrap(); } @@ -254,19 +349,70 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } - /// 文件坏了按出厂设置 —— 而出厂设置是**不检查**,不是检查。 + /// 文件坏了按出厂设置。 #[test] - fn a_corrupt_settings_file_falls_back_to_not_checking() { + fn a_corrupt_settings_file_falls_back_to_the_default() { let dir = tmp(); - save_prefs( - &dir, - &Prefs { - check_updates: true, - }, - ) - .unwrap(); std::fs::write(prefs_path(&dir), b"{ not json").unwrap(); - assert!(!load_prefs(&dir).check_updates); + assert_eq!(load_prefs(&dir), Prefs::default()); std::fs::remove_dir_all(&dir).unwrap(); } + + /// 读的是 tap 里真实的那份 cask —— 格式变了,这条先红。 + #[test] + fn the_version_comes_out_of_a_real_cask() { + let cask = r#"cask "thinkwatch-lite" do + version "2026.9.2" + sha256 "bccc9014b1b1df1fb4e33fa5534f1ccb7c431ac41a1b415aa932090c4dfd0cf4" + + url "https://github.com/ThinkWatchProject/ThinkWatch-Lite/releases/download/v#{version}/ThinkWatch-Lite-#{version}-arm64.dmg" +end +"#; + assert_eq!(cask_version(cask), Some("2026.9.2")); + assert_eq!( + cask_version("cask \"x\" do\n version :latest\nend\n"), + None + ); + assert_eq!(cask_version(""), None); + } + + #[test] + fn versions_compare_as_numbers_not_as_text() { + assert!(newer("2026.9.10", "2026.9.9"), "按字符串比会判反"); + assert!(newer("2026.10.0", "2026.9.9")); + assert!(!newer("2026.9.2", "2026.9.2")); + assert!(!newer("2026.9.1", "2026.9.2")); + // 拿不准就当不新 —— 不为一个读不懂的版本号弹窗 + assert!(!newer("latest", "2026.9.2")); + assert!(!newer("2026.9.3", "not-a-version")); + } + + #[test] + fn the_same_version_is_offered_at_most_once_a_day() { + let t0 = std::time::Instant::now(); + assert!(due(None, "2026.9.3", t0), "从没提过就提"); + + let last = Prompted { + version: "2026.9.3".into(), + at: t0, + }; + let six_hours = t0 + std::time::Duration::from_secs(6 * 3600); + assert!( + !due(Some(&last), "2026.9.3", six_hours), + "点过「稍后」,下一轮检查不再推同一个" + ); + assert!(due(Some(&last), "2026.9.3", t0 + REMIND_AFTER)); + assert!( + due(Some(&last), "2026.9.4", six_hours), + "又出了一个新版本,立刻提" + ); + } + + /// 本地的 tap 可能是一天前的,没有 `brew update` 的话,这条命令会回 + /// 「已经是最新」—— 而弹窗刚说有新版本。 + #[test] + fn the_brew_command_refreshes_the_tap_first() { + assert!(BREW_UPGRADE.starts_with("brew update && ")); + assert!(BREW_UPGRADE.ends_with("brew upgrade --cask thinkwatch-lite")); + } } diff --git a/src/Update.tsx b/src/Update.tsx index ec6b1508..f2173d55 100644 --- a/src/Update.tsx +++ b/src/Update.tsx @@ -1,126 +1,55 @@ -import { useCallback, useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { Button } from "@/ui/button"; import { Field, FieldContent, FieldDescription, FieldLabel } from "@/ui/field"; -import { Progress } from "@/ui/progress"; import { Spinner } from "@/ui/spinner"; import { Switch } from "@/ui/switch"; import { toast } from "sonner"; - -/** 这一份是怎么装上来的。决定更新由谁做。 */ -export type Install = "homebrew" | "standalone" | "dev"; - -export interface UpdateView { - version: string; - install: Install; - can_self_update: boolean; - check_updates: boolean; -} - -export interface Found { - version: string; - notes?: string | null; -} +import type { Found, UpdateView } from "./updateFlow"; /** - * 有新版本的时候,这一档该怎么装。 + * 设置里的「更新」。 * - * **Homebrew 装的那一份不给安装按钮。**它不是「这里暂时没做」—— - * 应用自己把包换掉之后,Homebrew 记的版本号指向一个已经不在磁盘上的 - * 版本,下一次 `brew upgrade` 会把旧的那版盖回来。所以这一档只说该执行 - * 什么,由用户在自己的终端里做。 - */ -export function howToUpdate(install: Install): { can: boolean; how: string } { - switch (install) { - case "homebrew": - return { - can: false, - how: "这一份由 Homebrew 管理,在终端中执行下面这条命令完成更新。", - }; - case "standalone": - return { can: true, how: "下载并替换当前版本,完成后应用会重新启动。" }; - case "dev": - return { can: false, how: "当前运行的是开发构建,不执行自动更新。" }; - } -} - -/** 下载进度。总长未知时不画进度条 —— 一根假装知道的进度条比没有更糟。 */ -function Downloading({ done, total }: { done: number; total: number | null }) { - if (total == null) { - return ( -

- 正在下载…({(done / 1_048_576).toFixed(1)} MB) -

- ); - } - return ( -
- -

- {(done / 1_048_576).toFixed(1)} / {(total / 1_048_576).toFixed(1)} MB -

-
- ); -} - -/** - * 更新。 - * - * 三件事:现在是哪一版、要不要自动去看有没有新的、有新的时候怎么装。 - * 第三件取决于这一份是怎么装上来的,而那个判断在 Rust 里 —— 界面只是 - * 把它说出来。 + * **这里不装任何东西。**查到新版本时打开的是更新窗口 —— 自动检查查到的 + * 和这里手动查到的,走的是同一个窗口、同一套按钮。两处各有一套安装界面 + * 的话,其中一套迟早会和另一套说不一样的话。 */ export default function Update() { const [view, setView] = useState(null); - const [found, setFound] = useState(null); - /** 这次会话查过没有 —— 「已是最新版本」只有在真查过之后才该说。 */ + /** 这次打开设置页之后查过没有 —— 「已是最新版本」只有在真查过之后才该说 */ const [looked, setLooked] = useState(false); const [busy, setBusy] = useState(false); - const [progress, setProgress] = useState<[number, number | null] | null>(null); useEffect(() => { void invoke("update_state").then(setView).catch(() => {}); }, []); - // 后台那轮自动检查查到了也要在这里显示出来,而不是只弹一条通知 —— - // 通知划掉就没了,而用户来这一页正是为了处理它。 + // 后台那轮自动检查查到了,这里也要跟着显示 useEffect(() => { - const un = listen("update-found", (e) => { - setFound(e.payload); - setLooked(true); - }); + const un = listen("update-found", (e) => + setView((v) => (v ? { ...v, offer: e.payload } : v)), + ); return () => { void un.then((f) => f()); }; }, []); - // 载荷是「这一块多大、总共多大」,要自己累加 —— 事件报的是增量, - // 不是已下载总量。 - useEffect(() => { - const un = listen<[number, number | null]>("update-progress", (e) => { - const [chunk, total] = e.payload; - setProgress((p) => [(p?.[0] ?? 0) + chunk, total ?? p?.[1] ?? null]); - }); - return () => { - void un.then((f) => f()); - }; - }, []); + if (!view) return null; - const look = useCallback(async () => { + const look = async () => { setBusy(true); try { - setFound(await invoke("update_check")); + // 查到的话 Rust 那边会把更新窗口拉起来 + const found = await invoke("update_check"); + setView((v) => (v ? { ...v, offer: found } : v)); setLooked(true); } catch (e) { toast.error("检查更新失败:" + (typeof e === "string" ? e : String(e))); } finally { setBusy(false); } - }, []); - - if (!view) return null; - const { can, how } = howToUpdate(view.install); + }; return (
@@ -147,69 +76,24 @@ export default function Update() { 自动检查新版本 - 默认不开。打开后启动时检查一次,此后每六小时一次,只读取版本清单, - 不下载任何内容。 + 启动两分钟后检查一次,此后每六小时一次,只读取一份版本清单。有新版本时弹出更新窗口。 -
+
- {looked && !found && ( - - 已是最新版本 {view.version} - - )} + + {view.offer + ? `新版本 ${view.offer.version} 可用,当前 ${view.version}` + : looked + ? `已是最新版本 ${view.version}` + : `当前版本 ${view.version}`} +
- - {found && ( -
-

- 新版本 {found.version} - - 当前 {view.version} - -

- {found.notes && ( -

- {found.notes} -

- )} -

{how}

- {can ? ( - progress ? ( - - ) : ( - - ) - ) : ( - view.install === "homebrew" && ( - - brew upgrade --cask thinkwatch-lite - - ) - )} -
- )}
); } diff --git a/src/UpdateWindow.tsx b/src/UpdateWindow.tsx new file mode 100644 index 00000000..54a488de --- /dev/null +++ b/src/UpdateWindow.tsx @@ -0,0 +1,234 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { invoke } from "@tauri-apps/api/core"; +import { listen } from "@tauri-apps/api/event"; +import { getCurrentWindow, LogicalSize } from "@tauri-apps/api/window"; +import { Button } from "@/ui/button"; +import { Input } from "@/ui/input"; +import { Progress } from "@/ui/progress"; +import { Spinner } from "@/ui/spinner"; +import { IconCopied, IconCopy } from "@/ui/icons"; +import { canInstall, describeStep, type Offer, type Step } from "./updateFlow"; + +/** + * 窗口宽度。**高度跟着内容走** —— 发布说明有长有短,固定高度要么留白要么 + * 截断。 + * + * 宽度是被 Homebrew 那条命令定下来的:它要在一行里完整显示出来。一条要 + * 粘进终端去执行的命令,显示成「…upgrade --cask thinkwatc」是不行的 —— + * 用户看不全自己要执行的是什么。Rust 建窗口时用的是同一个数。 + */ +const WIDTH = 480; + +/** 「已复制」留多久 */ +const COPIED_MS = 2_000; + +/** + * 更新窗口。 + * + * 查到新版本时由 Rust 建出来:自动检查查到了,或者用户在设置里点了 + * 「立即检查」。窗口建出来时是隐藏的 —— 这里画好、量出高度之后再亮出来。 + * + * 画哪一种取决于这一份是怎么装上来的: + * + * · 从网页下载的:「下载并安装」,按一次之后不再问任何问题 —— 下载、 + * 等网关手上的请求结束、替换、重启,全部自动。 + * · Homebrew 装的:给出那条命令和复制按钮。更新交给 brew。 + * · 开发构建:只说明不自动更新。 + * + * **没有任何按钮默认获得焦点。**这个窗口是在用户做别的事时冒出来的; + * 他在终端里按下的回车,不该变成一次「下载并安装」。 + */ +export default function UpdateWindow() { + const [offer, setOffer] = useState(null); + const [step, setStep] = useState(null); + const [progress, setProgress] = useState<[number, number | null]>([0, null]); + const [failed, setFailed] = useState(null); + const [copied, setCopied] = useState(false); + const [copyFailed, setCopyFailed] = useState(false); + const body = useRef(null); + const command = useRef(null); + const shown = useRef(false); + + const load = useCallback(() => { + void invoke("update_pending").then(setOffer); + }, []); + + useEffect(load, [load]); + + // 窗口开着的时候又查到了更新的一版 —— 换成新的那一版 + useEffect(() => { + const un = listen("update-found", load); + return () => { + void un.then((f) => f()); + }; + }, [load]); + + useEffect(() => { + const a = listen("update-step", (e) => setStep(e.payload)); + // 事件报的是**这一块多大**,不是已下载总量,要自己累加 + const b = listen<[number, number | null]>("update-progress", (e) => { + const [chunk, total] = e.payload; + setProgress(([done, t]) => [done + chunk, total ?? t]); + }); + return () => { + void a.then((f) => f()); + void b.then((f) => f()); + }; + }, []); + + // 内容高度变了就跟着改窗口高度:出现进度条、出现错误、换了一版带着 + // 更长的说明。第一次量完才亮出窗口,不让人看见跳一下的那一帧。 + useEffect(() => { + const el = body.current; + if (!offer || !el) return; + const w = getCurrentWindow(); + const fit = () => { + const h = Math.ceil(el.getBoundingClientRect().height); + void w.setSize(new LogicalSize(WIDTH, h)).then(async () => { + if (shown.current) return; + shown.current = true; + await w.show(); + await w.setFocus(); + }); + }; + fit(); + const ro = new ResizeObserver(fit); + ro.observe(el); + return () => ro.disconnect(); + }, [offer]); + + const close = useCallback(() => void getCurrentWindow().close(), []); + + // Esc 等于「稍后」。安装已经开始的话关掉的只是窗口,更新照常进行 + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") close(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [close]); + + if (!offer) return null; + const busy = step !== null && failed === null; + + const install = async () => { + setFailed(null); + setProgress([0, null]); + setStep({ step: "downloading" }); + try { + await invoke("update_install"); + } catch (e) { + setStep(null); + setFailed(typeof e === "string" ? e : String(e)); + } + }; + + const copy = async () => { + setCopyFailed(false); + try { + await invoke("update_copy_command"); + setCopied(true); + setTimeout(() => setCopied(false), COPIED_MS); + } catch { + // 系统剪贴板没写进去。**把命令选中**,让 ⌘C 立刻能用,并且说出来 + command.current?.focus(); + command.current?.select(); + setCopyFailed(true); + } + }; + + return ( +
+
+
+

ThinkWatch Lite {offer.version} 可用

+

当前版本 {offer.current}

+
+ + {offer.notes && ( +

+ {offer.notes} +

+ )} + + {canInstall(offer.install) ? ( + <> + {busy ? ( +
+ {/* 知道总长才画进度条 —— 一根假装知道还剩多少的进度条比没有更糟 */} + {step?.step === "downloading" && progress[1] ? ( + + ) : null} +

+ {!(step?.step === "downloading" && progress[1]) && } + {step && describeStep(step, progress[0], progress[1])} +

+ {/* 这一步可能要几分钟,而且长短取决于用户自己的请求 */} + {step?.step === "waiting" && ( +

+ 关闭这个窗口不影响更新,完成后会发送一条通知。 +

+ )} +
+ ) : ( +

+ 下载完成后自动安装。网关会等手上的请求全部结束,再重新启动。 +

+ )} + {failed &&

{failed}

} + {!busy && ( +
+ + +
+ )} + + ) : offer.install === "homebrew" && offer.command ? ( + <> +

+ 这一份由 Homebrew 管理。在终端中执行以下命令完成更新: +

+ {/* + 命令占满整行,复制放进底下那排按钮里当主操作 —— 和另一档的 + 「稍后 / 下载并安装」同一个位置、同一个分量。按钮塞在输入框 + 里面的话,命令就只剩一截能显示。 + */} + e.currentTarget.select()} + /> + {copyFailed && ( +

没能写入剪贴板。命令已选中,按 ⌘C 复制。

+ )} +
+ + +
+ + ) : ( + <> +

当前运行的是开发构建,不执行自动更新。

+
+ +
+ + )} +
+
+ ); +} diff --git a/src/main.tsx b/src/main.tsx index 27481e02..e0aff1b5 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,10 +1,27 @@ import React from "react"; import ReactDOM from "react-dom/client"; +import { getCurrentWindow } from "@tauri-apps/api/window"; import App from "./App"; +import UpdateWindow from "./UpdateWindow"; import "./index.css"; +// 更新窗口和主窗口是同一份页面,按窗口的名字决定画哪一个。给一个小窗 +// 单独起一个入口,就要多维护一份构建配置和一份样式入口。 +// +// 取不到窗口名(页面不在 Tauri 里打开,比如直接用浏览器看 `pnpm dev`) +// 就当主窗口 —— 否则整个页面在第一行就白屏。 +function windowLabel(): string { + try { + return getCurrentWindow().label; + } catch { + return "main"; + } +} + +const Root = windowLabel() === "update" ? UpdateWindow : App; + ReactDOM.createRoot(document.getElementById("root")!).render( - + , ); diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index 9e7e0b92..90958e2d 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -1,5 +1,5 @@ /** - * 源列表和工具条的图标。 + * 应用里用到的图标。 * * **从手写换成了 lucide。**这里原来是十二个手画的 16px 描边图形 —— * 当时的理由是「不为九个图标引一个依赖」。而 `components.json` 里 @@ -27,3 +27,5 @@ export { Server as IconServer } from "lucide-react"; // 上游 —— 一摞机 export { KeyRound as IconKey } from "lucide-react"; // 密钥 —— 钥匙,不是锁 export { SlidersHorizontal as IconSettings } from "lucide-react"; // 设置 —— 推子,齿轮留给系统设置 export { PanelLeft as IconSidebar } from "lucide-react"; // 收起/展开源列表 +export { Copy as IconCopy } from "lucide-react"; // 复制 —— 两张叠着的纸 +export { Check as IconCopied } from "lucide-react"; // 已复制 —— 一个勾 diff --git a/src/update.test.ts b/src/update.test.ts deleted file mode 100644 index ec6b71d3..00000000 --- a/src/update.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { howToUpdate, type Install } from "./Update"; - -/** - * 这一条是产品决定,不是界面细节。 - * - * Homebrew 把应用移进 `/Applications`,并记下它放进去的是哪一版。应用 - * 自己把那个包换掉之后,那条记录指向的版本已经不在磁盘上了,而下一次 - * `brew upgrade` 会拿旧的那版盖回来 —— 用户什么都没做,被降了一级。 - * - * Rust 那一侧也挡着(`update_install` 对这一档直接返回错误)。这里再测 - * 一遍,是因为界面上多出一个安装按钮本身就是错的:它承诺了一件做不到 - * 的事,而用户要点下去才知道。 - */ -describe("谁来做更新", () => { - it("Homebrew 装的不给安装按钮", () => { - expect(howToUpdate("homebrew").can).toBe(false); - }); - - it("手工装的可以自己更新", () => { - expect(howToUpdate("standalone").can).toBe(true); - }); - - it("开发构建不自更新", () => { - expect(howToUpdate("dev").can).toBe(false); - }); - - /** 每一档都要说清接下来该做什么 —— 一个不能点的按钮旁边必须有出路 */ - it("每一档都给出一句说明", () => { - const all: Install[] = ["homebrew", "standalone", "dev"]; - for (const k of all) expect(howToUpdate(k).how.length).toBeGreaterThan(8); - }); -}); diff --git a/src/updateFlow.test.ts b/src/updateFlow.test.ts new file mode 100644 index 00000000..2f5c5171 --- /dev/null +++ b/src/updateFlow.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; +import { canInstall, describeStep } from "./updateFlow"; + +describe("谁能在窗口里直接装", () => { + /** + * 这一条是产品决定,不是界面细节:Homebrew 装的那一份自己替换之后, + * 下一次 `brew upgrade` 会把旧版本盖回来。Rust 那一侧也挡着。 + */ + it("Homebrew 装的不给安装按钮", () => { + expect(canInstall("homebrew")).toBe(false); + }); + + it("从网页下载的可以", () => { + expect(canInstall("standalone")).toBe(true); + }); + + it("开发构建不自己更新", () => { + expect(canInstall("dev")).toBe(false); + }); +}); + +describe("安装进行到哪一步", () => { + it("下载时报已下载和总大小", () => { + expect(describeStep({ step: "downloading" }, 7_550_000, 13_000_000)).toBe( + "正在下载 7.2 / 12.4 MB", + ); + }); + + /** 服务器没给总长时,「/ 0.0 MB」是在编一个数 */ + it("总长未知时不报总长", () => { + const text = describeStep({ step: "downloading" }, 7_550_000, null); + expect(text).toBe("正在下载 7.2 MB"); + expect(text).not.toContain("/"); + }); + + /** + * 等请求结束的那一段可能有几分钟。**不说在等什么,用户会以为卡住了** + * —— 而他很可能正是那个发请求的人。 + */ + it("等待时说清在等几个请求", () => { + expect(describeStep({ step: "waiting", in_flight: 2 }, 0, null)).toBe( + "等待 2 个进行中的请求结束", + ); + }); +}); diff --git a/src/updateFlow.ts b/src/updateFlow.ts new file mode 100644 index 00000000..193fbb38 --- /dev/null +++ b/src/updateFlow.ts @@ -0,0 +1,77 @@ +/** + * 更新流程在界面这一侧的类型和纯函数。 + * + * 更新窗口和设置页都用它们。**判断在 Rust 里**(这一份怎么装上来的、 + * 能不能自己装、该不该弹窗),这里只负责把 Rust 给的状态说成一句话。 + */ + +/** 这一份是怎么装上来的。决定更新由谁做。 */ +export type Install = "homebrew" | "standalone" | "dev"; + +/** 查到的新版本。 */ +export interface Found { + version: string; + notes?: string | null; +} + +/** 设置页读的那份状态。 */ +export interface UpdateView { + version: string; + install: Install; + check_updates: boolean; + offer: Found | null; +} + +/** 更新窗口要画的东西。 */ +export interface Offer { + version: string; + notes?: string | null; + current: string; + install: Install; + /** Homebrew 那一档要执行的命令。由 Rust 给出,界面上不再写一遍 */ + command?: string | null; +} + +/** 按下安装之后走到了哪一步。 */ +export type Step = + | { step: "downloading" } + | { step: "waiting"; in_flight: number } + | { step: "installing" } + | { step: "restarting" }; + +/** + * 这一档能不能在窗口里直接装。 + * + * **Homebrew 那一档不能。**应用自己把包换掉之后,Homebrew 记的版本指向 + * 一个已经不在磁盘上的版本,下一次 `brew upgrade` 会把旧的那版盖回来。 + * Rust 那一侧也挡着;这里再判断一次,是因为多出来的那个按钮本身就是错 + * 的 —— 它承诺了一件做不到的事,用户要点下去才知道。 + */ +export function canInstall(install: Install): boolean { + return install === "standalone"; +} + +const MB = 1_048_576; + +function mb(bytes: number): string { + return (bytes / MB).toFixed(1); +} + +/** + * 当前这一步说成一句话。 + * + * **总长未知时不报总长。**服务器没给 Content-Length 的时候,一句 + * 「7.2 / 0.0 MB」是在编一个数。 + */ +export function describeStep(step: Step, done: number, total: number | null): string { + switch (step.step) { + case "downloading": + return total ? `正在下载 ${mb(done)} / ${mb(total)} MB` : `正在下载 ${mb(done)} MB`; + case "waiting": + return `等待 ${step.in_flight} 个进行中的请求结束`; + case "installing": + return "正在安装"; + case "restarting": + return "正在重新启动"; + } +} From c9b108dbfb0cb8f52a3e86906f08b83ec3157ddc Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 16 Sep 2026 19:16:58 +0800 Subject: [PATCH 2/2] fix: stop the core and wait for it before restarting into an update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Running the update end to end on a real bundle showed the restart race: the app exited, the new app started and spawned a core, and the old core was still holding the lock — it only notices its parent is gone about a second later. The new core failed twice ("已经有一个 twcore 在跑") before a third attempt stuck. The gateway was down a second longer than it needed to be, and every update left two error blocks in the log. `Supervisor::stop_and_wait` sends SIGTERM and waits for the child to actually exit, with a SIGKILL fallback, before the app restarts. That needed a way to say "stopped on purpose, do not start another". `run_once` returned a bool, and `false` meant "go to safe mode" to the supervise loop — a deliberate stop would have started a safe-mode core to fight over the lock and brought the main window up over a restarting app. It now returns `Next::{Again, SafeMode, Stop}`, and the stop check comes before any crash accounting. Same scenario after the fix: SIGTERM, core exits 0 within 8 ms, the new app's first core binds the port under a second later, nothing fails. Co-Authored-By: Claude Opus 5 --- src-tauri/src/lib.rs | 14 ++-- src-tauri/src/supervisor/mod.rs | 141 ++++++++++++++++++++++++++++++-- 2 files changed, 143 insertions(+), 12 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3c7191bd..9570ff96 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1199,6 +1199,12 @@ async fn update_install( app.package_info().version.to_string(), ); let _ = app.emit("update-step", Step::Restarting); + // 先停掉 core、等它真的退出,再重启应用 —— 否则新起来的应用会先撞上 + // 旧 core 手里的锁。见 `Supervisor::stop_and_wait`。 + state + .supervisor + .stop_and_wait(std::time::Duration::from_secs(5)) + .await; app.restart() } @@ -2170,14 +2176,12 @@ async fn supervise(sup: Arc, app: tauri::AppHandle) { let mut safe = false; loop { match sup.run_once(safe).await { - Ok(true) => { + Ok(supervisor::Next::Again) => { let _ = app.emit("core-restarting", ()); continue; } - Ok(false) => { - if safe { - break; - } + Ok(supervisor::Next::Stop) => break, + Ok(supervisor::Next::SafeMode) => { // 进安全模式:**必须打断用户并自动开窗**。这时候网关 // 已经不转发了,他所有的 AI 客户端都在瞎。 safe = true; diff --git a/src-tauri/src/supervisor/mod.rs b/src-tauri/src/supervisor/mod.rs index b87e360a..026ea2c6 100644 --- a/src-tauri/src/supervisor/mod.rs +++ b/src-tauri/src/supervisor/mod.rs @@ -38,6 +38,17 @@ pub enum CoreState { Stopped, } +/// 一次 core 退出之后,守护循环下一步做什么。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Next { + /// 再起一个 + Again, + /// 连续失败太多,改用安全模式起 + SafeMode, + /// 不再起了:安全模式里的 core 也退出了,或者它是为了退出应用而被停掉的 + Stop, +} + pub struct Supervisor { binary: PathBuf, config: Option, @@ -51,6 +62,11 @@ pub struct Supervisor { /// 进安全模式,那是荒唐的。这个标志把「它崩了」和「我们让它退的」 /// 分开,而这两件事在 `wait()` 眼里长得一模一样。 intentional: Arc, + /// 为了退出应用而停的。**和 `intentional` 相反:退了就不再起。** + /// + /// 两者分开是因为对 `wait()` 来说它们还是长得一模一样 —— 而一个应该 + /// 立刻重起,一个应该一个都不再起。 + stopping: AtomicBool, } impl Supervisor { @@ -61,6 +77,7 @@ impl Supervisor { policy: Mutex::new(RestartPolicy::new()), state: watch::channel(CoreState::Stopped).0, intentional: Arc::new(AtomicBool::new(false)), + stopping: AtomicBool::new(false), } } @@ -127,6 +144,42 @@ impl Supervisor { Ok(()) } + /// 为了退出应用而停掉 core,**并且等它真的退出**。 + /// + /// 应用重启(装完更新)之前要用它。只是自己退出、让 core 靠 `--parent` + /// 发现父进程没了再跟着退是不够的:它要一秒左右才发现,而新起来的应用 + /// 这时已经在拉新的 core —— 锁还在旧的手里,新的连起几次都失败,网关 + /// 多停一秒,日志里多出几段「已经有一个 twcore 在跑」。这是实测出来的。 + /// + /// 超时还没退就强杀。**不在跑就什么都不做。** + pub async fn stop_and_wait(&self, timeout: Duration) { + let CoreState::Running { pid } = self.state() else { + return; + }; + self.stopping.store(true, Ordering::SeqCst); + let mut rx = self.watch(); + // SIGTERM 而不是 SIGKILL:给它机会把 socket 和 lock 文件清掉 —— + // 下一个 core 要的正是那把锁。 + #[cfg(unix)] + unsafe { + libc::kill(pid as i32, libc::SIGTERM); + } + let gone = async { + while matches!(*rx.borrow_and_update(), CoreState::Running { pid: p } if p == pid) { + if rx.changed().await.is_err() { + break; + } + } + }; + if tokio::time::timeout(timeout, gone).await.is_err() { + tracing::warn!(pid, ?timeout, "core 没按时退出,强杀"); + #[cfg(unix)] + unsafe { + libc::kill(pid as i32, libc::SIGKILL); + } + } + } + /// 拼命令行。 /// /// `--parent` 是「一个程序」这条原则的落点:**UI 没了 core 跟着退**。 @@ -151,9 +204,7 @@ impl Supervisor { } /// 一次「起、看着、它死了、决定下一步」的完整循环。 - /// - /// 返回 false 表示别再循环了(进了安全模式或被主动停掉)。 - pub async fn run_once(&self, safe: bool) -> anyhow::Result { + pub async fn run_once(&self, safe: bool) -> anyhow::Result { self.set(CoreState::Starting); let args = self.command_args(safe); let started = Instant::now(); @@ -173,12 +224,21 @@ impl Supervisor { // 的那个 —— 所以另外两个信号(socket 断开、心跳)不是冗余。 let status = child.wait().await?; let ran_for = started.elapsed(); + + // **先看是不是为了退出而停的。**这一条必须排在最前面:落到下面任何 + // 一个分支里,它都会被当成一次崩溃 —— 要么立刻再起一个去抢那把锁, + // 要么攒够次数进安全模式、把主窗口弹出来。 + if self.stopping.load(Ordering::SeqCst) { + tracing::info!(?status, "core 已按要求停止"); + self.set(CoreState::Stopped); + return Ok(Next::Stop); + } tracing::warn!(?status, ?ran_for, "core 退出"); if safe { // 安全模式下的 core 退出了,说明用户主动停的或者更严重的问题。 self.set(CoreState::Stopped); - return Ok(false); + return Ok(Next::Stop); } if self.intentional.swap(false, Ordering::SeqCst) { @@ -188,7 +248,7 @@ impl Supervisor { attempt: 0, in_ms: 0, }); - return Ok(true); + return Ok(Next::Again); } let mut policy = self.policy.lock().await; @@ -209,12 +269,12 @@ impl Supervisor { if !d.is_zero() { tokio::time::sleep(d).await; } - Ok(true) + Ok(Next::Again) } Decision::SafeMode => { self.set(CoreState::SafeMode); tracing::error!(failures, "连续失败太多,进安全模式"); - Ok(false) + Ok(Next::SafeMode) } } } @@ -281,4 +341,71 @@ mod tests { async fn state_starts_stopped() { assert_eq!(sup().state(), CoreState::Stopped); } + + /// 一个不管参数、一直跑到被信号杀掉的「core」。 + fn long_runner(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("tw-sup-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let bin = dir.join("fake-core"); + std::fs::write(&bin, "#!/bin/sh\nexec sleep 30\n").unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); + bin + } + + async fn until_running(s: &Supervisor) -> u32 { + let mut rx = s.watch(); + loop { + if let CoreState::Running { pid } = *rx.borrow_and_update() { + return pid; + } + tokio::time::timeout(Duration::from_secs(5), rx.changed()) + .await + .expect("core 迟迟没起来") + .unwrap(); + } + } + + /// 这一条是 `stop_and_wait` 存在的理由:为了重启应用而停的 core,**守护 + /// 循环不能把它当成一次崩溃**。当成崩溃的话,要么立刻再起一个去抢锁, + /// 要么进安全模式、把主窗口弹到正在重启的应用上。 + #[tokio::test] + async fn a_core_stopped_for_exit_is_not_restarted() { + let s = Arc::new(Supervisor::new(long_runner("stop"), None)); + let looped = { + let s = s.clone(); + tokio::spawn(async move { s.run_once(false).await.unwrap() }) + }; + until_running(&s).await; + + let t0 = Instant::now(); + s.stop_and_wait(Duration::from_secs(5)).await; + assert!( + t0.elapsed() < Duration::from_secs(5), + "SIGTERM 就该让它退出,不用等到强杀" + ); + assert_eq!(s.state(), CoreState::Stopped); + assert_eq!(looped.await.unwrap(), Next::Stop, "停下之后不再起"); + } + + #[tokio::test] + async fn stopping_what_is_not_running_returns_at_once() { + let s = sup(); + let t0 = Instant::now(); + s.stop_and_wait(Duration::from_secs(5)).await; + assert!(t0.elapsed() < Duration::from_millis(100)); + } + + /// 对照组:改配置那种重启照旧立刻再起 —— 两个标志没有串。 + #[tokio::test] + async fn a_requested_restart_still_comes_back() { + let s = Arc::new(Supervisor::new(long_runner("restart"), None)); + let looped = { + let s = s.clone(); + tokio::spawn(async move { s.run_once(false).await.unwrap() }) + }; + until_running(&s).await; + s.request_restart().await.unwrap(); + assert_eq!(looped.await.unwrap(), Next::Again); + } }