Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(desktop): download updates from the dl.avibe.bot mirror with GitHub fallback (#2285)
Call White20c332e44fef
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lockindex 9db016573..772e21614 100644--- a/desktop/Cargo.lock+++ b/desktop/Cargo.lock@@ -258,7 +258,6 @@ dependencies = ["tauri-plugin-notification","tauri-plugin-opener","tauri-plugin-single-instance",- "tauri-plugin-updater","tauri-plugin-window-state","tempfile","tokio",@@ -592,16 +591,6 @@ dependencies = ["version_check",]-[[package]]-name = "core-foundation"-version = "0.9.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"-dependencies = [- "core-foundation-sys",- "libc",-]-[[package]]name = "core-foundation"version = "0.10.1"@@ -625,7 +614,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"dependencies = ["bitflags 2.13.1",- "core-foundation 0.10.1",+ "core-foundation","core-graphics-types","foreign-types","libc",@@ -638,7 +627,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = ["bitflags 2.13.1",- "core-foundation 0.10.1",+ "core-foundation","libc",]@@ -1707,11 +1696,9 @@ dependencies = ["percent-encoding","pin-project-lite","socket2",- "system-configuration","tokio","tower-service","tracing",- "windows-registry",][[package]]@@ -1959,36 +1946,6 @@ dependencies = ["windows-sys 0.45.0",]-[[package]]-name = "jni"-version = "0.22.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"-dependencies = [- "cfg-if",- "combine",- "jni-macros",- "jni-sys 0.4.1",- "log",- "simd_cesu8",- "thiserror 2.0.19",- "walkdir",- "windows-link 0.2.1",-]--[[package]]-name = "jni-macros"-version = "0.22.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"-dependencies = [- "proc-macro2",- "quote",- "rustc_version",- "simd_cesu8",- "syn 2.0.119",-]-[[package]]name = "jni-sys"version = "0.3.1"@@ -2466,18 +2423,6 @@ dependencies = ["objc2-core-foundation",]-[[package]]-name = "objc2-osa-kit"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"-dependencies = [- "bitflags 2.13.1",- "objc2",- "objc2-app-kit",- "objc2-foundation",-]-[[package]]name = "objc2-quartz-core"version = "0.3.2"@@ -2552,12 +2497,6 @@ dependencies = ["libc",]-[[package]]-name = "openssl-probe"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"-[[package]]name = "option-ext"version = "0.2.0"@@ -2584,20 +2523,6 @@ dependencies = ["pin-project-lite",]-[[package]]-name = "osakit"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"-dependencies = [- "objc2",- "objc2-foundation",- "objc2-osa-kit",- "serde",- "serde_json",- "thiserror 2.0.19",-]-[[package]]name = "pango"version = "0.18.3"@@ -3131,20 +3056,15 @@ dependencies = ["http-body","http-body-util","hyper",- "hyper-rustls","hyper-util","js-sys","log","percent-encoding","pin-project-lite",- "rustls",- "rustls-pki-types",- "rustls-platform-verifier","serde","serde_json","sync_wrapper","tokio",- "tokio-rustls","tokio-util","tower","tower-http",@@ -3246,18 +3166,6 @@ dependencies = ["zeroize",]-[[package]]-name = "rustls-native-certs"-version = "0.8.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"-dependencies = [- "openssl-probe",- "rustls-pki-types",- "schannel",- "security-framework",-]-[[package]]name = "rustls-pki-types"version = "1.15.1"@@ -3268,33 +3176,6 @@ dependencies = ["zeroize",]-[[package]]-name = "rustls-platform-verifier"-version = "0.7.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"-dependencies = [- "core-foundation 0.10.1",- "core-foundation-sys",- "jni 0.22.4",- "log",- "once_cell",- "rustls",- "rustls-native-certs",- "rustls-platform-verifier-android",- "rustls-webpki",- "security-framework",- "security-framework-sys",- "webpki-root-certs",- "windows-sys 0.61.2",-]--[[package]]-name = "rustls-platform-verifier-android"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"-[[package]]name = "rustls-webpki"version = "0.103.15"@@ -3327,15 +3208,6 @@ dependencies = ["winapi-util",]-[[package]]-name = "schannel"-version = "0.1.29"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"-dependencies = [- "windows-sys 0.61.2",-]-[[package]]name = "schemars"version = "0.8.22"@@ -3393,29 +3265,6 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"-[[package]]-name = "security-framework"-version = "3.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"-dependencies = [- "bitflags 2.13.1",- "core-foundation 0.10.1",- "core-foundation-sys",- "libc",- "security-framework-sys",-]--[[package]]-name = "security-framework-sys"-version = "2.17.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"-dependencies = [- "core-foundation-sys",- "libc",-]-[[package]]name = "selectors"version = "0.36.1"@@ -3648,22 +3497,6 @@ version = "0.3.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"-[[package]]-name = "simd_cesu8"-version = "1.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"-dependencies = [- "rustc_version",- "simdutf8",-]--[[package]]-name = "simdutf8"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"-[[package]]name = "siphasher"version = "1.0.3"@@ -3854,27 +3687,6 @@ dependencies = ["libc",]-[[package]]-name = "system-configuration"-version = "0.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"-dependencies = [- "bitflags 2.13.1",- "core-foundation 0.9.4",- "system-configuration-sys",-]--[[package]]-name = "system-configuration-sys"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"-dependencies = [- "core-foundation-sys",- "libc",-]-[[package]]name = "system-deps"version = "6.2.2"@@ -3896,7 +3708,7 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"dependencies = ["bitflags 2.13.1","block2",- "core-foundation 0.10.1",+ "core-foundation","core-graphics","crossbeam-channel","dbus",@@ -3906,7 +3718,7 @@ dependencies = ["gdkwayland-sys","gdkx11-sys","gtk",- "jni 0.21.1",+ "jni","libc","log","ndk",@@ -3973,7 +3785,7 @@ dependencies = ["gtk","heck 0.5.0","http",- "jni 0.21.1",+ "jni","libc","log","mime",@@ -4219,39 +4031,6 @@ dependencies = ["zbus",]-[[package]]-name = "tauri-plugin-updater"-version = "2.12.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7a5cad8ed5948d988e1018ecd31e27cacedbf72ce3fb972940c3e4bf51639e4b"-dependencies = [- "base64 0.22.1",- "dirs 6.0.0",- "flate2",- "futures-util",- "http",- "infer",- "log",- "minisign-verify",- "osakit",- "percent-encoding",- "reqwest 0.13.4",- "rustls",- "semver",- "serde",- "serde_json",- "tar",- "tauri",- "tauri-plugin",- "tempfile",- "thiserror 2.0.19",- "time",- "tokio",- "url",- "windows-sys 0.60.2",- "zip",-]-[[package]]name = "tauri-plugin-window-state"version = "2.4.1"@@ -4277,7 +4056,7 @@ dependencies = ["dpi","gtk","http",- "jni 0.21.1",+ "jni","objc2","objc2-ui-kit","objc2-web-kit",@@ -4300,7 +4079,7 @@ checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"dependencies = ["gtk","http",- "jni 0.21.1",+ "jni","log","objc2","objc2-app-kit",@@ -5112,15 +4891,6 @@ dependencies = ["system-deps",]-[[package]]-name = "webpki-root-certs"-version = "1.0.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"-dependencies = [- "rustls-pki-types",-]-[[package]]name = "webpki-roots"version = "1.0.9"@@ -5684,7 +5454,7 @@ dependencies = ["gtk","http","javascriptcore-rs",- "jni 0.21.1",+ "jni","libc","ndk","objc2",diff --git a/desktop/README.md b/desktop/README.mdindex 3d8badf26..a276a70c8 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -401,15 +401,22 @@ The **Use TEST Updates** toggle persists beside the private Runtime, defaults onfor prerelease app versions and off for stable versions, and never downgrades.Browsers and Python installations retain their existing update behavior.-The provider discovers published GitHub Releases in `avibe-bot/avibe`, using-canonical `gh-vX.Y.ZrcN` for TEST and `vX.Y.Z` for stable. It selects the highest-SemVer in the channel (up to 1,000 releases; overflow is an error). Releases+The provider discovers published releases of `avibe-bot/avibe` from the+`dl.avibe.bot` release index, which also lists each tag's peeled commit+([release download mirror](../docs/plans/release-download-mirror.md)). When the+index is unavailable it falls back to the GitHub API (up to 1,000 releases;+overflow is an error). It uses canonical `gh-vX.Y.ZrcN` for TEST and `vX.Y.Z`+for stable and selects the highest SemVer in the channel. Releaseswithout signed metadata cannot be installed automatically, including rc14. Asigned per-target `desktop-update-<target>.json` binds the repository, tag, peeledsource commit, desktop version, target, artifact URL, size, SHA-256, and Tauriartifact signature. Both metadata and payload signatures are verified locallywith the build-pinned public key. `.SIGNATURE` is OS-signing status text only.-The plugin response must equal the authenticated metadata before download.+Metadata, signatures, and the payload come from the mirror first and GitHub+second, starting with the source that last worked. A connection that does not+open within 10 seconds, or delivers nothing for 30 seconds, hands over to the+next source, which resumes with `Range`. Neither source is trusted: the same+verification applies to every byte, wherever it came from.macOS installs a signed `.app.tar.gz`; the DMG remains the first/manual installformat. The app is extracted on the installation filesystem, its bundle ID,@@ -453,10 +460,11 @@ never use the disposable test-fixture key for a release.overwrite a published asset, and never rotate the public key without a plannedbridge release signed by the currently trusted key.-Dependencies: native updater `tauri-plugin-updater` 2.12.0 (locked), shared-`minisign-verify` 0.2.5 / `base64` 0.22 / `semver` 1, HTTPS `reqwest`, and native-archive/temporary-file support. The frontend needs no updater JS permission or-plugin: it opens the native owner through a fixed navigation request.+Dependencies: shared `minisign-verify` 0.2.5 / `base64` 0.22 / `semver` 1, HTTPS+`reqwest`, and native archive/temporary-file support. The shell downloads and+verifies updates itself; no updater plugin is installed. The frontend needs no+updater JS permission or plugin: it opens the native owner through a fixed+navigation request.### Residual native acceptancediff --git a/desktop/runtime-host/src/download.rs b/desktop/runtime-host/src/download.rsnew file mode 100644index 000000000..6465f1b7b--- /dev/null+++ b/desktop/runtime-host/src/download.rs@@ -0,0 +1,94 @@+//! Downloads one immutable file from ordered, byte-identical sources.+//!+//! The client owns the connect timeout and the stall watchdog (its read+//! timeout); this module owns the source order and resumption. Callers verify+//! the returned bytes: a source is trusted for availability, never integrity.+use reqwest::{+ header::{CONTENT_RANGE, RANGE},+ StatusCode,+};++/// How many bytes a complete download holds.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Length {+ /// Exactly this many bytes, as pinned by signed metadata.+ Exact(u64),+ /// Unknown in advance, but never more than this many bytes.+ AtMost(u64),+}++enum Failure {+ /// The source can still serve the rest of the file later or elsewhere.+ Retry(String),+ /// The source served bytes that cannot belong to the file.+ Discard(String),+}++/// Fetches from `sources`, starting at index `start` and trying each source at+/// most twice in rotation. A failed or stalled source hands the bytes already+/// received to the next one, which resumes with `Range`; a source that+/// ignores the range restarts from zero. Returns the bytes and the index of+/// the source that completed them.+pub async fn fetch(+ client: &reqwest::Client,+ sources: &[String],+ start: usize,+ length: Length,+) -> Result<(Vec<u8>, usize), String> {+ if sources.is_empty() {+ return Err("no download source".into());+ }+ let mut data = Vec::new();+ let mut last = String::new();+ for attempt in 0..sources.len() * 2 {+ let index = (start + attempt) % sources.len();+ match continue_from(client, &sources[index], &mut data, length).await {+ Ok(()) => return Ok((data, index)),+ Err(Failure::Retry(error)) => last = error,+ Err(Failure::Discard(error)) => {+ data.clear();+ last = error;+ }+ }+ }+ Err(last)+}++async fn continue_from(client: &reqwest::Client, url: &str, data: &mut Vec<u8>, length: Length) -> Result<(), Failure> {+ let retry = |error: reqwest::Error| Failure::Retry(format!("download failed: {error}"));+ let mut request = client.get(url);+ if !data.is_empty() {+ request = request.header(RANGE, format!("bytes={}-", data.len()));+ }+ let mut response = request.send().await.map_err(retry)?;+ match response.status() {+ StatusCode::OK => data.clear(),+ StatusCode::PARTIAL_CONTENT if !data.is_empty() => {+ let resumes_here = response+ .headers()+ .get(CONTENT_RANGE)+ .and_then(|value| value.to_str().ok())+ .and_then(|value| value.strip_prefix("bytes "))+ .and_then(|value| value.split_once('-'))+ .and_then(|(first, _)| first.parse::<usize>().ok())+ == Some(data.len());+ if !resumes_here {+ return Err(Failure::Retry("download resumed at the wrong offset".into()));+ }+ }+ status => return Err(Failure::Retry(format!("download failed: HTTP {status}"))),+ }+ let limit = match length {+ Length::Exact(size) | Length::AtMost(size) => size,+ };+ while let Some(chunk) = response.chunk().await.map_err(retry)? {+ if (data.len() + chunk.len()) as u64 > limit {+ return Err(Failure::Discard("download exceeds its expected size".into()));+ }+ data.extend_from_slice(&chunk);+ }+ if matches!(length, Length::Exact(size) if data.len() as u64 != size) {+ return Err(Failure::Retry("download ended early".into()));+ }+ Ok(())+}diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rsindex af4a9233f..dab8568fc 100644--- a/desktop/runtime-host/src/lib.rs+++ b/desktop/runtime-host/src/lib.rs@@ -23,6 +23,7 @@pub mod bootstrap;pub mod bootstrap_log;pub mod deep_link;+pub mod download;pub mod health;pub mod launcher;pub mod notifications;diff --git a/desktop/runtime-host/src/update.rs b/desktop/runtime-host/src/update.rsindex 230271e2c..0ee14052f 100644--- a/desktop/runtime-host/src/update.rs+++ b/desktop/runtime-host/src/update.rs@@ -58,6 +58,14 @@ impl Channel {}Ok(version)}+ /// The highest SemVer release in this channel; publication order never counts.+ pub fn latest(self, releases: Vec<Release>) -> Option<(Version, Release)> {+ releases+ .into_iter()+ .filter(|release| release.prerelease == (self == Self::Test))+ .filter_map(|release| Some((self.version(&release.tag).ok()?, release)))+ .max_by(|a, b| a.0.cmp(&b.0))+ }}pub fn target_spec(target: &str) -> Result<(&'static str, &'static str), String> {@@ -73,6 +81,66 @@ pub fn manifest_name(target: &str) -> String {pub fn asset_url(tag: &str, name: &str) -> String {format!("https://github.com/{REPOSITORY}/releases/download/{tag}/{name}")}+/// Byte-identical copies of published release assets, plus the release index+/// (`docs/plans/release-download-mirror.md`). Unauthenticated, like GitHub:+/// every byte from either source passes the same verification.+pub const MIRROR: &str = "https://dl.avibe.bot";+pub const INDEX_URL: &str = "https://dl.avibe.bot/index/releases.json";+/// Download order for a release asset URL: the mirror, then GitHub. The mirror+/// URL is derived only by substituting the prefix, keeping percent-encoding.+pub fn sources(url: &str) -> Vec<String> {+ let github = format!("https://github.com/{REPOSITORY}/releases/download/");+ match url.strip_prefix(&github) {+ Some(path) => vec![format!("{MIRROR}/releases/{path}"), url.to_owned()],+ None => vec![url.to_owned()],+ }+}++/// A published release as discovery sees it, from the index or the GitHub API.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Release {+ pub tag: String,+ pub prerelease: bool,+ /// The peeled tag commit, when the source already lists it.+ pub commit: Option<String>,+ /// Asset names published under the canonical download URL.+ pub assets: Vec<String>,+}+#[derive(Deserialize)]+struct Index {+ schema_version: u32,+ repository: String,+ releases: Vec<IndexRelease>,+}+#[derive(Deserialize)]+struct IndexRelease {+ tag: String,+ prerelease: bool,+ commit: String,+ assets: Vec<IndexAsset>,+}+#[derive(Deserialize)]+struct IndexAsset {+ name: String,+}+/// Parses the mirror's release index, schema 1. Unknown fields are ignored so+/// the producer can add some without breaking installed shells.+pub fn index_releases(bytes: &[u8]) -> Result<Vec<Release>, String> {+ let index: Index = serde_json::from_slice(bytes).map_err(|_| "invalid release index")?;+ if index.schema_version != 1 || index.repository != REPOSITORY {+ return Err("unsupported release index".into());+ }+ Ok(index+ .releases+ .into_iter()+ .map(|release| Release {+ tag: release.tag,+ prerelease: release.prerelease,+ commit: Some(release.commit),+ assets: release.assets.into_iter().map(|asset| asset.name).collect(),+ })+ .collect())+}pub fn artifact_name(version: &str, target: &str) -> Result<String, String> {Ok(format!("Avibe_{version}_{target}{}", target_spec(target)?.1))}diff --git a/desktop/runtime-host/tests/download.rs b/desktop/runtime-host/tests/download.rsnew file mode 100644index 000000000..ae229ff17--- /dev/null+++ b/desktop/runtime-host/tests/download.rs@@ -0,0 +1,218 @@+use avibe_runtime_host::download::{fetch, Length};+use std::io::{Read, Write};+use std::net::{TcpListener, TcpStream};+use std::sync::{Arc, Mutex};+use std::time::Duration;++const PAYLOAD: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";+const EXACT: Length = Length::Exact(PAYLOAD.len() as u64);++/// One scripted response per connection. Once the script is exhausted the+/// listener closes and the source refuses connections.+#[derive(Clone, Copy)]+enum Reply {+ /// The file, honouring `Range`.+ Serve,+ /// The whole file with 200, whatever the request asked for.+ IgnoreRange,+ Status(u16),+ /// Promises the rest of the file, sends this many bytes, and drops the connection.+ Cut(usize),+ /// Sends this many bytes, then stops sending without closing.+ Stall(usize),+ /// No length announced: sends this many bytes and closes cleanly.+ Unsized(usize),+ /// 206 from the wrong offset.+ WrongOffset,+ /// The file followed by bytes that cannot belong to it.+ Oversized,+}++struct Source {+ url: String,+ /// The `Range` header of each request received.+ ranges: Arc<Mutex<Vec<Option<String>>>>,+}++impl Source {+ fn ranges(&self) -> Vec<Option<String>> {+ self.ranges.lock().unwrap().clone()+ }+}++fn source(replies: impl IntoIterator<Item = Reply>) -> Source {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}/asset", listener.local_addr().unwrap());+ let ranges = Arc::new(Mutex::new(Vec::new()));+ let seen = ranges.clone();+ let replies: Vec<Reply> = replies.into_iter().collect();+ std::thread::spawn(move || {+ for reply in replies {+ let (stream, _) = listener.accept().unwrap();+ let seen = seen.clone();+ // Each connection runs alone, so a stalled reply never delays the next.+ std::thread::spawn(move || respond(stream, reply, &seen));+ }+ });+ Source { url, ranges }+}++fn respond(mut stream: TcpStream, reply: Reply, seen: &Mutex<Vec<Option<String>>>) {+ let mut request = Vec::new();+ let mut buffer = [0; 1024];+ while !request.windows(4).any(|window| window == b"\r\n\r\n") {+ let read = stream.read(&mut buffer).unwrap();+ assert!(read > 0, "request ended before its headers");+ request.extend_from_slice(&buffer[..read]);+ }+ let range = String::from_utf8(request).unwrap().lines().find_map(|line| {+ let (name, value) = line.split_once(':')?;+ name.eq_ignore_ascii_case("range").then(|| value.trim().to_owned())+ });+ seen.lock().unwrap().push(range.clone());+ let offset = range+ .as_deref()+ .and_then(|range| range.strip_prefix("bytes=")?.strip_suffix('-')?.parse::<usize>().ok())+ .unwrap_or(0);+ let rest = &PAYLOAD[offset..];+ let partial = |body: &[u8], length: usize| {+ let mut head = if offset == 0 {+ "HTTP/1.1 200 OK\r\n".to_owned()+ } else {+ format!(+ "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {offset}-{}/{}\r\n",+ PAYLOAD.len() - 1,+ PAYLOAD.len()+ )+ };+ head.push_str(&format!("Content-Length: {length}\r\nConnection: close\r\n\r\n"));+ [head.as_bytes(), body].concat()+ };+ let response = match reply {+ Reply::Serve => partial(rest, rest.len()),+ Reply::IgnoreRange => [+ format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", PAYLOAD.len()).as_bytes(),+ PAYLOAD,+ ]+ .concat(),+ Reply::Status(code) => format!("HTTP/1.1 {code} Nope\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").into_bytes(),+ Reply::Cut(sent) | Reply::Stall(sent) => partial(&rest[..sent], rest.len()),+ Reply::Unsized(sent) => [b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".as_slice(), &PAYLOAD[..sent]].concat(),+ Reply::WrongOffset => format!(+ "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-{}/{}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ PAYLOAD.len() - 1,+ PAYLOAD.len(),+ PAYLOAD.len()+ )+ .into_bytes(),+ Reply::Oversized => {+ let body = [PAYLOAD, b"extra"].concat();+ partial(&body, body.len())+ }+ };+ // A source whose peer already gave up may fail to write; that is the point.+ let _ = stream.write_all(&response);+ let _ = stream.flush();+ if matches!(reply, Reply::Stall(_)) {+ std::thread::sleep(Duration::from_secs(3));+ }+}++fn client() -> reqwest::Client {+ reqwest::Client::builder()+ .connect_timeout(Duration::from_secs(2))+ .read_timeout(Duration::from_millis(300))+ .build()+ .unwrap()+}++async fn download(sources: &[&Source], start: usize, length: Length) -> Result<(Vec<u8>, usize), String> {+ let urls: Vec<String> = sources.iter().map(|source| source.url.clone()).collect();+ fetch(&client(), &urls, start, length).await+}++#[tokio::test]+async fn a_mirror_miss_falls_back_to_github_from_the_start() {+ let mirror = source([Reply::Status(404)]);+ let github = source([Reply::Serve]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 1)));+ assert_eq!(mirror.ranges(), [None]);+ assert_eq!(github.ranges(), [None]);+}++#[tokio::test]+async fn a_stalled_or_dropped_source_hands_its_bytes_to_the_next_one() {+ for (failure, sent) in [(Reply::Stall(10), 10), (Reply::Cut(7), 7)] {+ let mirror = source([failure]);+ let github = source([Reply::Serve]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 1)));+ assert_eq!(github.ranges(), [Some(format!("bytes={sent}-"))]);+ }+}++#[tokio::test]+async fn resumption_alternates_sources_until_each_had_two_attempts() {+ let mirror = source([Reply::Cut(5), Reply::Serve]);+ let github = source([Reply::Cut(9)]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 0)));+ assert_eq!(mirror.ranges(), [None, Some("bytes=14-".into())]);+ assert_eq!(github.ranges(), [Some("bytes=5-".into())]);++ let mirror = source([Reply::Status(503), Reply::Status(503), Reply::Serve]);+ let github = source([Reply::Status(502), Reply::Status(502)]);+ assert_eq!(+ download(&[&mirror, &github], 0, EXACT).await,+ Err("download failed: HTTP 502 Bad Gateway".into())+ );+ assert_eq!(mirror.ranges().len(), 2);+ assert_eq!(github.ranges().len(), 2);+}++#[tokio::test]+async fn the_last_source_that_worked_is_tried_first() {+ let mirror = source([]);+ let github = source([Reply::Serve]);+ assert_eq!(download(&[&mirror, &github], 1, EXACT).await, Ok((PAYLOAD.to_vec(), 1)));+ assert!(mirror.ranges().is_empty());+}++#[tokio::test]+async fn a_source_that_ignores_or_misplaces_the_range_never_splices_bytes() {+ let mirror = source([Reply::Cut(12)]);+ let github = source([Reply::IgnoreRange]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 1)));+ assert_eq!(github.ranges(), [Some("bytes=12-".into())]);++ let mirror = source([Reply::Cut(12), Reply::Serve]);+ let github = source([Reply::WrongOffset]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 0)));+ assert_eq!(mirror.ranges(), [None, Some("bytes=12-".into())]);+}++#[tokio::test]+async fn a_clean_early_end_is_a_failure_only_when_the_length_is_pinned() {+ let mirror = source([Reply::Unsized(20)]);+ let github = source([Reply::Serve]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 1)));+ assert_eq!(github.ranges(), [Some("bytes=20-".into())]);++ let only = source([Reply::Unsized(20)]);+ assert_eq!(+ download(&[&only], 0, Length::AtMost(1024)).await,+ Ok((PAYLOAD[..20].to_vec(), 0))+ );+}++#[tokio::test]+async fn bytes_beyond_the_expected_size_are_discarded_with_their_source() {+ let mirror = source([Reply::Oversized]);+ let github = source([Reply::Serve]);+ assert_eq!(download(&[&mirror, &github], 0, EXACT).await, Ok((PAYLOAD.to_vec(), 1)));+ assert_eq!(github.ranges(), [None], "nothing from the oversized source is kept");++ let only = source([Reply::Oversized, Reply::Oversized]);+ assert_eq!(+ download(&[&only], 0, Length::AtMost(PAYLOAD.len() as u64)).await,+ Err("download exceeds its expected size".into())+ );+}diff --git a/desktop/runtime-host/tests/fixtures/updater/releases-index.json b/desktop/runtime-host/tests/fixtures/updater/releases-index.jsonnew file mode 100644index 000000000..35a9de3fc--- /dev/null+++ b/desktop/runtime-host/tests/fixtures/updater/releases-index.json@@ -0,0 +1,286 @@+{+ "schema_version": 1,+ "repository": "avibe-bot/avibe",+ "releases": [+ {+ "tag": "gh-v3.1.2rc7",+ "prerelease": true,+ "published_at": "2026-09-29T16:46:30Z",+ "commit": "1264c311df1088a8eb1efe46611ae72f5af51188",+ "assets": [+ {+ "name": "Avibe_3.1.2-rc.7_aarch64-apple-darwin.SHA256SUMS",+ "size": 464,+ "sha256": "0b3dfba54e602669918ce90c2c48ad20963d2e42443628ffcf3a58e2880d7e40"+ },+ {+ "name": "Avibe_3.1.2-rc.7_aarch64-apple-darwin.SIGNATURE",+ "size": 35,+ "sha256": "e27df2e02236bf793fc5ba489d244300ff4eea084bff7849146a7ac407bf5d2a"+ },+ {+ "name": "Avibe_3.1.2-rc.7_aarch64-apple-darwin.SOURCE.json",+ "size": 207,+ "sha256": "70423562853e85c9d3afa6334db917a96b5e78ea850aa2490332744a2e01feba"+ },+ {+ "name": "Avibe_3.1.2-rc.7_aarch64-apple-darwin.app.tar.gz",+ "size": 166803577,+ "sha256": "fcd311cf2bffc4c1a82055c4b3da56e2debd3a3399e6b62675923e6db806cfc6"+ },+ {+ "name": "Avibe_3.1.2-rc.7_aarch64-apple-darwin.dmg",+ "size": 170414173,+ "sha256": "be104e5c79d4760633368351938012d3c549851dcc65c00085dbd4e42e3750de"+ },+ {+ "name": "Avibe_3.1.2-rc.7_aarch64-apple-darwin.runtime-manifest.json",+ "size": 1171,+ "sha256": "beef75d823389e91892ea5a3e2a7ece8d853708e0c329161a5ebec8254106391"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-apple-darwin.SHA256SUMS",+ "size": 460,+ "sha256": "3b350a7dbbee4673369558b473964b7b87449632b190499cc922e972a9ae8e71"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-apple-darwin.SIGNATURE",+ "size": 35,+ "sha256": "e27df2e02236bf793fc5ba489d244300ff4eea084bff7849146a7ac407bf5d2a"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-apple-darwin.SOURCE.json",+ "size": 206,+ "sha256": "b16c91e879df7c5abfa03111ab9646a8839543dc0541aaeb1c5737a99f57e30a"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-apple-darwin.app.tar.gz",+ "size": 166358301,+ "sha256": "b1c6faf4e8d77caaf074038842fba6e2c08ea115fc2e361ee1fd73e6aea75111"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-apple-darwin.dmg",+ "size": 169384860,+ "sha256": "f504969f6129843b9ad3a49e60bfb68b45b0e747ba971ebda01b95389cdedcbb"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-apple-darwin.runtime-manifest.json",+ "size": 1167,+ "sha256": "b058d08b76e09888623b7e24e721a06e70284614579373c9b6fa3e3b290d640d"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-pc-windows-msvc.SHA256SUMS",+ "size": 476,+ "sha256": "5e9e5433e53a4fd801547a43244e9bb4a566ad7d10ba95d36a84758bbb2c156e"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-pc-windows-msvc.SIGNATURE",+ "size": 20,+ "sha256": "f9bcf5978f0ed33f00e66451fa1d63fa91ea8c3570587ab6cd423f12d1162d97"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-pc-windows-msvc.SOURCE.json",+ "size": 217,+ "sha256": "6285414602acb426c517050d8b660a24b36acd87a5541d436163e44bf3b618b9"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-pc-windows-msvc.exe",+ "size": 142318525,+ "sha256": "362582ae854635eb55a2601b1f4aad8ef382da151734722d9aff78ec2a4d2f7e"+ },+ {+ "name": "Avibe_3.1.2-rc.7_x86_64-pc-windows-msvc.runtime-manifest.json",+ "size": 1197,+ "sha256": "c2d20b672532d9041364723c1fc7a0796db356df23ba1941165f02f877d82796"+ },+ {+ "name": "avibe_memory-3.1.2rc7-py3-none-any.whl",+ "size": 991,+ "sha256": "9cf1b371a4d3d5c7c5b0d441e88bf900758fd0ca68b2449c140b924af249ac70"+ },+ {+ "name": "avibe_os-3.1.2rc7-py3-none-any.whl",+ "size": 10186464,+ "sha256": "ee24019bdec8ee146765d5db78efdc859c060a88ad9e854d2e0d88e791c77753"+ },+ {+ "name": "avibe_os-3.1.2rc7.tar.gz",+ "size": 9925198,+ "sha256": "c9bbfca97ccdf66436f5c445b0a1a721d7c2eebd910a04ad0251709459ccfb0a"+ },+ {+ "name": "desktop-update-aarch64-apple-darwin.json",+ "size": 988,+ "sha256": "e17dc8da151298897986ed8e4b58e1978191352af40c01e82f9db07503b8eeee"+ },+ {+ "name": "desktop-update-aarch64-apple-darwin.json.sig",+ "size": 436,+ "sha256": "f9a10ee9b738556a3d8d0e4bce34d3329e0fe57c12d9a032b5fe6b416a28dd6f"+ },+ {+ "name": "desktop-update-x86_64-apple-darwin.json",+ "size": 985,+ "sha256": "4138a43fc7559983f236be57a840ceff97c88675f8bd858fb85eea8a489b12c8"+ },+ {+ "name": "desktop-update-x86_64-apple-darwin.json.sig",+ "size": 432,+ "sha256": "312dba9091c689c04ea87ecd95cd2314be10c43ce8dd26e1a4ad7098eb20cde0"+ },+ {+ "name": "desktop-update-x86_64-pc-windows-msvc.json",+ "size": 998,+ "sha256": "b881b0baf11ba8ee621bfde437125a0e17f109005fcc1efb3b717748048a725c"+ },+ {+ "name": "desktop-update-x86_64-pc-windows-msvc.json.sig",+ "size": 436,+ "sha256": "db70ce8c1add8dc6b43fb8ec04acb5bf0894fd3aa16d76baefac9c8c11ce2803"+ },+ {+ "name": "show-runtime-manifest.json",+ "size": 2138,+ "sha256": "535d5dcda939f17cea3770cdab4b1b0ac4d9ebb9fc63b642919dd34de48ca012"+ },+ {+ "name": "vibe-show-runtime-node-darwin-arm64.tgz",+ "size": 23632198,+ "sha256": "065987d6f25151c0da77fb36a64d7c9849f246f56f473f243e1fb5185b497362"+ },+ {+ "name": "vibe-show-runtime-node-darwin-x64.tgz",+ "size": 24538620,+ "sha256": "efdd7b117f6d020ccef7b0b708237e10857e4757b0efc252565e9220aa8ddd4a"+ },+ {+ "name": "vibe-show-runtime-node-linux-arm64.tgz",+ "size": 23639689,+ "sha256": "44b0998f7695d55c4ea92d99435285373e68ea0eb5af6448078d1d9bbb8a34bb"+ },+ {+ "name": "vibe-show-runtime-node-linux-x64.tgz",+ "size": 24582200,+ "sha256": "87b821727417a2cda892dc222a62779e514e4afdcbb6db5dd82badf677290d84"+ },+ {+ "name": "vibe-show-runtime-node-win32-arm64.tgz",+ "size": 23610373,+ "sha256": "95a09a954cb85c4bf6219845c89b85dc59653216800f7f84aaa8a98c4f172a94"+ },+ {+ "name": "vibe-show-runtime-node-win32-x64.tgz",+ "size": 25537347,+ "sha256": "4d168c735030626617a587ed1b32cb444d3907f3698f5d58b234a3bc566bd795"+ }+ ]+ },+ {+ "tag": "gh-v3.1.2rc6",+ "prerelease": true,+ "published_at": "2026-09-29T07:35:48Z",+ "commit": "f1e20d49fc16af2219d45f8a26d65e8fa1147d57",+ "assets": [+ {+ "name": "Avibe_3.1.2-rc.6_aarch64-apple-darwin.app.tar.gz",+ "size": 125719920,+ "sha256": "8e05d811c9e14c16f5a5113bf66e4b14b5f4e44baf9a0149e2efbfc11aee0e5f"+ },+ {+ "name": "desktop-update-aarch64-apple-darwin.json",+ "size": 988,+ "sha256": "d07d37d6f2497441c74ee70bdf46388fd23772926ed1b5a7e1ab736c93859db8"+ },+ {+ "name": "desktop-update-aarch64-apple-darwin.json.sig",+ "size": 436,+ "sha256": "6f4bf9c5950921006ebd863d35f2cfa19e8adca0c07a5ce5e43d9496c1869976"+ }+ ]+ },+ {+ "tag": "v3.1.1",+ "prerelease": false,+ "published_at": "2026-09-27T12:24:51Z",+ "commit": "198bd3e0ea4a3a4ab70e43fe3372cc520c666a21",+ "assets": [+ {+ "name": "avibe_memory-3.1.1-py3-none-any.whl",+ "size": 961,+ "sha256": "ce4dd454850c2dba6c88792b86681a0c1ebf07a70374c7b9349604aa27003b09"+ },+ {+ "name": "avibe_os-3.1.1-py3-none-any.whl",+ "size": 10135454,+ "sha256": "d204adaf4e7fb7831d975cf8c7e302a3a9e7801416e206bd36ab3bb572ddca68"+ },+ {+ "name": "avibe_os-3.1.1.tar.gz",+ "size": 9877216,+ "sha256": "df5fcb74183f1163247d47cbd0dc2cc9922d156a5bfc0f530bf681b989a42e69"+ },+ {+ "name": "show-runtime-manifest.json",+ "size": 2102,+ "sha256": "01b320ceb7eb7a92eb47505a258cc969a2c8ea6cd1812fb17801d646808c4fd9"+ },+ {+ "name": "vibe-show-runtime-node-darwin-arm64.tgz",+ "size": 23602602,+ "sha256": "9203f9dd672d6afd36c6074f775cccf0882d588f6144a427590ab03bcbece752"+ },+ {+ "name": "vibe-show-runtime-node-darwin-x64.tgz",+ "size": 24510048,+ "sha256": "5fa747fd5c025173737eaa5386e7068bbf7e2cda36fff36fccc8e37b0833d6fa"+ },+ {+ "name": "vibe-show-runtime-node-linux-arm64.tgz",+ "size": 23616096,+ "sha256": "04ba6585ad9e476bbb15e32432800b998c7d3e31197b7ba7dd70fb9f0892c9e9"+ },+ {+ "name": "vibe-show-runtime-node-linux-x64.tgz",+ "size": 24554025,+ "sha256": "67dbb0581ef4000136e16d1a0022e1541832e48b24c91a25e126ca1297240dda"+ },+ {+ "name": "vibe-show-runtime-node-win32-arm64.tgz",+ "size": 23583239,+ "sha256": "eb25354c0809793f40727b8dac6714691792615d21c66a4b32838ab2aa934921"+ },+ {+ "name": "vibe-show-runtime-node-win32-x64.tgz",+ "size": 25513797,+ "sha256": "87140ea50f705dc4bfa33b7b59fb80d4e3d8ae9bb8f7c92784a03b5b3b66f9bf"+ }+ ]+ },+ {+ "tag": "model-hub-engine-v7.3.16-3",+ "prerelease": false,+ "published_at": "2026-09-26T03:01:46Z",+ "commit": "df6fef95c078536c4406d1357ea676daaba7160b",+ "assets": [+ {+ "name": "CLIProxyAPI_7.3.16_darwin_aarch64.tar.gz",+ "size": 39534924,+ "sha256": "bc046156ac880beb1c09b2b69a8f80513ce3caec92f34fbc00dbf8aaf2c91754"+ }+ ]+ },+ {+ "tag": "git-runtime-v2.55.0-1",+ "prerelease": false,+ "published_at": "2026-07-16T16:11:57Z",+ "commit": "ebe0af0cc1a019d9fe46655d9b78fa507cfba3c0",+ "assets": [+ {+ "name": "git-2.55.0-darwin-arm64.tar.gz",+ "size": 1684366,+ "sha256": "02477119b1dd0f19a10c2ec5a443417f1697b83b1b18dbca874c0b72efedebae"+ }+ ]+ }+ ]+}diff --git a/desktop/runtime-host/tests/updater.rs b/desktop/runtime-host/tests/updater.rsindex 19811338e..73b1daaed 100644--- a/desktop/runtime-host/tests/updater.rs+++ b/desktop/runtime-host/tests/updater.rs@@ -125,3 +125,105 @@ fn download_and_verification_failures_never_reach_the_replacement_boundary() {});assert_eq!(result, Err("replacement failure".into()));}++#[test]+fn release_assets_come_from_the_mirror_first_by_prefix_substitution_only() {+ use avibe_runtime_host::update::{asset_url, sources};+ let url = asset_url("gh-v3.1.2rc7", "Avibe_3.1.2-rc.7_aarch64-apple-darwin.app.tar.gz");+ assert_eq!(+ sources(&url),+ [+ "https://dl.avibe.bot/releases/gh-v3.1.2rc7/Avibe_3.1.2-rc.7_aarch64-apple-darwin.app.tar.gz".to_owned(),+ url+ ]+ );+ for (github, mirror) in [+ ("v1.0.0/a%2Bb.tgz", "v1.0.0/a%2Bb.tgz"),+ ("v1.0.0/%E6%B5%8B%E8%AF%95.tgz", "v1.0.0/%E6%B5%8B%E8%AF%95.tgz"),+ ("v1.0.0/测试 a.tgz", "v1.0.0/测试 a.tgz"),+ ] {+ let url = format!("https://github.com/avibe-bot/avibe/releases/download/{github}");+ assert_eq!(sources(&url), [format!("https://dl.avibe.bot/releases/{mirror}"), url]);+ }+ for other in [+ "https://github.com/avibe-bot/avault/releases/download/v1.0.0/a.tgz",+ "https://api.github.com/repos/avibe-bot/avibe/releases",+ "http://github.com/avibe-bot/avibe/releases/download/v1.0.0/a.tgz",+ ] {+ assert_eq!(sources(other), [other]);+ }+}++#[test]+fn the_published_index_selects_the_highest_release_in_each_channel() {+ use avibe_runtime_host::update::index_releases;+ let releases = index_releases(&fs::read(fixtures().join("releases-index.json")).unwrap()).unwrap();+ let (version, test) = Channel::Test.latest(releases.clone()).unwrap();+ assert_eq!(version.to_string(), "3.1.2-rc.7");+ assert_eq!(test.tag, "gh-v3.1.2rc7");+ assert_eq!(test.commit.as_deref(), Some("1264c311df1088a8eb1efe46611ae72f5af51188"));+ for name in [+ "desktop-update-aarch64-apple-darwin.json",+ "desktop-update-aarch64-apple-darwin.json.sig",+ "Avibe_3.1.2-rc.7_aarch64-apple-darwin.app.tar.gz",+ ] {+ assert!(test.assets.iter().any(|asset| asset == name), "{name}");+ }+ // Runtime releases are full releases too, but never stable desktop tags.+ let (version, stable) = Channel::Stable.latest(releases).unwrap();+ assert_eq!((version.to_string().as_str(), stable.tag.as_str()), ("3.1.1", "v3.1.1"));+}++#[test]+fn channel_selection_uses_semver_and_the_prerelease_flag_together() {+ use avibe_runtime_host::update::Release;+ let release = |tag: &str, prerelease: bool| Release {+ tag: tag.into(),+ prerelease,+ commit: None,+ assets: Vec::new(),+ };+ let listed = vec![+ release("gh-v3.1.2rc9", true),+ release("gh-v3.1.2rc10", true),+ release("gh-v3.1.3rc01", true),+ release("gh-v9.0.0rc1", false),+ release("v9.0.0", true),+ release("v3.1.1", false),+ ];+ assert_eq!(Channel::Test.latest(listed.clone()).unwrap().1.tag, "gh-v3.1.2rc10");+ assert_eq!(Channel::Stable.latest(listed).unwrap().1.tag, "v3.1.1");+ assert!(Channel::Stable.latest(Vec::new()).is_none());+}++#[test]+fn only_the_supported_index_schema_for_this_repository_is_read() {+ use avibe_runtime_host::update::index_releases;+ let index = serde_json::json!({+ "schema_version": 1,+ "repository": "avibe-bot/avibe",+ "future_field": true,+ "releases": [{+ "tag": "v3.1.1",+ "prerelease": false,+ "published_at": "2026-09-01T00:00:00Z",+ "commit": "a".repeat(40),+ "assets": [{ "name": "测试.tgz", "size": 1, "sha256": "0".repeat(64), "future_field": 1 }]+ }]+ });+ let releases = index_releases(&serde_json::to_vec(&index).unwrap()).unwrap();+ assert_eq!(releases[0].assets, ["测试.tgz"]);+ for (field, value) in [+ ("schema_version", serde_json::json!(2)),+ ("repository", serde_json::json!("someone/avibe")),+ ("releases", serde_json::json!({})),+ ] {+ let mut changed = index.clone();+ changed[field] = value;+ assert!(+ index_releases(&serde_json::to_vec(&changed).unwrap()).is_err(),+ "{field}"+ );+ }+ assert!(index_releases(b"<html>captive portal</html>").is_err());+}diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 5cc3306eb..87a383d14 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -34,7 +34,6 @@ tauri-plugin-dialog = "2"tauri-plugin-notification = "2"tauri-plugin-opener = "2"tauri-plugin-single-instance = "2"-tauri-plugin-updater = "=2.12.0"tauri-plugin-window-state = "2"tempfile = "3"tokio.workspace = truediff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 772631158..ce54087f5 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -1698,7 +1698,6 @@ pub fn run() {).plugin(native_frame::init()).plugin(tauri_plugin_dialog::init())- .plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_autostart::Builder::new().build()).plugin(tauri_plugin_notification::init()).on_menu_event(|app, event| {diff --git a/desktop/src-tauri/src/updater.rs b/desktop/src-tauri/src/updater.rsindex d872f1058..ef5383b04 100644--- a/desktop/src-tauri/src/updater.rs+++ b/desktop/src-tauri/src/updater.rs@@ -1,10 +1,13 @@//! Native-only desktop updater. Remote WebViews never receive updater commands.-use avibe_runtime_host::update::{self, Channel, Manifest, REPOSITORY};+use avibe_runtime_host::{+ download::{self, Length},+ update::{self, Channel, Manifest, Release, REPOSITORY},+};use serde::Deserialize;use std::{path::PathBuf,sync::{- atomic::{AtomicBool, Ordering},+ atomic::{AtomicBool, AtomicUsize, Ordering},Mutex,},time::Duration,@@ -14,7 +17,6 @@ use tauri::{AppHandle, Manager,};use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};-use tauri_plugin_updater::{Update, UpdaterExt};pub const MENU_ID: &str = "desktop-update";pub const CHANNEL_ID: &str = "desktop-update-test";@@ -81,6 +83,9 @@ struct State {pub struct Updater {state: Mutex<State>,busy: AtomicBool,+ /// Index into `update::sources` of the source that last completed a+ /// download; the next download tries it first.+ source: AtomicUsize,channel_path: PathBuf,skipped_path: PathBuf,pub menu: MenuItem<tauri::Wry>,@@ -113,6 +118,7 @@ pub fn init(app: &AppHandle) -> tauri::Result<()> {channel,}),busy: AtomicBool::new(false),+ source: AtomicUsize::new(0),channel_path,skipped_path: app.path().app_local_data_dir()?.join("update-skipped.json"),menu: MenuItem::with_id(app, MENU_ID, &c.menu, true, None::<&str>)?,@@ -210,69 +216,85 @@ fn skip_version(app: &AppHandle, version: &str) {}#[derive(Deserialize)]-struct Release {+struct GithubRelease {tag_name: String,draft: bool,prerelease: bool,- assets: Vec<ReleaseAsset>,+ assets: Vec<GithubAsset>,}#[derive(Deserialize)]-struct ReleaseAsset {+struct GithubAsset {name: String,browser_download_url: String,}-async fn bytes(client: &reqwest::Client, url: &str, max: usize) -> Result<Vec<u8>, String> {- let mut response = client- .get(url)- .send()- .await- .map_err(|_| "network request failed")?- .error_for_status()- .map_err(|_| "release metadata unavailable")?;- let mut result = Vec::new();- while let Some(chunk) = response.chunk().await.map_err(|_| "metadata download failed")? {- if result.len() + chunk.len() > max {- return Err("metadata too large".into());- }- result.extend_from_slice(&chunk);- }- Ok(result)-}-async fn find_update(app: &AppHandle, channel: Channel) -> Result<Option<(Update, Manifest)>, String> {- let client = reqwest::Client::builder()+/// Connects fail fast; a download that stops moving hands over to the next+/// source, while a slow one that keeps moving is left to finish.+fn client() -> Result<reqwest::Client, String> {+ reqwest::Client::builder().https_only(true)- .timeout(Duration::from_secs(30))+ .connect_timeout(Duration::from_secs(10))+ .read_timeout(Duration::from_secs(30)).user_agent("Avibe-desktop-updater").build()- .map_err(|_| "HTTP client failed")?;- let mut candidates = Vec::new();+ .map_err(|_| "HTTP client failed".into())+}+async fn fetch(client: &reqwest::Client, url: String, max: u64) -> Result<Vec<u8>, String> {+ Ok(download::fetch(client, &[url], 0, Length::AtMost(max)).await?.0)+}+/// A release asset from the mirror or GitHub, starting with the last source+/// that worked. Callers authenticate the bytes.+async fn asset(app: &AppHandle, client: &reqwest::Client, url: &str, length: Length) -> Result<Vec<u8>, String> {+ let source = &app.state::<Updater>().source;+ let (data, used) = download::fetch(client, &update::sources(url), source.load(Ordering::SeqCst), length).await?;+ source.store(used, Ordering::SeqCst);+ Ok(data)+}+/// The mirror's index lists releases and their commits in one request; the+/// paginated GitHub API is the fallback when the mirror is unreachable.+async fn releases(client: &reqwest::Client) -> Result<Vec<Release>, String> {+ match fetch(client, update::INDEX_URL.into(), 8 * 1024 * 1024)+ .await+ .and_then(|data| update::index_releases(&data))+ {+ Ok(releases) => return Ok(releases),+ Err(error) => eprintln!("desktop update index: {error}; falling back to GitHub"),+ }+ let mut releases = Vec::new();// GitHub orders by creation, not SemVer. Walk the complete bounded history;// reaching the bound fails instead of claiming an incomplete list is current.for page in 1..=10 {- let data = bytes(- &client,- &format!("https://api.github.com/repos/{REPOSITORY}/releases?per_page=100&page={page}"),+ let data = fetch(+ client,+ format!("https://api.github.com/repos/{REPOSITORY}/releases?per_page=100&page={page}"),8 * 1024 * 1024,).await?;- let releases: Vec<Release> = serde_json::from_slice(&data).map_err(|_| "invalid releases response")?;- let done = releases.len() < 100;- for release in releases {- if !release.draft && release.prerelease == (channel == Channel::Test) {- if let Ok(version) = channel.version(&release.tag_name) {- candidates.push((version, release));- }- }+ let listed: Vec<GithubRelease> = serde_json::from_slice(&data).map_err(|_| "invalid releases response")?;+ let done = listed.len() < 100;+ for release in listed.into_iter().filter(|release| !release.draft) {+ let assets = release+ .assets+ .into_iter()+ .filter(|asset| asset.browser_download_url == update::asset_url(&release.tag_name, &asset.name))+ .map(|asset| asset.name)+ .collect();+ releases.push(Release {+ tag: release.tag_name,+ prerelease: release.prerelease,+ commit: None,+ assets,+ });}if done {- break;- }- if page == 10 {- return Err("release history exceeds discovery bound".into());+ return Ok(releases);}}- let Some((version, release)) = candidates.into_iter().max_by(|a, b| a.0.cmp(&b.0)) else {+ Err("release history exceeds discovery bound".into())+}+async fn find_update(app: &AppHandle, channel: Channel) -> Result<Option<Manifest>, String> {+ let client = client()?;+ let Some((version, release)) = channel.latest(releases(&client).await?) else {return Err("no release in this channel".into());};set_state(app, Phase::Checking, Some(version.to_string()));@@ -280,63 +302,49 @@ async fn find_update(app: &AppHandle, channel: Channel) -> Result<Option<(Updatereturn Ok(None);}let name = update::manifest_name(TARGET);- for name in [&name, &format!("{name}.sig")] {- let expected = update::asset_url(&release.tag_name, name);- if release- .assets- .iter()- .filter(|asset| asset.name == *name && asset.browser_download_url == expected)- .count()- != 1- {- return Err("signed updater metadata unavailable; manual installation required".into());- }+ let signature = format!("{name}.sig");+ if !release.assets.contains(&name) || !release.assets.contains(&signature) {+ return Err("signed updater metadata unavailable; manual installation required".into());}- let manifest_url = update::asset_url(&release.tag_name, &name);- let raw = bytes(&client, &manifest_url, 64 * 1024).await?;- let sig = bytes(&client, &format!("{manifest_url}.sig"), 4096).await?;+ let raw = asset(+ app,+ &client,+ &update::asset_url(&release.tag, &name),+ Length::AtMost(64 * 1024),+ )+ .await?;+ let sig = asset(+ app,+ &client,+ &update::asset_url(&release.tag, &signature),+ Length::AtMost(4096),+ )+ .await?;let manifest = Manifest::authenticated(&raw, std::str::from_utf8(&sig).map_err(|_| "invalid signature")?, KEY)?;- let commit: serde_json::Value = serde_json::from_slice(- &bytes(- &client,- &format!("https://api.github.com/repos/{REPOSITORY}/commits/{}", release.tag_name),- 2 * 1024 * 1024,+ let commit = match release.commit {+ Some(commit) => commit,+ None => serde_json::from_slice::<serde_json::Value>(+ &fetch(+ &client,+ format!("https://api.github.com/repos/{REPOSITORY}/commits/{}", release.tag),+ 2 * 1024 * 1024,+ )+ .await?,)- .await?,- )- .map_err(|_| "invalid source response")?;- let artifact = manifest.validate(- channel,- &release.tag_name,- commit["sha"].as_str().ok_or("missing source")?,- TARGET,- )?;- if !release.assets.iter().any(|a| a.browser_download_url == artifact.url) {- return Err("updater artifact missing".into());- }- let updater = app- .updater_builder()- .pubkey(KEY)- .target(update::target_spec(TARGET)?.0)- .endpoints(vec![manifest_url.parse().map_err(|_| "invalid endpoint")?])- .map_err(|_| "invalid updater endpoint")?- .timeout(Duration::from_secs(600))- .build()- .map_err(|_| "updater initialization failed")?;- let update = updater- .check()- .await- .map_err(|_| "updater check failed")?- .ok_or("release changed during check")?;- let authenticated: serde_json::Value = serde_json::from_slice(&raw).map_err(|_| "invalid manifest")?;- if update.raw_json != authenticated- || update.version != manifest.version- || update.download_url.as_str() != artifact.url- || update.signature != artifact.signature+ .map_err(|_| "invalid source response")?["sha"]+ .as_str()+ .ok_or("missing source")?+ .to_owned(),+ };+ let artifact = manifest.validate(channel, &release.tag, &commit, TARGET)?;+ if !release+ .assets+ .iter()+ .any(|name| update::asset_url(&release.tag, name) == artifact.url){- return Err("updater response differs from signed manifest".into());+ return Err("updater artifact missing".into());}- Ok(Some((update, manifest)))+ Ok(Some(manifest))}pub fn check(app: AppHandle, interactive: bool) {@@ -360,7 +368,7 @@ pub fn check(app: AppHandle, interactive: bool) {set_state(&app, Phase::Checking, None);tauri::async_runtime::spawn(async move {match find_update(&app, channel).await {- Ok(Some((update, manifest))) => {+ Ok(Some(manifest)) => {set_state(&app, Phase::Available, Some(manifest.version.clone()));let skipped = skipped_version(&app.state::<Updater>());if !should_prompt(interactive, skipped.as_deref(), &manifest.version) {@@ -387,7 +395,7 @@ pub fn check(app: AppHandle, interactive: bool) {c.cancel.clone(),)).show_with_result(move |result| match choice(&result, &c) {- Choice::Install => install(confirmation, update, manifest),+ Choice::Install => install(confirmation, manifest),Choice::Skip => {skip_version(&confirmation, &manifest.version);finish(&confirmation);@@ -425,17 +433,17 @@ fn finish(app: &AppHandle) {updater.busy.store(false, Ordering::SeqCst);let _ = updater.channel_menu.set_enabled(true);}-fn install(app: AppHandle, update: Update, manifest: Manifest) {+fn install(app: AppHandle, manifest: Manifest) {set_state(&app, Phase::Downloading, None);tauri::async_runtime::spawn(async move {let result = async {- let download = update- .download(|_, _| {}, || {})- .await- .map_err(|_| "download or signature verification failed".to_string());let artifact = manifest.validate(manifest.channel, &manifest.tag, &manifest.source_sha, TARGET)?.clone();+ let download = match client() {+ Ok(client) => asset(&app, &client, &artifact.url, Length::Exact(artifact.size)).await,+ Err(error) => Err(error),+ };let handle = app.clone();tauri::async_runtime::spawn_blocking(move || {update::install_verified(download, &artifact, KEY, |data| {@@ -476,26 +484,6 @@ fn install(app: AppHandle, update: Update, manifest: Manifest) {#[cfg(test)]mod tests {use super::*;- #[test]- fn signed_manifests_are_consumed_by_the_pinned_official_updater() {- for (target, key, _) in update::TARGETS {- for channel in ["test", "stable"] {- let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(format!(- "../runtime-host/tests/fixtures/updater/{channel}-{target}.json"- ));- let raw = std::fs::read(path).unwrap();- let release: tauri_plugin_updater::RemoteRelease = serde_json::from_slice(&raw).unwrap();- let manifest: Manifest = serde_json::from_slice(&raw).unwrap();- assert_eq!(release.version.to_string(), manifest.version);- assert_eq!(- release.download_url(key).unwrap().as_str(),- manifest.platforms[*key].url- );- assert_eq!(release.signature(key).unwrap(), &manifest.platforms[*key].signature);- }- }- }-#[test]fn dialog_buttons_map_to_one_choice_and_dismissal_is_later() {for locale in ["en", "zh"] {diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.jsonindex 1a2dba7bf..6cc6bc475 100644--- a/desktop/src-tauri/tauri.conf.json+++ b/desktop/src-tauri/tauri.conf.json@@ -41,10 +41,6 @@"avibe"]}- },- "updater": {- "pubkey": "",- "endpoints": []}},"bundle": {diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rsindex 5ab314c7b..5a9b8597d 100644--- a/desktop/src-tauri/tests/shell_boundaries.rs+++ b/desktop/src-tauri/tests/shell_boundaries.rs@@ -963,7 +963,9 @@ fn explicit_stop_does_not_schedule_automatic_recovery() {fn updates_have_one_native_owner_and_no_remote_install_permission() {let source = include_str!("../src/lib.rs");let updater = include_str!("../src/updater.rs");- assert!(source.contains("tauri_plugin_updater::Builder::new().build()"));+ // The shell downloads and verifies updates itself; no plugin exposes a+ // second update path.+ assert!(!source.contains("tauri_plugin_updater"));assert!(source.contains("updater::check(app.handle().clone(), false)"));assert!(source.contains("updater::MENU_ID => updater::check(app.clone(), true)"));assert!(source.contains("url.as_str() == updater::OPEN_URL"));diff --git a/docs/plans/desktop-auto-update.md b/docs/plans/desktop-auto-update.mdindex 5a02ca106..3c1c56390 100644--- a/docs/plans/desktop-auto-update.md+++ b/docs/plans/desktop-auto-update.md@@ -20,13 +20,15 @@ no silent auto-install option: installation keeps its native confirmation.## Distribution contract-GitHub Releases in `avibe-bot/avibe` are the discovery source. Canonical stable-`vX.Y.Z` and TEST `gh-vX.Y.ZrcN` tags select disjoint channels. Each target owns a-Tauri-compatible manifest plus detached Minisign signature. The signed manifest-binds repository, tag, peeled source commit, SemVer, target, artifact URL, size,-SHA-256, and the artifact's own Tauri signature. The shell verifies all these-fields and the GitHub tag source before offering installation. It checks the-plugin's fetched JSON against the authenticated manifest before downloading.+GitHub Releases in `avibe-bot/avibe` are the source of truth. The shell discovers+them through the `dl.avibe.bot` release index and falls back to the GitHub API+when the index is unavailable ([release download mirror](release-download-mirror.md)).+Canonical stable `vX.Y.Z` and TEST `gh-vX.Y.ZrcN` tags select disjoint channels.+Each target owns a Tauri-compatible manifest plus detached Minisign signature.+The signed manifest binds repository, tag, peeled source commit, SemVer, target,+artifact URL, size, SHA-256, and the artifact's own Tauri signature. The shell+verifies all these fields and the tag's peeled commit, as listed by the index or+the GitHub API, before offering installation.macOS updater payloads are `.app.tar.gz`; DMGs remain manual installers. Windowsuses NSIS EXE. `.SIGNATURE` remains human-readable OS-signing metadata and never@@ -36,10 +38,12 @@ Existing unsigned releases cannot become auto-installable retroactively.## Installation and verification-The pinned Tauri v2 updater owns HTTPS update checks and artifact signature-verification. Application replacement must preserve the old runnable application-on failure. The implementation must account for the upstream macOS install path-not restoring its temporary backup, and Windows returning before NSIS completes.+The shell owns HTTPS update checks and downloads, mirror first with GitHub+fallback, and verifies the artifact's size, SHA-256, and signature itself; no+updater plugin is installed. Application replacement must preserve the old+runnable application on failure. It does not use the upstream Tauri install+path, which does not restore its temporary macOS backup and returns on Windows+before NSIS completes.Validate metadata/signatures and all bytes before any replacement operation.Use shared Rust contract verification both in the shell and release validation;diff --git a/docs/plans/release-download-mirror.md b/docs/plans/release-download-mirror.mdindex 12dc6d121..7fe6723ea 100644--- a/docs/plans/release-download-mirror.md+++ b/docs/plans/release-download-mirror.md@@ -63,8 +63,8 @@ and fall back to GitHub.every listed asset already exists in the bucket with those bytes.- `sha256` is GitHub's asset digest, re-verified against the downloaded bytesbefore upload. `commit` is the peeled tag target.-- Producer: the release mirror workflow. Planned consumers: the desktop- updater, the CLI update checker, and the runtime downloaders, replacing their+- Producer: the release mirror workflow. Consumers: the desktop updater.+ Planned: the CLI update checker and the runtime downloaders, replacing their`api.github.com` discovery calls.- The index is unauthenticated metadata. A hostile index can at most withholdreleases or name copies that then fail the consumer's existing verification.@@ -122,10 +122,11 @@ Cloudflare configuration lives outside the repository. The expected state:1. Mirror and index (this change), then a full backfill by manual dispatch.2. Cache Rule, then real-file tests from the three mainland carriers at theevening peak.-3. Clients, one at a time: desktop updater, then runtime and Show Runtime- downloads, then `install.sh` and `install.ps1`. Each tries the mirror first,- then GitHub, with a connect timeout and a stall watchdog, resumes with+3. Clients, one at a time: desktop updater (done), then runtime and Show+ Runtime downloads, then `install.sh` and `install.ps1`. Each tries the mirror+ first, then GitHub, with a connect timeout and a stall watchdog, resumes with`Range` when switching source, and remembers the last source that worked.+ The desktop shell's `avibe_runtime_host::download` is the Rust reference.4. Install-script third-party dependencies (the uv installer andpython-build-standalone) through `UV_INSTALLER_GITHUB_BASE_URL` and`UV_PYTHON_INSTALL_MIRROR`, if step 2 shows GitHub is still theirdiff --git a/scripts/desktop_updater.py b/scripts/desktop_updater.pyindex f14fd10f4..acb60dc2d 100644--- a/scripts/desktop_updater.py+++ b/scripts/desktop_updater.py@@ -38,7 +38,6 @@ def configure(config: Path, env_file: Path, enabled: bool) -> None:data = json.loads(config.read_text(encoding='utf-8'))# Payloads are sealed after final OS signing. We sign those final bytes below.data.setdefault('bundle', {})['createUpdaterArtifacts'] = False- data.setdefault('plugins', {})['updater'] = {'pubkey': public if enabled else '', 'endpoints': []}config.write_text(json.dumps(data) + '\n', encoding='utf-8')with env_file.open('a', encoding='utf-8') as stream:stream.write(f"AVIBE_DESKTOP_UPDATER_PUBLIC_KEY={public if enabled else ''}\n")diff --git a/tests/test_desktop_updater.py b/tests/test_desktop_updater.pyindex 7e52e5c60..f842c0016 100644--- a/tests/test_desktop_updater.py+++ b/tests/test_desktop_updater.py@@ -30,14 +30,13 @@ def test_enabled_channel_requires_both_signing_key_and_pinned_public_key(enableddesktop_updater.configuration(enabled, public, private)-def test_disabled_build_explicitly_erases_endpoint_and_embedded_public_key(tmp_path, monkeypatch):+def test_disabled_build_explicitly_erases_the_embedded_public_key(tmp_path, monkeypatch):config = tmp_path / 'config.json'config.write_text(json.dumps({'version': '3.1.2-rc.15'}))env = tmp_path / 'env'monkeypatch.setenv('AVIBE_DESKTOP_UPDATER_PUBLIC_KEY', 'a configured key')desktop_updater.configure(config, env, False)actual = json.loads(config.read_text())- assert actual['plugins']['updater'] == {'pubkey': '', 'endpoints': []}assert not actual['bundle']['createUpdaterArtifacts']assert env.read_text() == 'AVIBE_DESKTOP_UPDATER_PUBLIC_KEY=\n'