diff --git a/README.md b/README.md index b6f0c6e..a30325e 100644 --- a/README.md +++ b/README.md @@ -296,6 +296,8 @@ The update channel is this repository: a `releases` branch holding the installer Once a day at startup, and on demand from Settings -> **Updates**, Shift reads the manifest, compares versions with semver rules including prereleases, and offers a download. A downloaded installer is checked twice before it can be installed: exact byte length, then a recomputed SHA256 that must match the manifest. A mismatch deletes the file and says so, so nothing half-downloaded launches. Publishing is one command, `scripts/publish-release.sh`, and `docs/RELEASE.md` covers the manifest format, the flags, and the difference between the integrity the hash proves and the authenticity a signed manifest adds (`--key` plus a key baked in with `SHIFT_UPDATE_PUBKEY`). +**Install & relaunch** finishes the update without leaving the app. macOS replaces its own `.app` bundle from the downloaded disk image and Windows runs the same installer silently, both from a helper script that starts once Shift has quit and then opens the new copy - so a conversion is interrupted, but nothing is left half-installed and a failed swap reopens the copy you had. The tab states your operating system, architecture, running version and the feed it reads above everything else, so one screenshot explains any report about an update. + ## External dependencies Core conversion, radial menu, capture, and OCR work with nothing installed. These extend coverage: diff --git a/README.zh-CN.md b/README.zh-CN.md index 43d8a0b..557f3ec 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -298,6 +298,8 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供 Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。下载完成的安装包在安装前要通过两道校验:字节数完全一致,以及重新计算的 SHA256 与清单一致。任一不符即删除文件并明确报错,因此半成品永远不会被启动。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。 +**「安装并重启」让你在应用内完成升级**:macOS 会用下载好的磁盘镜像替换自己的 `.app`,Windows 会静默运行同一个安装程序,两者都由一个在 Shift 退出后才启动的辅助脚本执行,完成后自动打开新版本——正在进行的转换会被中断,但不会装到一半卡住,替换失败也会重新打开原来的版本。该标签页最上方依次显示本机系统、架构、当前版本与更新源,截一张图就能说明升级问题出在哪里。 + ## 外部依赖 核心转换、环形菜单、截图与 OCR 在零外部依赖的情况下即可工作。以下工具用于扩展能力边界: diff --git a/docs/RELEASE.md b/docs/RELEASE.md index f953fc3..70cdbfb 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -180,7 +180,8 @@ guessing at one. installed: the byte length must equal the manifest's `size`, and the recomputed SHA256 must equal the manifest's `sha256`. A mismatch deletes the file and reports the error, so a truncated or swapped installer never reaches the installer step. -4. **Install** runs the verified artifact; **Discard** removes it. When an update is +4. **Install & relaunch** applies the verified artifact and restarts Shift on it, as + described in the next section; **Discard** removes the download. When an update is available the tray menu gains a row that opens Settings on the Updates tab. Manifest `schema` is checked, and a newer schema than this build understands is refused @@ -189,6 +190,41 @@ manifest can name a platform an older app has never heard of. The Updates panel states which of the two properties the current feed satisfies, so an unsigned channel never looks signed. +## Applying an update + +Neither operating system lets a running program replace its own executable, so the work +belongs to a helper that outlives the app. `update_install` writes a script into the +download folder, starts it detached, and exits about half a second later; the script waits +for that pid to disappear and only then touches the installed copy. + +| Platform | What the helper does | +| --- | --- | +| macOS | Mounts the downloaded `.dmg`, `ditto`s the new bundle next to the old one, swaps them with two `mv` calls, removes the quarantine flag, detaches the image, and `open`s the result | +| Windows | Waits for `shift.exe` to leave the process table, runs the installer with `/S`, then starts the `shift.exe` the installer wrote | +| Linux, and a macOS binary run outside a bundle | Nothing is replaced; the artifact is opened instead, and the panel says so | + +Both scripts are written so a failure cannot end with Shift simply closed: every macOS +failure path still `open`s the bundle it had, and the swap is `move aside, move in`, so a +copy that fails halfway leaves the previous version where it was. Before the handoff +starts, macOS writes a probe file next to the bundle — a root-owned copy in +`/Applications` is reported as "open the downloaded installer yourself" rather than +quietly quitting on an update that could not be applied. + +The Windows installer is the same one a user runs by hand, so the update path cannot drift +from the manual one. Because the silent install comes from Shift itself, `${Silent}` skips +the interactive "Shift is running, close it?" box: the app already told the user it is +about to restart, and a box nobody can answer would abort the update. + +This is not a delta update and not a signature check on the running binary: the same +SHA256 gate that guards a manual install is the only integrity gate, and the manifest +signature rules in "Signing the channel" apply unchanged. + +Replacing the bundle gives it a new code-signing hash, and macOS keys permissions such as +Screen Recording to that hash. A release signed with the same identity as the copy it +replaces normally keeps its approvals; a locally signed build, where every build has its +own identity, can ask again after an update. That is the same consequence a manual +reinstall has, and it is why the notarized-build item in the roadmap is worth closing. + ## Trust boundary Two properties, two mechanisms: @@ -230,13 +266,13 @@ test, which is the proof that the check is real and not a pass-through. Checked against the live `releases` branch of this repository: -Version **0.1.1**, checked by downloading each artifact back from the raw endpoint rather +Version **0.1.2**, checked by downloading each artifact back from the raw endpoint rather than trusting the local copy: | Key | Artifact | Verified from the remote | | --- | --- | --- | -| `macos` | `Shift-macOS-universal.dmg` (55,479,751 B) | bytes downloaded, SHA256 matches the manifest | -| `windows` | `Shift-Setup-0.1.1-win-x64.exe` (24,545,040 B) | bytes downloaded, SHA256 matches the manifest | +| `macos` | `Shift-macOS-universal.dmg` (55,509,300 B) | bytes downloaded, SHA256 matches the manifest | +| `windows` | `Shift-Setup-0.1.2-win-x64.exe` (24,524,080 B) | bytes downloaded, SHA256 matches the manifest | | `windows-arm64` | not published | by choice — see "Supported release targets" | | `linux` | not published | by choice: Linux is a build target here, not a shipped product | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 9d880e0..2a6058c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -90,6 +90,14 @@ names what is still missing. `docs/RELEASE.md`. - Daily startup probe with a manual "check now", a progress readout, and a tray row that jumps to Settings → Updates. +- Installing happens inside the app: after the SHA256 gate, macOS replaces its own bundle + from the downloaded disk image and Windows runs the same NSIS installer with `/S`, each + from a detached helper that waits for this process to exit and then opens the new copy. + macOS was exercised end to end — a 0.1.1 bundle swapped by the published 0.1.2 image, + `codesign --verify --deep --strict` clean afterwards — including the failure path, where + a busy image left the old copy running instead of leaving Shift closed. The Windows + script is cross-built and its `${Silent}` gate compiles, but the restart itself needs + real hardware. See "Applying an update" in `docs/RELEASE.md`. - Signed and notarized macOS package: pending (builds are signed with a local identity). - Signed Windows installer: pending. - Manifest signing is done. `scripts/release-key.py` mints the release key, @@ -117,11 +125,11 @@ names what is still missing. nothing, so a stock Linux build still stops at "no artifact for this platform". No host here compiles the branch, so it was type-checked by temporarily disabling the other two arms; it has never run on a Linux desktop. -- The published channel was re-verified by hand against the live `releases` branch for - every release since: the 0.1.1 manifest's signature checks out against the baked key and - both artifacts (`macos`, `windows`) match their published size and SHA256. The - `windows-arm64` and `linux` keys are absent because only those two platforms are shipped. - See "State of the published channel" in `docs/RELEASE.md`. +- The published channel is re-verified by hand against the live `releases` branch with + every release: the 0.1.2 manifest's signature checks out against the baked key and both + artifacts (`macos`, `windows`) match their published size and SHA256 after being + downloaded back. The `windows-arm64` and `linux` keys are absent because only those two + platforms are shipped. See "State of the published channel" in `docs/RELEASE.md`. ## M6: Next desktop work diff --git a/package.json b/package.json index 32f9b58..11fcfe5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "shift", "private": true, - "version": "0.1.1", + "version": "0.1.2", "type": "module", "scripts": { "prepare:ocr": "bash scripts/prepare-ocr-assets.sh", diff --git a/scripts/windows-installer.nsi b/scripts/windows-installer.nsi index 5132a54..0cdbe46 100644 --- a/scripts/windows-installer.nsi +++ b/scripts/windows-installer.nsi @@ -120,11 +120,15 @@ Function .onInit ; Shift keeps a tray process alive and Windows refuses to overwrite a mapped ; EXE, so ask before closing a conversion the user may be waiting on. + ; A silent install comes from Shift itself, which has already said it is about to + ; restart, and nobody is there to answer a box: go straight to the taskkill. ${If} ${FileExists} "$INSTDIR\shift.exe" FindWindow $0 "" "${APP_NAME}" ${If} $0 != 0 - MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(close_shift)" IDOK +2 - Abort + ${IfNot} ${Silent} + MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(close_shift)" IDOK +2 + Abort + ${EndIf} ${EndIf} ${EndIf} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 39a7c45..b36f3b1 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3899,7 +3899,7 @@ dependencies = [ [[package]] name = "shift" -version = "0.1.1" +version = "0.1.2" dependencies = [ "base64 0.22.1", "calamine", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 2abd09e..23ffa5f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "shift" -version = "0.1.1" +version = "0.1.2" description = "A radial file utility with screenshot, recording and OCR." authors = ["Shift Contributors"] edition = "2021" diff --git a/src-tauri/src/update.rs b/src-tauri/src/update.rs index bb9d348..f6153e5 100644 --- a/src-tauri/src/update.rs +++ b/src-tauri/src/update.rs @@ -688,9 +688,163 @@ pub async fn update_download(app: AppHandle) -> Result { .map_err(|error| format!("Update download failed: {error}"))? } -/// Hand the verified installer to the system: mount the disk image on macOS, start -/// the installer on Windows, open the AppImage or package on Linux. The app never -/// replaces itself in place. +/// The `.app` bundle a macOS build is running from, or None when the binary was +/// started outside a bundle (a dev build, a raw `target/debug` run). The shape is +/// fixed by the bundle layout: `.app/Contents/MacOS/`. +fn bundle_path(exe: &Path) -> Option { + let contents = exe.parent()?.parent()?; + let bundle = contents.parent()?; + if contents.file_name()? != "Contents" { + return None; + } + bundle + .extension() + .filter(|ext| ext.eq_ignore_ascii_case("app"))?; + Some(bundle.to_path_buf()) +} + +#[cfg(target_os = "macos")] +#[cfg(target_os = "macos")] +/// Whether this copy can be replaced where it sits. The handoff moves the bundle +/// aside and moves a new one in, which needs write access to the folder holding it +/// rather than to the bundle: a copy in a root-owned folder is not replaceable, and +/// finding that out after quitting would leave the user with a closed app and an +/// update that did not happen. +fn can_replace(bundle: &Path) -> bool { + let parent = match bundle.parent() { + Some(parent) => parent, + None => return false, + }; + let probe = parent.join(format!(".shift-replace-{}", std::process::id())); + match fs::File::create(&probe) { + Ok(_) => { + let _ = fs::remove_file(&probe); + true + } + Err(_) => false, + } +} + +#[cfg(target_os = "macos")] +/// The macOS handoff: wait for this process to quit, then replace the bundle with +/// the one inside the downloaded disk image and open the new copy. Written as a +/// script because the copy can only happen once this process is gone. +/// +/// Every failure path ends with `open` on the bundle, so a handoff that cannot +/// finish leaves the previous copy running rather than leaving Shift closed. +fn macos_handoff(pid: u32, image: &Path, bundle: &Path, log: &Path) -> String { + format!( + r#"#!/bin/sh +pid="{pid}" +image="{image}" +bundle="{bundle}" +log="{log}" +while kill -0 "$pid" 2>/dev/null; do sleep 0.2; done +mount="$TMPDIR/Shift Updates/mount.$$" +[ -n "$TMPDIR" ] || mount="/tmp/Shift Updates/mount.$$" +mkdir -p "${{mount%/*}}" +if ! /usr/bin/hdiutil attach -nobrowse -readonly -mountpoint "$mount" "$image" >>"$log" 2>&1; then + echo "mount failed" >>"$log" + /usr/bin/open "$bundle" + exit 1 +fi +status=0 +if ! /usr/bin/ditto "$mount/Shift.app" "$bundle.new" >>"$log" 2>&1; then + status=1 +else + # A DMG fetched by a browser carries a quarantine flag, and an app copied out of + # one is re-assessed on next launch. This build is signed but not notarized, so + # drop the flag the same way a manual drag out of the image would. + /usr/bin/xattr -dr com.apple.quarantine "$bundle.new" 2>/dev/null + if mv "$bundle" "$bundle.old" >>"$log" 2>&1 && mv "$bundle.new" "$bundle" >>"$log" 2>&1; then + /bin/rm -rf "$bundle.old" + else + status=1 + [ -d "$bundle.old" ] && [ ! -d "$bundle" ] && mv "$bundle.old" "$bundle" >>"$log" 2>&1 + /bin/rm -rf "$bundle.new" + fi +fi +/usr/bin/hdiutil detach "$mount" -quiet >>"$log" 2>&1 +[ "$status" -eq 0 ] || echo "handoff failed; reopening the previous copy" >>"$log" +/usr/bin/open "$bundle" +exit "$status" +"#, + pid = pid, + image = image.display(), + bundle = bundle.display(), + log = log.display(), + ) +} + +/// The Windows handoff: wait for this process to exit, run the installer silently, +/// then start the copy the installer wrote. The installer refuses to overwrite a +/// running EXE, so the wait is the whole point of the script. +#[cfg(target_os = "windows")] +fn windows_handoff(pid: u32, installer: &Path, log: &Path) -> String { + format!( + r#"@echo off +setlocal EnableExtensions +set "WAIT_FOR={pid}" +set "INSTALLER={installer}" +set "LOG={log}" +set /a TRIES=0 +:waitloop +tasklist /FI "PID eq %WAIT_FOR%" /NH /FO CSV 2>nul | find /I "shift.exe" >nul || goto install +set /a TRIES+=1 +if %TRIES% LSS 100 (ping -n 2 127.0.0.1 >nul & goto waitloop) +:install +rem The installer writes its own directory to the registry; fall back to its default. +set "TARGET=%LOCALAPPDATA%\Programs\Shift\shift.exe" +for /f "tokens=1,2,*" %%a in ('reg query "HKCU\Software\Shift" /v InstallDirectory 2^>nul ^| find "InstallDirectory"') do set "TARGET=%%c\shift.exe" +start /wait "" "%INSTALLER%" /S +if errorlevel 1 echo installer exited with %ERRORLEVEL% >> "%LOG%" +if exist "%TARGET%" start "" "%TARGET%" +"#, + pid = pid, + installer = installer.display(), + log = log.display(), + ) +} + +/// Write a handoff script and start it detached, so it is still alive when this +/// process has exited. `name` is the file in the update directory. +fn spawn_handoff(name: &str, script: &str) -> Result<(), String> { + let path = download_directory().join(name); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + // A previous attempt leaves its script behind, and a half-written one would be + // inherited by the next install. + let _ = fs::remove_file(&path); + fs::write(&path, script).map_err(|error| error.to_string())?; + #[cfg(target_os = "windows")] + let mut command = crate::process::command("cmd.exe"); + #[cfg(target_os = "windows")] + command.args(["/D", "/C", &path.to_string_lossy().to_string()]); + #[cfg(not(target_os = "windows"))] + let mut command = crate::process::command("/bin/sh"); + #[cfg(not(target_os = "windows"))] + command.arg(&path); + command + .spawn() + .map_err(|error| format!("Could not start the updater: {error}"))?; + Ok(()) +} + +/// Quit shortly after the handoff is scheduled. The delay lets the invoke resolve +/// and the panel paint its installing state before the windows disappear. +fn quit_for_update(app: &AppHandle) { + let app = app.clone(); + thread::spawn(move || { + thread::sleep(Duration::from_millis(600)); + app.exit(0); + }); +} + +/// Install the verified artifact and restart on it. macOS replaces its own bundle +/// and Windows runs its installer silently, both from a helper that starts once +/// this process is gone, then opens the new copy. Anything else is handed to the +/// system the way a double-click would. #[tauri::command] pub async fn update_install(app: AppHandle) -> Result { let path = app @@ -701,22 +855,54 @@ pub async fn update_install(app: AppHandle) -> Result { .and_then(|guard| guard.as_ref().and_then(|status| status.path.clone())) .ok_or_else(|| "Download and verify an update first.".to_string())?; tauri::async_runtime::spawn_blocking(move || { + let artifact = PathBuf::from(&path); + let log = download_directory().join("handoff.log"); + let pid = std::process::id(); + + // A bundled macOS build replaces itself; `open`ing the disk image instead + // would leave the user dragging a window they were told to stop expecting. + #[cfg(target_os = "macos")] + { + let exe = std::env::current_exe().map_err(|error| error.to_string())?; + if let Some(bundle) = bundle_path(&exe) { + if !can_replace(&bundle) { + let folder = bundle + .parent() + .map_or_else(|| "its folder".to_string(), |parent| { + parent.to_string_lossy().to_string() + }); + return Err(format!( + "Shift cannot replace itself in {folder}. Open the downloaded installer to update by hand." + )); + } + let script = macos_handoff(pid, &artifact, &bundle, &log); + spawn_handoff("Shift-update.sh", &script)?; + quit_for_update(&app); + return Ok(path); + } + } + #[cfg(target_os = "windows")] + { + let script = windows_handoff(pid, &artifact, &log); + spawn_handoff("Shift-update.cmd", &script)?; + quit_for_update(&app); + return Ok(path); + } + // Reaching here means the update cannot be applied in place: a Linux build + // has no in-place install, and a macOS binary run straight out of `target/` + // has no bundle to replace. Both get the artifact opened instead. #[cfg(target_os = "macos")] crate::process::command("/usr/bin/open") - .arg(&path) + .arg(&artifact) .status() .map_err(|error| format!("Could not open the update: {error}"))?; - #[cfg(target_os = "windows")] - crate::process::command(&path) - .spawn() - .map_err(|error| format!("Could not start the installer: {error}"))?; // Linux bundles are not installed in place. An AppImage carries its own runtime // but arrives without the executable bit, which is enough to make a double-click // fail, so set that bit and start it directly. A .deb means nothing on its own // and goes to whatever handler the desktop registered for the package format. #[cfg(not(any(target_os = "macos", target_os = "windows")))] { - let bundle = PathBuf::from(&path); + let bundle = artifact.clone(); if bundle .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("appimage")) @@ -996,6 +1182,79 @@ mod tests { assert!(error.contains("schema"), "{error}"); } + #[test] + fn a_bundled_binary_finds_its_app_bundle() { + let exe = Path::new("/Applications/Shift.app/Contents/MacOS/shift"); + assert_eq!( + bundle_path(exe), + Some(PathBuf::from("/Applications/Shift.app")) + ); + } + + #[test] + fn a_binary_outside_a_bundle_has_no_bundle_to_replace() { + // `target/debug/shift` and a relocated executable must not be mistaken for + // an installed copy, because the handoff would then replace nothing. + assert_eq!(bundle_path(Path::new("/repo/target/debug/shift")), None); + assert_eq!(bundle_path(Path::new("/tmp/shift")), None); + } + + #[cfg(target_os = "macos")] + #[test] + fn the_macos_handoff_waits_for_this_process_before_it_touches_the_bundle() { + let script = macos_handoff( + 4242, + Path::new("/tmp/Shift Updates/Shift.dmg"), + Path::new("/Applications/Shift.app"), + Path::new("/tmp/handoff.log"), + ); + assert!(script.contains("pid=\"4242\""), "the script lost our pid"); + // The wait must come before any write to the bundle, or the copy races the + // running executable. + let wait = script.find("kill -0 \"$pid\"").expect("no wait loop"); + let replace = script + .find("mv \"$bundle\" \"$bundle.old\"") + .expect("no swap"); + assert!(wait < replace); + // A failed mount or copy still reopens the old copy: an update attempt must + // never end with Shift simply gone. + assert_eq!(script.matches("/usr/bin/open \"$bundle\"").count(), 2); + assert!(script.contains("hdiutil attach")); + assert!(script.contains("hdiutil detach")); + } + + #[cfg(target_os = "windows")] + #[test] + fn the_windows_handoff_installs_only_after_this_process_is_gone() { + let script = windows_handoff( + 4242, + Path::new("C:\\Users\\me\\Shift-Setup.exe"), + Path::new("C:\\tmp\\handoff.log"), + ); + assert!( + script.contains("set \"WAIT_FOR=4242\""), + "the script lost our pid" + ); + let wait = script + .find("tasklist /FI \"PID eq %WAIT_FOR%\"") + .expect("no wait"); + let install = script.find("\"%INSTALLER\" /S").expect("no silent install"); + assert!(wait < install); + assert!(script.contains("start \"\" \"%TARGET%\""), "never restarts"); + } + + #[cfg(target_os = "macos")] + #[test] + fn only_a_bundle_in_a_writable_folder_can_be_replaced() { + let dir = std::env::temp_dir().join(format!("shift-replace-test-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + assert!(can_replace(&dir.join("Shift.app"))); + // A bundle whose folder does not exist, or cannot be written, must be refused + // before the app quits rather than after. + assert!(!can_replace(&dir.join("missing").join("Shift.app"))); + let _ = fs::remove_dir(&dir); + } + #[test] fn the_status_reports_the_key_it_resolved() { // The UI shows this key next to the operating system, so it must be what the diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index fe7e96c..33cf2a6 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Shift", - "version": "0.1.1", + "version": "0.1.2", "identifier": "app.nex.shift", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/components/MainWindow.tsx b/src/components/MainWindow.tsx index 1422d89..8956998 100644 --- a/src/components/MainWindow.tsx +++ b/src/components/MainWindow.tsx @@ -1023,6 +1023,7 @@ export function MainWindow() { platform: runtimeInfo.platform, osVersion: runtimeInfo.osVersion, architecture: runtimeInfo.architecture, + appVersion: runtimeInfo.appVersion, } : null } diff --git a/src/components/UpdatePanel.tsx b/src/components/UpdatePanel.tsx index b73cd4e..cd6d672 100644 --- a/src/components/UpdatePanel.tsx +++ b/src/components/UpdatePanel.tsx @@ -1,10 +1,11 @@ import { Check, - Monitor, Download, LoaderCircle, + Monitor, PackageOpen, RefreshCw, + Rss, ShieldCheck, Sparkle, X, @@ -31,6 +32,8 @@ export interface UpdateSystemInfo { platform: string; osVersion: string; architecture: string; + /** Version of the copy the user is looking at, so the header needs no check. */ + appVersion: string; } /** Rust reports `std::env::consts::ARCH`; the channel names the same thing differently. */ @@ -50,8 +53,19 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P const { t } = useI18n(); // One state machine shared with any other view of the channel, driven by the // events Rust already broadcasts, so two views cannot offer different actions. - const { status, checking, downloading, installing, progress, percent, check, download, install, clear } = - useUpdateFlow(); + const { + status, + checking, + downloading, + installing, + installError, + progress, + percent, + check, + download, + install, + clear, + } = useUpdateFlow(); const verified = status?.state === "ready"; // Rust reports the key it resolved; the panel only repeats it. @@ -61,6 +75,48 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P return (
+ {/* The two facts an update answer has to be read against come first: which + machine and which Shift version is asking, then where updates come from. + Both precede the Updates heading so a screenshot of this panel already + says what was upgraded and from where. */} +
+
+ + {t("updateSystem")} + {system ? ( + + {system.osVersion || system.platform} + {architectureLabel(system.architecture)} + Shift {system.appVersion} + + ) : ( + {t("updateSystemPending")} + )} + {artifactKey ? ( + + {t("updateSystemArtifact", { key: artifactKey })} + + ) : status && status.state === "unavailable" ? ( + + {t("updateSystemArtifactUnknown")} + + ) : null} +
+
+ + {t("updateFeed")} + {/* Only a status backed by a manifest may claim anything about trust: an + errored check has no manifest to have verified. */} + {status && status.state !== "error" ? ( + + + {t(status.signed ? "updateSigned" : "updateUnsigned")} + + ) : null} + {feedUrl || t("updateFeedNone")} +
+
+
@@ -76,44 +132,7 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
-
- {t("updateFeed")} - {feedUrl || t("updateFeedNone")} - {/* Only a status backed by a manifest may claim anything about trust: an - errored check has no manifest to have verified. */} - {status && status.state !== "error" ? ( - - - {t(status.signed ? "updateSigned" : "updateUnsigned")} - - ) : null} -
- - {/* Which artifact the feed serves, and whether it can be installed at all, - are both decided by the host. Saying it here is what makes an "no artifact - for this platform" answer explain itself. */} -
- - {t("updateSystem")} - {system ? ( - - {system.osVersion || system.platform} - {architectureLabel(system.architecture)} - - ) : ( - {t("updateSystemPending")} - )} - {artifactKey ? ( - - {t("updateSystemArtifact", { key: artifactKey })} - - ) : status && status.state === "unavailable" ? ( - {t("updateSystemArtifactUnknown")} - ) : null} -
-
- {status?.currentVersion ?? "-"} {available && status ? ( @@ -172,6 +191,14 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
) : null} + {/* An install that could not run leaves the verified download in place, so it + is reported beside the button instead of rewriting the status. */} + {installError ? ( +
+ {installError} +
+ ) : null} +
{available && !verified ? ( ) : null} {verified ? ( diff --git a/src/i18n.ts b/src/i18n.ts index 0eb0891..92dc780 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -209,14 +209,15 @@ const messages: Record> = { updateUnavailable: "No artifact for this platform", updateDownload: "Download & verify", updateDownloading: "Downloading…", - updateInstall: "Install update", + updateInstall: "Install & relaunch", + updateInstalling: "Installing\u2026 Shift restarts when it is done", updateDiscard: "Discard", updateVerified: "SHA256 matched the manifest.", updateSigned: "Manifest signature verified against the release key.", updateUnsigned: "This build cannot verify a manifest signature, so the manifest is trusted through HTTPS alone. The SHA256 gate still applies.", updateAutoCheck: "Check for updates daily", updateBody: - "Releases come from this repository’s release branch. Every download is re-hashed and must match the manifest before it can be installed.", + "Releases come from this repository’s release branch. Every download is re-hashed and must match the manifest before it can be installed. Installing replaces this copy and restarts it; a conversion still running is interrupted.", radial: "Radial rings", radialKind: "File type preset", ringActions: "Actions", @@ -479,14 +480,15 @@ const messages: Record> = { updateUnavailable: "该平台没有对应安装包", updateDownload: "下载并校验", updateDownloading: "下载中…", - updateInstall: "安装更新", + updateInstall: "安装并重启", + updateInstalling: "正在安装…完成后 Shift 会自动重启", updateDiscard: "放弃", updateVerified: "SHA256 与清单一致。", updateSigned: "清单签名已用发布公钥验证通过。", updateUnsigned: "本构建内置的公钥无法验证清单签名,因此清单本身只依赖 HTTPS 通道的信任;SHA256 校验依然生效。", updateAutoCheck: "每天自动检查更新", updateBody: - "更新包来自本仓库的 release 分支。下载后会重新计算 SHA256,只有与清单一致才允许安装。", + "更新包来自本仓库的 release 分支。下载后会重新计算 SHA256,只有与清单一致才允许安装。安装会替换当前版本并自动重启,正在进行的转换会被中断。", radial: "环形菜单", radialKind: "文件类型预设", ringActions: "快捷操作", diff --git a/src/lib/useUpdate.ts b/src/lib/useUpdate.ts index 7e5288b..ae0f745 100644 --- a/src/lib/useUpdate.ts +++ b/src/lib/useUpdate.ts @@ -8,6 +8,10 @@ export interface UpdateFlow { checking: boolean; downloading: boolean; installing: boolean; + /** Why the last install attempt failed, or null. The verified download survives + * an install failure, so this is kept apart from the status rather than turning a + * "ready" status into an "error" one. */ + installError: string | null; progress: UpdateProgress | null; /** Percent of the download, or null until the first byte-aligned report. */ percent: number | null; @@ -32,6 +36,7 @@ export function useUpdateFlow(): UpdateFlow { const [checking, setChecking] = useState(false); const [downloading, setDownloading] = useState(false); const [installing, setInstalling] = useState(false); + const [installError, setInstallError] = useState(null); const [progress, setProgress] = useState(null); const [percent, setPercent] = useState(null); const mounted = useRef(true); @@ -60,6 +65,7 @@ export function useUpdateFlow(): UpdateFlow { const download = useCallback(async () => { if (downloading) return; setDownloading(true); + setInstallError(null); setProgress(null); setPercent(null); try { @@ -81,15 +87,19 @@ export function useUpdateFlow(): UpdateFlow { setInstalling(true); try { await api.updateInstall(); + // Success means a helper is now waiting for this process to exit, so the + // button stays on "installing" instead of offering the action again in the + // moment before the windows close. } catch (error) { - const last = statusRef.current; - if (last) publish({ ...last, message: String(error) }); - } finally { - if (mounted.current) setInstalling(false); + if (mounted.current) { + setInstallError(String(error).replace(/^Error:\s*/, "")); + setInstalling(false); + } } }, [installing, publish]); const clear = useCallback(async () => { + setInstallError(null); await api.updateClear().catch(() => undefined); publish(null); }, [publish]); @@ -129,6 +139,7 @@ export function useUpdateFlow(): UpdateFlow { checking, downloading, installing, + installError, progress, percent, check, diff --git a/src/styles.css b/src/styles.css index 5bd47b9..c759e99 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2349,23 +2349,6 @@ kbd { background: #fff; } -/* Host row in the Updates tab: which machine this is, and which artifact the - feed will therefore serve. */ -.update-system { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 7px; - margin-top: 10px; - color: #6b4f42; - font-size: 11.5px; -} - -.update-system-label { - color: #9c7e6d; - font-weight: 600; -} - .update-system-host { display: inline-flex; align-items: baseline; @@ -2384,6 +2367,14 @@ kbd { font-weight: 600; } +.update-system-host em { + color: #3f2a20; + font-family: "SF Mono", "Cascadia Code", ui-monospace, monospace; + font-size: 11px; + font-style: normal; + font-weight: 620; +} + .update-system-key { padding: 2px 7px; border-radius: 999px; @@ -4430,28 +4421,42 @@ body[data-view="radial"] .share-backdrop { } /* Updates: git release branch, hash-verified download. */ -.update-feed { +/* The two header lines above the Updates heading: the host and the feed. The + host line also carries the artifact the feed will install, so an "no artifact + for this platform" answer below explains itself. */ +.update-meta { display: grid; - gap: 4px; - margin: 10px 0 14px; + gap: 6px; + padding-bottom: 12px; + margin-bottom: 14px; + border-bottom: 1px solid rgba(140, 92, 62, 0.12); } -.update-feed-label { - font-size: 11px; - text-transform: uppercase; - letter-spacing: 0.08em; - color: rgba(91, 55, 35, 0.55); +.update-meta-line { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 7px; + color: #6b4f42; + font-size: 11.5px; } -.update-feed code { +.update-meta-line code { + flex: 1 1 240px; + min-width: 0; font-size: 11px; - padding: 6px 8px; + padding: 4px 8px; border-radius: 8px; background: rgba(240, 79, 36, 0.06); color: rgba(60, 34, 20, 0.8); word-break: break-all; } +.update-meta-label { + color: #9c7e6d; + font-weight: 600; +} + .update-trust { display: inline-flex; align-items: center; @@ -4472,10 +4477,6 @@ body[data-view="radial"] .share-backdrop { flex-wrap: wrap; } -.update-status-row > strong { - font-size: 15px; -} - .update-arrow { display: inline-flex; align-items: center;