From 61af8c79c9295e6ee2b16c349084ecbeca4f1647 Mon Sep 17 00:00:00 2001 From: rgdevment Date: Tue, 10 Nov 2026 10:51:01 -0300 Subject: [PATCH 1/3] fix(update): a Store copy offers the update the Store has, whatever number comes with it, and says why it waits --- .github/oversized.txt | 2 +- PRIVACY.md | 8 +- app/src-tauri/Cargo.toml | 1 + app/src-tauri/src/about.rs | 4 +- app/src-tauri/src/lib.rs | 50 ++- app/src-tauri/src/shop.rs | 555 ++++++++++++++++++++++++++++++-- app/src-tauri/src/update.rs | 306 ++++++++++++++++-- app/src/i18n.ts | 34 +- app/src/settings/About.test.tsx | 70 +++- app/src/settings/About.tsx | 54 +++- app/src/settings/update.ts | 9 +- 11 files changed, 982 insertions(+), 111 deletions(-) diff --git a/.github/oversized.txt b/.github/oversized.txt index 4d263e3..fc3ec61 100644 --- a/.github/oversized.txt +++ b/.github/oversized.txt @@ -1,2 +1,2 @@ -1860 app/src-tauri/src/lib.rs +1852 app/src-tauri/src/lib.rs 1817 crates/linkunbound-shell/src/main.rs diff --git a/PRIVACY.md b/PRIVACY.md index 3366034..1a6d07b 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -215,7 +215,11 @@ download says whether the machine is Apple Silicon or Intel — as a download made by hand from the releases page would. A copy installed from the Microsoft Store takes its update from the Store -instead, and never reads the feed above. A copy installed with Homebrew updates +instead. To name the version on its way, it reads the Store's public listing of +LinkUnbound at `displaycatalog.mp.microsoft.com`, asked with a fixed market and +language so the request says nothing about you. Only when that listing cannot +be read does it read the feed above. Nothing is installed from either: only the +Store installs it. A copy installed with Homebrew updates itself the same way as a downloaded one; `brew upgrade` works as well. A copy installed with winget came from the same releases page and updates itself the same way too. @@ -227,7 +231,7 @@ same way too. LinkUnbound is available through the Microsoft Store. The Store version: - **Follows the same privacy principles** as the standalone version. -- **Asks the Store about updates**, not the feed above: a release reaches the Store when its certification lets it through, which is not when it reaches everyone else. +- **Asks the Store about updates**, and reads the Store's public listing of LinkUnbound to name the version on its way: a release reaches the Store when its certification lets it through, which is not when it reaches everyone else. The feed above only stands in when that listing cannot be read. - **Uses MSIX packaging** — installs and uninstalls cleanly with standard Windows mechanisms. - **Microsoft Store policies** apply to distribution, but LinkUnbound itself does not share any data with Microsoft beyond what the Store platform requires for installation and updates. diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index af7a591..f41030c 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -63,6 +63,7 @@ linkunbound-win.workspace = true windows-future = "0.3" windows = { version = "0.62", features = [ "ApplicationModel", + "Management_Deployment", "Services_Store", "Win32_Foundation", "Win32_System_Com", diff --git a/app/src-tauri/src/about.rs b/app/src-tauri/src/about.rs index 9671773..20e758d 100644 --- a/app/src-tauri/src/about.rs +++ b/app/src-tauri/src/about.rs @@ -2,7 +2,7 @@ use serde::Serialize; use linkunbound_core::Language; -use crate::{HERE, catalogue, same_name, shown_origin, store, system, update}; +use crate::{HERE, catalogue, same_name, shop, shown_origin, store, system, update}; const NOTICES: &str = include_str!("../../../THIRD-PARTY-BUNDLED.md"); const LICENCES: &str = include_str!("../../../THIRD-PARTY-LICENSES.md"); @@ -16,6 +16,7 @@ pub struct Build { candidates: bool, candidates_apply: bool, kept_by_the_store: bool, + not_sold: bool, } #[tauri::command] @@ -29,6 +30,7 @@ pub fn about() -> Build { candidates: update::tracking(HERE, kept.candidates), candidates_apply: !store_copy, kept_by_the_store: store_copy, + not_sold: store_copy && !shop::sold(), } } diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index c356313..305d6aa 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -575,41 +575,33 @@ const fn owner(_app: &AppHandle) -> Option { #[tauri::command] async fn update_ready( app: AppHandle, - now_please: Option, + look: Option, ) -> Result, String> { let dir = store().dir().to_path_buf(); let kept = update::route(); let mut looked = update::looked(&dir); let now = update::now(); - let asked = now_please.unwrap_or(false); + let asked = look.is_some(); - // A copy the Store keeps asks the Store, not the manifest: a release is out for everyone else - // while certification still has it. Silence falls through, though — the Store answers for - // nothing in a package it did not sell. - if kept.route == update::Route::Store - && let Some(window) = owner(&app) - { - // Held to the manifest's interval too: a Store that never answers strands the thread. - if !asked && !update::due(looked.checked_at, now) { - return Ok(looked - .found_version - .as_deref() - .and_then(|version| update::from_the_shop(version, HERE))); - } - if let Ok(shelf) = tauri::async_runtime::spawn_blocking(move || shop::asked(window)).await - && shelf != shop::Shelf::Silent - { - let seen = match shelf { - shop::Shelf::Waiting(version) => update::from_the_shop(&version, HERE), - _ => None, - }; - looked.checked_at = Some(now); - looked.found_version = seen.as_ref().map(|one| one.version.clone()); - looked.found_route = seen.as_ref().map(|one| one.route.name().to_owned()); - looked.found_installs = seen.as_ref().map(|one| one.installs); - update::keep(&dir, &looked); - return Ok(seen); + // A release is out for everyone else while certification still has it from the Store. + if kept.route == update::Route::Store { + let was = shop::Memory::of(&looked); + let Some(window) = owner(&app) else { + return Ok(shop::last_said(HERE, &was)); + }; + let pressed = look == Some(update::Look::Pressed); + let wants = looked.candidates; + let verdict = + tauri::async_runtime::spawn_blocking(move || shop::look(window, pressed, wants, was)) + .await + .map_err(|why| why.to_string())?; + verdict.memory.clone().written_into(&mut looked); + looked.checked_at = Some(now); + update::keep(&dir, &looked); + if verdict.refused(pressed) { + return Err("updateUnanswered".to_owned()); } + return Ok(verdict.ready); } if !asked && !update::due(looked.checked_at, now) { @@ -996,7 +988,7 @@ fn run_errand(app: AppHandle, errand: Errand) { // asked here, with no window, the manifest would answer for a package it did not sell. Errand::Look if update::route().route == update::Route::Store => {} Errand::Look => { - let _ = update_ready(app.clone(), Some(false)).await; + let _ = update_ready(app.clone(), None).await; } Errand::Update => { let _ = install(app.clone(), false).await; diff --git a/app/src-tauri/src/shop.rs b/app/src-tauri/src/shop.rs index 5602334..2c40656 100644 --- a/app/src-tauri/src/shop.rs +++ b/app/src-tauri/src/shop.rs @@ -1,28 +1,155 @@ -/// A shop that answers it has nothing is not a shop that never answered: the first means this copy -/// is current, the second that nothing is known and the old wording still stands. +#![cfg_attr(not(windows), allow(dead_code))] + +use crate::HERE; +use crate::update::{self, Ahead, Coming, Ready, Route}; +use linkunbound_core::update::Looked; + #[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(not(windows), allow(dead_code))] pub enum Shelf { - Waiting(String), + Waiting, + Landed(String), + Queued, + Paused, Current, Silent, + NotSold, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Memory { + pub version: Option, + pub offered: Option, +} + +impl Memory { + #[must_use] + pub fn of(looked: &Looked) -> Self { + let kept = looked.found_route.as_deref() == Some(Route::Store.name()); + Self { + version: looked.found_version.clone(), + offered: looked.found_installs.filter(|_| kept), + } + } + + pub fn written_into(self, looked: &mut Looked) { + looked.found_route = self.offered.map(|_| Route::Store.name().to_owned()); + looked.found_installs = self.offered; + looked.found_version = self.version; + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Verdict { + pub ready: Option, + pub memory: Memory, + pub unanswered: bool, +} + +impl Verdict { + #[must_use] + pub const fn refused(&self, pressed: bool) -> bool { + pressed && self.unanswered + } +} + +#[must_use] +pub fn waits(pressed: bool, ahead: &Ahead) -> bool { + pressed && *ahead != Ahead::Nothing +} + +#[must_use] +pub fn last_said(now: &str, was: &Memory) -> Option { + let version = was + .version + .as_deref() + .filter(|one| update::later(now, one))?; + Some(if was.offered? { + update::from_the_shop(Some(version)) + } else { + update::on_its_way(Some(version), Coming::NotYet) + }) +} + +#[must_use] +pub fn verdict(shelf: Shelf, ahead: Ahead, now: &str, was: Memory) -> Verdict { + let number = match &ahead { + Ahead::Is(version) => Some(version.clone()), + Ahead::Nothing => None, + Ahead::Unheard => was.version.clone().filter(|one| update::later(now, one)), + }; + let told = |ready: Ready, version: Option, offered: bool| Verdict { + ready: Some(ready), + memory: Memory { + version, + offered: Some(offered), + }, + unanswered: false, + }; + let none = |unanswered: bool| Verdict { + ready: None, + memory: Memory::default(), + unanswered, + }; + match (shelf, ahead) { + (Shelf::Waiting, _) => told(update::from_the_shop(number.as_deref()), number, true), + (Shelf::Landed(version), _) => { + let landed = Ready { + installs: false, + ..update::from_the_shop(Some(&version)) + }; + told(landed, Some(version), true) + } + (Shelf::Queued, _) => told( + update::on_its_way(number.as_deref(), Coming::Queued), + number, + false, + ), + (Shelf::Paused, _) => told( + update::on_its_way(number.as_deref(), Coming::Paused), + number, + false, + ), + (Shelf::NotSold, _) => none(false), + (_, Ahead::Is(version)) => told( + update::on_its_way(Some(&version), Coming::NotYet), + Some(version), + false, + ), + (Shelf::Current, Ahead::Nothing) => none(false), + (Shelf::Silent, Ahead::Nothing) if was.offered != Some(true) => none(true), + (Shelf::Current, Ahead::Unheard) if was.offered != Some(false) => none(false), + (shelf, _) => Verdict { + ready: last_said(now, &was), + memory: was, + unanswered: shelf == Shelf::Silent, + }, + } +} + +#[must_use] +pub fn look(window: isize, pressed: bool, wants: Option, was: Memory) -> Verdict { + let (shelf, ahead) = match settled() { + Some(shelf) => (shelf, Ahead::Unheard), + None => { + let ahead = update::ahead(HERE, wants, update::catalog(HERE), update::fetch); + let shelf = asked(window, waits(pressed, &ahead)); + (shelf, ahead) + } + }; + verdict(shelf, ahead, HERE, was) } #[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(not(windows), allow(dead_code))] pub enum Trouble { Gone, Stopped, Failed(String), } -/// The Store counts the download as the first four fifths of the errand and the install as the -/// rest, so what it hands over is stretched back into a download of its own. -#[cfg_attr(not(windows), allow(dead_code))] +/// The Store counts the download as the first four fifths of the errand and the install as the rest. const DOWNLOADED: f64 = 0.8; #[must_use] -#[cfg_attr(not(windows), allow(dead_code))] pub fn step(far: f64) -> (&'static str, u64) { if far >= DOWNLOADED { return ("installing", 100); @@ -31,8 +158,18 @@ pub fn step(far: f64) -> (&'static str, u64) { } #[must_use] -pub fn asked(window: isize) -> Shelf { - there::asked(window) +pub fn settled() -> Option { + there::settled() +} + +#[must_use] +pub fn sold() -> bool { + there::sold_here() +} + +#[must_use] +pub fn asked(window: isize, waits: bool) -> Shelf { + there::asked(window, waits) } pub fn take( @@ -45,23 +182,24 @@ pub fn take( #[cfg(windows)] mod there { use super::{Shelf, Trouble}; - use windows::ApplicationModel::PackageSignatureKind; - use windows::ApplicationModel::{Package, PackageVersion}; + use windows::ApplicationModel::{Package, PackageSignatureKind, PackageVersion}; + use windows::Management::Deployment::PackageManager; use windows::Services::Store::{ StoreContext, StorePackageUpdateState, StorePackageUpdateStatus, + StoreQueueItemExtendedState, StoreQueueItemState, }; use windows::Win32::Foundation::HWND; use windows::Win32::System::Com::CoIncrementMTAUsage; use windows::Win32::UI::Shell::IInitializeWithWindow; - use windows::core::{Interface, Ref}; + use windows::core::{HSTRING, Interface, Ref}; use windows_future::AsyncOperationProgressHandler; const PATIENCE: std::time::Duration = std::time::Duration::from_secs(10); - /// Long past the point where the process should already have been taken down by the install. + const AGAIN: std::time::Duration = std::time::Duration::from_secs(6); + const UNTIL: std::time::Duration = std::time::Duration::from_secs(75); const AT_LENGTH: std::time::Duration = std::time::Duration::from_secs(30 * 60); - /// The Store answers on a thread of its own and has been known to never answer at all, which - /// would otherwise leave the window waiting on it for the rest of the session. + /// The Store has been known to never answer, which would leave the window waiting for good. fn apart( how_long: std::time::Duration, work: impl FnOnce() -> T + Send + 'static, @@ -73,40 +211,125 @@ mod there { hear.recv_timeout(how_long).ok() } - /// A copy the Store did not sell is one the Store will never have an update for, and its - /// empty answer reads exactly like «you are on the newest one». Left as that, a package - /// installed by hand would be told it was current for the rest of its life. - fn sold_here() -> bool { + pub fn sold_here() -> bool { Package::Current() .and_then(|one| one.SignatureKind()) .is_ok_and(|kind| kind == PackageSignatureKind::Store) } - pub fn asked(window: isize) -> Shelf { + pub fn settled() -> Option { if !sold_here() { - return Shelf::Silent; + return Some(Shelf::NotSold); + } + beside_us().map(Shelf::Landed) + } + + pub fn asked(window: isize, waits: bool) -> Shelf { + match offers(window) { + Some(true) => Shelf::Waiting, + Some(false) if waits => waited_out(window), + Some(false) => in_its_queue(window), + None => Shelf::Silent, + } + } + + fn offers(window: isize) -> Option { + apart(PATIENCE, move || waiting(window)).and_then(Result::ok) + } + + /// Asking wakes the Store's own errand and it answers with the state from before, so a press + /// waits on what that errand leaves behind, watching what costs no rationed look. + fn waited_out(window: isize) -> Shelf { + let since = std::time::Instant::now(); + while since.elapsed() < UNTIL { + std::thread::sleep(AGAIN); + if let Some(version) = beside_us() { + return Shelf::Landed(version); + } + if let Some(Ok(Some(found))) = apart(PATIENCE, move || queued(window)) { + return found; + } + } + match offers(window) { + Some(true) => Shelf::Waiting, + Some(false) => in_its_queue(window), + None => Shelf::Silent, } - match apart(PATIENCE, move || waiting(window)) { - Some(Ok(Some(version))) => Shelf::Waiting(version), + } + + fn in_its_queue(window: isize) -> Shelf { + match apart(PATIENCE, move || queued(window)) { + Some(Ok(Some(found))) => found, Some(Ok(None)) => Shelf::Current, Some(Err(_)) | None => Shelf::Silent, } } - /// The errand covers optional packages too, and the version of one of those is not a version - /// of LinkUnbound to put in front of anybody. - fn waiting(window: isize) -> windows::core::Result> { + fn queued(window: isize) -> windows::core::Result> { + let ours = Package::Current()?.Id()?.FamilyName()?; + let items = shop(window)?.GetAssociatedStoreQueueItemsAsync()?.join()?; + for one in 0..items.Size()? { + let item = items.GetAt(one)?; + if item.PackageFamilyName().unwrap_or_default() != ours { + continue; + } + let status = item.GetCurrentStatus()?; + let state = status.PackageInstallState()?; + if matches!( + state, + StoreQueueItemState::Active | StoreQueueItemState::Paused + ) { + let reason = status.PackageInstallExtendedState().unwrap_or_default(); + return Ok(Some(of_the_queue(state, reason))); + } + } + Ok(None) + } + + pub(super) fn of_the_queue( + state: StoreQueueItemState, + reason: StoreQueueItemExtendedState, + ) -> Shelf { + let waits_for_us = matches!( + reason, + StoreQueueItemExtendedState::PausedPackagesInUse + | StoreQueueItemExtendedState::PausedReadyToInstall + ); + if state == StoreQueueItemState::Paused && !waits_for_us { + Shelf::Paused + } else { + Shelf::Queued + } + } + + fn beside_us() -> Option { + let ours = Package::Current().ok()?; + let family = ours.Id().ok()?.FamilyName().ok()?; + let mine: semver::Version = numbered(&ours.Id().ok()?.Version().ok()?).parse().ok()?; + let this_user = HSTRING::new(); + PackageManager::new() + .ok()? + .FindPackagesByUserSecurityIdPackageFamilyName(&this_user, &family) + .ok()? + .into_iter() + .filter_map(|one| numbered(&one.Id().ok()?.Version().ok()?).parse().ok()) + .filter(|said: &semver::Version| *said > mine) + .max() + .map(|newest| newest.to_string()) + } + + /// The package an offer names is the one installed here, so its number says nothing of what comes. + fn waiting(window: isize) -> windows::core::Result { let updates = shop(window)? .GetAppAndOptionalStorePackageUpdatesAsync()? .join()?; let ours = Package::Current()?.Id()?.FamilyName()?; for one in 0..updates.Size()? { - let id = updates.GetAt(one)?.Package()?.Id()?; - if id.FamilyName()? == ours { - return Ok(Some(numbered(&id.Version()?))); + if updates.GetAt(one)?.Package()?.Id()?.FamilyName()? == ours { + return Ok(true); } } - Ok(None) + Ok(false) } pub fn take( @@ -200,7 +423,15 @@ mod there { mod there { use super::{Shelf, Trouble}; - pub fn asked(_window: isize) -> Shelf { + pub const fn settled() -> Option { + None + } + + pub const fn sold_here() -> bool { + false + } + + pub const fn asked(_window: isize, _waits: bool) -> Shelf { Shelf::Silent } @@ -214,7 +445,27 @@ mod there { #[cfg(test)] mod tests { - use super::step; + use super::*; + + const NOW: &str = "2.8.0"; + + fn offered_before(version: Option<&str>) -> Memory { + Memory { + version: version.map(str::to_owned), + offered: Some(true), + } + } + + fn coming_before(version: &str) -> Memory { + Memory { + version: Some(version.to_owned()), + offered: Some(false), + } + } + + fn known(version: &str) -> Ahead { + Ahead::Is(version.to_owned()) + } #[test] fn the_download_fills_the_bar_on_its_own() { @@ -235,4 +486,240 @@ mod tests { assert_eq!(step(-1.0), ("getting", 0)); assert_eq!(step(2.0), ("installing", 100)); } + + #[test] + fn the_store_s_offer_can_be_taken_whatever_is_known_of_its_number() { + let named = verdict(Shelf::Waiting, known("2.9.0"), NOW, Memory::default()); + let ready = named.ready.expect("an offer"); + assert!(ready.installs); + assert_eq!(ready.version, "2.9.0"); + assert_eq!(named.memory, offered_before(Some("2.9.0"))); + + for ahead in [Ahead::Nothing, Ahead::Unheard] { + let ready = verdict(Shelf::Waiting, ahead, NOW, Memory::default()).ready; + let ready = ready.expect("an offer with no number is still an offer"); + assert!(ready.installs); + assert_eq!(ready.version, ""); + } + } + + #[test] + fn with_nobody_able_to_say_the_version_known_stays_while_it_is_still_ahead() { + let ahead_of_us = verdict(Shelf::Waiting, Ahead::Unheard, NOW, coming_before("2.9.0")); + assert_eq!(ahead_of_us.ready.expect("an offer").version, "2.9.0"); + + let behind_us = verdict(Shelf::Waiting, Ahead::Unheard, NOW, coming_before("2.8.0")); + assert_eq!(behind_us.ready.expect("an offer").version, ""); + } + + #[test] + fn what_already_landed_offers_nothing_to_press() { + let landed = verdict( + Shelf::Landed("2.9.0".into()), + Ahead::Nothing, + NOW, + Memory::default(), + ); + let ready = landed.ready.expect("it is here"); + assert!(!ready.installs); + assert_eq!(ready.version, "2.9.0"); + assert_eq!(ready.coming, None); + } + + #[test] + fn a_queue_held_up_is_told_apart_from_one_that_finishes_by_itself() { + let moving = verdict(Shelf::Queued, known("2.9.0"), NOW, Memory::default()); + assert_eq!( + moving.ready.expect("on its way").coming, + Some(Coming::Queued) + ); + + let paused = verdict(Shelf::Paused, known("2.9.0"), NOW, Memory::default()); + let paused = paused.ready.expect("paused there"); + assert_eq!(paused.coming, Some(Coming::Paused)); + assert!(!paused.installs, "only the Store can start it again"); + } + + #[test] + fn a_copy_the_store_did_not_sell_is_never_told_the_store_brings_anything() { + let said = verdict( + Shelf::NotSold, + known("2.9.0"), + NOW, + offered_before(Some("2.9.0")), + ); + assert_eq!(said.ready, None); + assert_eq!(said.memory, Memory::default()); + assert!(!said.unanswered, "the Store was never asked"); + } + + #[test] + fn a_version_the_catalog_lists_is_on_its_way_even_when_the_store_says_nothing() { + for shelf in [Shelf::Current, Shelf::Silent] { + let said = verdict(shelf, known("2.9.0"), NOW, Memory::default()); + let ready = said.ready.expect("on its way"); + assert_eq!(ready.coming, Some(Coming::NotYet)); + assert!(!ready.installs); + assert_eq!(said.memory, coming_before("2.9.0")); + assert!(!said.unanswered); + } + } + + #[test] + fn a_store_that_answered_and_a_catalog_with_nothing_newer_end_the_matter() { + let said = verdict( + Shelf::Current, + Ahead::Nothing, + NOW, + offered_before(Some("2.9.0")), + ); + assert_eq!(said.ready, None); + assert_eq!(said.memory, Memory::default()); + assert!(!said.unanswered); + } + + #[test] + fn a_store_that_did_not_answer_is_reported_even_when_the_catalog_lists_nothing_newer() { + let offer = verdict( + Shelf::Silent, + Ahead::Nothing, + NOW, + offered_before(Some("2.9.0")), + ); + assert!(offer.unanswered); + assert!(offer.ready.expect("its own offer stands").installs); + assert_eq!(offer.memory, offered_before(Some("2.9.0"))); + + let coming = verdict(Shelf::Silent, Ahead::Nothing, NOW, coming_before("2.9.0")); + assert!(coming.unanswered); + assert_eq!( + coming.ready, None, + "the catalog says no such version is out" + ); + assert_eq!(coming.memory, Memory::default()); + } + + #[test] + fn the_store_saying_it_has_no_offer_takes_back_the_offer_it_made() { + let said = verdict( + Shelf::Current, + Ahead::Unheard, + NOW, + offered_before(Some("2.9.0")), + ); + assert_eq!(said.ready, None); + assert_eq!(said.memory, Memory::default()); + + let coming = verdict(Shelf::Current, Ahead::Unheard, NOW, coming_before("2.9.0")); + assert!(coming.ready.expect("still on its way").coming.is_some()); + assert_eq!(coming.memory, coming_before("2.9.0")); + } + + #[test] + fn a_store_that_did_not_answer_leaves_what_it_last_said_standing() { + let said = verdict( + Shelf::Silent, + Ahead::Unheard, + NOW, + offered_before(Some("2.9.0")), + ); + assert!(said.ready.expect("still standing").installs); + assert_eq!(said.memory, offered_before(Some("2.9.0"))); + assert!(said.unanswered); + } + + #[test] + fn what_was_last_said_ends_when_this_copy_catches_up_or_had_no_number() { + assert_eq!(last_said(NOW, &offered_before(Some("2.8.0"))), None); + assert_eq!(last_said(NOW, &coming_before("2.8.0")), None); + assert_eq!(last_said(NOW, &offered_before(None)), None); + assert_eq!(last_said(NOW, &Memory::default()), None); + let offer = last_said(NOW, &offered_before(Some("2.9.0"))); + assert!(offer.expect("an offer").installs); + let coming = last_said(NOW, &coming_before("2.9.0")); + assert!(coming.expect("on its way").coming.is_some()); + } + + #[test] + fn only_a_press_is_waited_for_and_only_when_there_may_be_something() { + assert!(waits(true, &known("2.9.0"))); + assert!(waits(true, &Ahead::Unheard)); + assert!(!waits(true, &Ahead::Nothing)); + assert!(!waits(false, &known("2.9.0"))); + assert!(!waits(false, &Ahead::Unheard)); + } + + #[test] + fn only_a_press_is_told_the_store_did_not_answer() { + let said = verdict(Shelf::Silent, Ahead::Unheard, NOW, Memory::default()); + assert!(said.refused(true)); + assert!(!said.refused(false)); + + let answered = verdict(Shelf::Current, Ahead::Nothing, NOW, Memory::default()); + assert!(!answered.refused(true)); + } + + #[test] + fn the_file_the_resident_reads_keeps_what_the_store_said() { + for memory in [ + offered_before(Some("2.9.0")), + coming_before("2.9.0"), + offered_before(None), + Memory::default(), + ] { + let mut looked = Looked { + candidates: Some(true), + ..Looked::default() + }; + memory.clone().written_into(&mut looked); + assert_eq!(Memory::of(&looked), memory); + assert_eq!( + looked.candidates, + Some(true), + "the track is not the Store's" + ); + } + + let offer = { + let mut looked = Looked::default(); + offered_before(Some("2.9.0")).written_into(&mut looked); + looked + }; + assert_eq!(offer.found_route.as_deref(), Some("store")); + assert_eq!(offer.found_installs, Some(true)); + } + + #[test] + fn a_download_s_offer_written_down_is_not_taken_for_the_store_s() { + let looked = Looked { + found_version: Some("2.9.0".into()), + found_route: Some("download".into()), + found_installs: Some(true), + ..Looked::default() + }; + assert_eq!(Memory::of(&looked).offered, None); + } + + #[cfg(windows)] + #[test] + fn only_what_quitting_linkunbound_will_not_clear_counts_as_paused() { + use windows::Services::Store::{ + StoreQueueItemExtendedState as Reason, StoreQueueItemState as State, + }; + + for reason in [ + Reason::Paused, + Reason::PausedLowBattery, + Reason::PausedWiFiRequired, + ] { + assert_eq!(there::of_the_queue(State::Paused, reason), Shelf::Paused); + } + for reason in [Reason::PausedPackagesInUse, Reason::PausedReadyToInstall] { + assert_eq!(there::of_the_queue(State::Paused, reason), Shelf::Queued); + } + assert_eq!( + there::of_the_queue(State::Active, Reason::ActiveDownloading), + Shelf::Queued + ); + } } diff --git a/app/src-tauri/src/update.rs b/app/src-tauri/src/update.rs index c65249d..9c8964a 100644 --- a/app/src-tauri/src/update.rs +++ b/app/src-tauri/src/update.rs @@ -16,6 +16,17 @@ pub const LATEST: &str = pub const CANDIDATE: &str = "https://raw.githubusercontent.com/rgdevment/LinkUnbound/manifest/candidate.json"; +/// Market and language are fixed, so the request says nothing of the person making it. +const CATALOG: &str = + "https://displaycatalog.mp.microsoft.com/v7.0/products/9N9F7C8Q43KC?market=US&languages=en-US"; +const STORE_FAMILY: &str = "rgdevment.LinkUnbound-BrowserPicker_kdjgfdc2rb3gc"; +const STORE_ARCH: &str = if cfg!(target_arch = "aarch64") { + "arm64" +} else { + "x64" +}; +const LISTING_AT_MOST: u64 = 256 * 1024; + const PATIENCE: Duration = Duration::from_secs(5); const APART: u64 = 24 * 60 * 60; @@ -49,6 +60,22 @@ pub struct Ready { pub route: Route, pub package: Option<&'static str>, pub installs: bool, + pub coming: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Coming { + Queued, + Paused, + NotYet, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Look { + Now, + Pressed, } impl Route { @@ -142,19 +169,29 @@ pub fn newer(now: &str, manifest: &str, kept: Kept, wants: Option) -> Opti (best > here).then(|| offered(best.to_string(), kept)) } -/// `self_installs` says no for the Store because a copy kept there cannot replace itself from a -/// download; an offer the Store itself made is the one it can take without leaving the window. #[must_use] -pub fn from_the_shop(version: &str, now: &str) -> Option { - let here: semver::Version = now.parse().ok()?; - let said: semver::Version = version.parse().ok()?; - - (said > here).then(|| Ready { - version: said.to_string(), +pub fn from_the_shop(version: Option<&str>) -> Ready { + Ready { + version: version.unwrap_or_default().to_owned(), route: Route::Store, package: None, installs: true, - }) + coming: None, + } +} + +#[must_use] +pub fn on_its_way(version: Option<&str>, coming: Coming) -> Ready { + Ready { + installs: false, + coming: Some(coming), + ..from_the_shop(version) + } +} + +#[must_use] +pub fn later(now: &str, found: &str) -> bool { + linkunbound_core::update::newer_than(found, now) } fn offered(version: String, kept: Kept) -> Ready { @@ -166,6 +203,7 @@ fn offered(version: String, kept: Kept) -> Ready { // `update_install` reads the same thing: offering a button it will take away is worse // than not offering one. installs: self_installs(kept.route) && !from_a_mount(), + coming: None, } } @@ -256,20 +294,113 @@ fn chosen(running: Option<&Path>, there: impl Fn(&Path) -> bool) -> Kept { Kept::plain(Route::Download) } -#[must_use] -pub fn fetch() -> Option { - let asked = reqwest::blocking::Client::builder() +fn client() -> Option { + reqwest::blocking::Client::builder() .timeout(PATIENCE) .user_agent(concat!("linkunbound/", env!("CARGO_PKG_VERSION"))) .build() - .ok()? - .get(MANIFEST) - .send() - .ok()?; + .ok() +} + +#[must_use] +pub fn fetch() -> Option { + let asked = client()?.get(MANIFEST).send().ok()?; asked.status().is_success().then(|| asked.text().ok())? } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Ahead { + Unheard, + Nothing, + Is(String), +} + +fn ours_in_the_catalog(full: &str, arch: &str) -> Option { + let mut parts = full.split('_'); + let (name, version, built_for, publisher) = ( + parts.next()?, + parts.next()?, + parts.next()?, + parts.next_back()?, + ); + if format!("{name}_{publisher}") != STORE_FAMILY || ![arch, "neutral"].contains(&built_for) { + return None; + } + let mut numbers = version.split('.'); + format!( + "{}.{}.{}", + numbers.next()?, + numbers.next()?, + numbers.next()? + ) + .parse() + .ok() +} + +/// Microsoft does not document this answer, so one with no package of ours in it says nothing. +#[must_use] +pub fn listed(now: &str, arch: &str, said: &str) -> Ahead { + let Ok(here) = now.parse::() else { + return Ahead::Unheard; + }; + let Ok(read) = serde_json::from_str::(said) else { + return Ahead::Unheard; + }; + let best = read + .pointer("/Product/DisplaySkuAvailabilities") + .and_then(serde_json::Value::as_array) + .into_iter() + .flatten() + .filter_map(|one| one.pointer("/Sku/Properties/Packages")?.as_array()) + .flatten() + .filter_map(|package| package.get("PackageFullName")?.as_str()) + .filter_map(|full| ours_in_the_catalog(full, arch)) + .max(); + match best { + None => Ahead::Unheard, + Some(best) if best > here => Ahead::Is(best.to_string()), + Some(_) => Ahead::Nothing, + } +} + +#[must_use] +pub fn catalog(now: &str) -> Ahead { + use std::io::Read; + + let Some(answer) = client().and_then(|asking| asking.get(CATALOG).send().ok()) else { + return Ahead::Unheard; + }; + if !answer.status().is_success() { + return Ahead::Unheard; + } + let mut said = String::new(); + if answer + .take(LISTING_AT_MOST) + .read_to_string(&mut said) + .is_err() + { + return Ahead::Unheard; + } + listed(now, STORE_ARCH, &said) +} + +pub fn ahead( + now: &str, + wants: Option, + catalog: Ahead, + feed: impl FnOnce() -> Option, +) -> Ahead { + if catalog != Ahead::Unheard { + return catalog; + } + let Some(said) = feed().filter(|said| serde_json::from_str::(said).is_ok()) else { + return Ahead::Unheard; + }; + newer(now, &said, Kept::plain(Route::Store), wants) + .map_or(Ahead::Nothing, |one| Ahead::Is(one.version)) +} + pub use linkunbound_core::update::{Progress, keep, looked, progress, settle, tell, under_way_for}; #[cfg(test)] @@ -468,11 +599,9 @@ mod tests { assert!(!tracking("tomorrow", None), "unreadable means stable"); } - /// The store's own offer is the one a store copy can take without leaving the window, and it - /// is the only place `installs` is decided by anything other than the route. #[test] fn an_offer_the_store_itself_made_is_one_it_can_install() { - let found = from_the_shop("2.1.0", "2.0.0").expect("the store has something newer"); + let found = from_the_shop(Some("2.1.0")); assert_eq!(found.version, "2.1.0"); assert_eq!(found.route, Route::Store); @@ -480,6 +609,7 @@ mod tests { found.installs, "a store copy cannot install from a download, but it can take what the store offered" ); + assert_eq!(found.coming, None); assert!( !self_installs(Route::Store), "which is why the route alone must not decide this" @@ -487,15 +617,143 @@ mod tests { } #[test] - fn the_store_offering_nothing_newer_is_not_an_update() { - assert!(from_the_shop("2.0.0", "2.0.0").is_none()); - assert!(from_the_shop("1.9.0", "2.0.0").is_none()); + fn an_offer_with_no_number_can_still_be_taken() { + let offer = from_the_shop(None); + + assert_eq!(offer.version, ""); assert!( - from_the_shop("2.0.0.4", "2.0.0").is_none(), - "a package version has four parts and a release has three" + offer.installs, + "the Store said it has one, and that is enough" ); } + #[test] + fn what_the_store_is_still_bringing_has_no_button() { + let coming = on_its_way(Some("2.1.0"), Coming::Paused); + + assert_eq!(coming.version, "2.1.0"); + assert_eq!(coming.route, Route::Store); + assert!(!coming.installs); + assert_eq!(coming.coming, Some(Coming::Paused)); + } + + fn catalog_naming(packages: &[&str]) -> String { + let named: Vec<_> = packages + .iter() + .map(|full| serde_json::json!({"PackageFullName": full, "PackageFormat": "Msix"})) + .collect(); + serde_json::json!({"Product": {"DisplaySkuAvailabilities": [ + {"Sku": {"SkuId": "0010", "Properties": {"Packages": named}}}, + {"Sku": {"SkuId": "0011", "Properties": {"Packages": null}}}, + ]}}) + .to_string() + } + + const OURS_28: &str = "rgdevment.LinkUnbound-BrowserPicker_2.8.0.0_x64__kdjgfdc2rb3gc"; + const OURS_29: &str = "rgdevment.LinkUnbound-BrowserPicker_2.9.0.0_x64__kdjgfdc2rb3gc"; + + #[test] + fn the_catalog_names_the_newest_of_ours_it_lists() { + let said = catalog_naming(&[OURS_28, OURS_29]); + + assert_eq!(listed("2.8.0", "x64", &said), Ahead::Is("2.9.0".into())); + assert_eq!(listed("2.9.0", "x64", &said), Ahead::Nothing); + assert_eq!(listed("3.0.0", "x64", &said), Ahead::Nothing); + } + + #[test] + fn a_package_that_is_not_ours_is_not_counted_as_the_catalog_answering() { + for full in [ + "Another.App_9.0.0.0_x64__kdjgfdc2rb3gc", + "rgdevment.LinkUnbound-BrowserPicker_9.0.0.0_x64__someoneelse", + "rgdevment.LinkUnbound-BrowserPicker_9.0_x64__kdjgfdc2rb3gc", + "rgdevment.LinkUnbound-BrowserPicker", + ] { + assert_eq!( + listed("2.8.0", "x64", &catalog_naming(&[full])), + Ahead::Unheard, + "{full}" + ); + } + } + + #[test] + fn a_package_built_for_another_machine_is_not_one_this_copy_can_be_given() { + let said = catalog_naming(&[ + OURS_29, + "rgdevment.LinkUnbound-BrowserPicker_9.0.0.0_arm64__kdjgfdc2rb3gc", + ]); + assert_eq!(listed("2.8.0", "x64", &said), Ahead::Is("2.9.0".into())); + assert_eq!(listed("2.8.0", "arm64", &said), Ahead::Is("9.0.0".into())); + + let bundled = catalog_naming(&[ + "rgdevment.LinkUnbound-BrowserPicker_2.9.0.0_neutral_~_kdjgfdc2rb3gc", + ]); + assert_eq!(listed("2.8.0", "x64", &bundled), Ahead::Is("2.9.0".into())); + } + + #[test] + fn a_catalog_that_stopped_reading_as_it_did_says_nothing_rather_than_nothing_newer() { + for said in [ + "", + "not json", + "{}", + r#"{"Product":null}"#, + r#"{"Product":{"DisplaySkuAvailabilities":[]}}"#, + ] { + assert_eq!(listed("2.8.0", "x64", said), Ahead::Unheard, "{said}"); + } + assert_eq!( + listed("tomorrow", "x64", &catalog_naming(&[OURS_29])), + Ahead::Unheard + ); + } + + #[test] + fn a_catalog_that_answered_is_not_second_guessed_by_the_feed() { + let no_feed = || panic!("the catalog answered, so nothing should go to GitHub"); + + assert_eq!( + ahead("2.8.0", None, Ahead::Is("2.9.0".into()), no_feed), + Ahead::Is("2.9.0".into()) + ); + assert_eq!( + ahead("2.8.0", None, Ahead::Nothing, no_feed), + Ahead::Nothing + ); + } + + #[test] + fn the_feed_stands_in_for_a_catalog_nobody_could_read() { + let feed = |said: &str| Some(format!(r#"{{"schema":1,"latest":"{said}"}}"#)); + + assert_eq!( + ahead("2.8.0", None, Ahead::Unheard, || feed("2.9.0")), + Ahead::Is("2.9.0".into()) + ); + assert_eq!( + ahead("2.9.0", None, Ahead::Unheard, || feed("2.9.0")), + Ahead::Nothing + ); + assert_eq!( + ahead("2.8.0", None, Ahead::Unheard, || None), + Ahead::Unheard + ); + assert_eq!( + ahead("2.8.0", None, Ahead::Unheard, || Some("not json".into())), + Ahead::Unheard, + "a feed nobody can read says nothing either" + ); + } + + #[test] + fn what_the_catalog_names_is_the_identity_the_release_checks() { + let workflow = include_str!("../../../.github/workflows/release.yml"); + let (name, _) = STORE_FAMILY.split_once('_').expect("a family"); + + assert!(workflow.contains(&format!("$was = \"{name}\""))); + } + #[test] fn only_a_copy_that_owns_its_own_folder_replaces_itself() { assert!(self_installs(Route::Download)); diff --git a/app/src/i18n.ts b/app/src/i18n.ts index 06fb6ad..6b3e92e 100644 --- a/app/src/i18n.ts +++ b/app/src/i18n.ts @@ -284,7 +284,6 @@ const ES = { candidatesNote: "Llegan antes y están menos probadas. Puedes volver a las estables cuando quieras.", updateStore: "La instala Microsoft Store, sin salir de aquí", - updateStoreByHand: "Instálala desde Microsoft Store: esta copia no puede hacerlo por sí sola", updateFromMount: "Mueve LinkUnbound a Aplicaciones y ábrelo desde ahí; desde la imagen de disco no puede actualizarse", updateWaiting: "hay una versión nueva", @@ -293,6 +292,22 @@ const ES = { lookNow: "Buscar ahora", lookingNow: "Buscando…", lookNowNone: "Estás en la última versión", + lookNowNoneStore: "Microsoft Store no tiene nada más nuevo para esta copia ahora mismo", + lookStoreKeeps: + "Microsoft Store mantiene esta copia al día. Se le pregunta cada vez que abres esta ventana", + lookNotSold: + "Esta copia no vino de Microsoft Store, así que la Store no la actualiza y ella no puede hacerlo sola", + updateOffered: "Microsoft Store tiene una versión nueva", + updateComing: "Microsoft Store está trayendo una versión nueva", + updateComingWhy: + "Microsoft Store la trae por su cuenta. Se instala sola cuando llegue y LinkUnbound no esté abierto: ni esta ventana ni el icono de la bandeja.", + updatePausedWhy: "Microsoft Store la tiene en pausa. Ábrela para reanudarla.", + updateNotYetWhy: + "Microsoft Store todavía no se la ofrece a este equipo. Suele tardar unas horas; puedes revisarlo en la Store.", + updateLanded: + "Ya está en este equipo y entra cuando LinkUnbound no esté abierto: ni esta ventana ni el icono de la bandeja", + updateOpenShop: "Abrir Microsoft Store", + updateUnanswered: "Microsoft Store no respondió; vuelve a intentarlo en un rato", aboutWhat: "Cuando abres un enlace, LinkUnbound te pregunta en qué navegador quieres que se abra. Y si siempre respondes lo mismo, deja de preguntar.", aboutPrivacy: @@ -627,7 +642,6 @@ const EN: Record = { candidatesNote: "They arrive sooner and are less tested. You can go back to the stable ones whenever you like.", updateStore: "Microsoft Store installs it, without leaving this window", - updateStoreByHand: "Install it from Microsoft Store: this copy cannot do it on its own", updateFromMount: "Move LinkUnbound to Applications and open it from there; it cannot update from the disk image", updateWaiting: "a new version is waiting", @@ -636,6 +650,22 @@ const EN: Record = { lookNow: "Check now", lookingNow: "Checking…", lookNowNone: "You are on the latest version", + lookNowNoneStore: "Microsoft Store has nothing newer for this copy right now", + lookStoreKeeps: + "Microsoft Store keeps this copy up to date. It is asked every time you open this window", + lookNotSold: + "This copy did not come from Microsoft Store, so the Store does not update it and it cannot update itself", + updateOffered: "Microsoft Store has a new version", + updateComing: "Microsoft Store is bringing a new version", + updateComingWhy: + "Microsoft Store brings it on its own. It installs itself once it lands and LinkUnbound is not running: neither this window nor the icon in the tray.", + updatePausedWhy: "Microsoft Store has it paused. Open it to resume.", + updateNotYetWhy: + "Microsoft Store has not offered it to this computer yet. That usually takes a few hours; you can check in the Store.", + updateLanded: + "It is already on this computer and takes over once LinkUnbound is not running: neither this window nor the icon in the tray", + updateOpenShop: "Open Microsoft Store", + updateUnanswered: "Microsoft Store did not answer; try again in a while", aboutWhat: "When you open a link, LinkUnbound asks which browser you want it in. And once you keep giving the same answer, it stops asking.", aboutPrivacy: diff --git a/app/src/settings/About.test.tsx b/app/src/settings/About.test.tsx index c0c3ee1..d05f584 100644 --- a/app/src/settings/About.test.tsx +++ b/app/src/settings/About.test.tsx @@ -57,10 +57,11 @@ function Host({ starring={asking} onStarSettled={() => setAsking(false)} onSettled={settled} - onLook={(nowPlease) => - invoke("update_ready", { nowPlease }).then((one: unknown) => { - setReady((one ?? null) as Ready | null); - return one; + onLook={(look) => + invoke("update_ready", { look }).then((one: unknown) => { + const said = (one ?? null) as Ready | null; + setReady(said); + return said; }) } /> @@ -189,7 +190,7 @@ describe("about", () => { show(); await userEvent.click(screen.getByRole("button", { name: "Buscar ahora" })); - expect(invoke).toHaveBeenCalledWith("update_ready", { nowPlease: true }); + expect(invoke).toHaveBeenCalledWith("update_ready", { look: "pressed" }); expect(screen.getByText("Buscando…")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Buscar ahora" })).toBeDisabled(); @@ -202,7 +203,7 @@ describe("about", () => { it("says what to do when the copy cannot install what it found", () => { show({ ...NEWER, route: "store", installs: false }); expect(screen.queryByRole("button", { name: "Actualizar" })).toBeNull(); - expect(screen.getByText(/Instálala desde Microsoft Store/)).toBeInTheDocument(); + expect(screen.getByText(/Ya está en este equipo/)).toBeInTheDocument(); cleanup(); show({ ...NEWER, route: "brew", installs: false }); @@ -210,6 +211,63 @@ describe("about", () => { expect(screen.getByText(/Mueve LinkUnbound a Aplicaciones/)).toBeInTheDocument(); }); + it("offers what the store has even when nobody can say its number", () => { + show({ ...FROM_STORE, version: "" }); + expect(screen.getByText("Microsoft Store tiene una versión nueva")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Actualizar" })).toBeEnabled(); + }); + + it("tells a store copy why it can only wait, and opens the store for it", async () => { + const waiting: Ready = { ...FROM_STORE, version: "", installs: false }; + + show({ ...waiting, coming: "queued" }); + expect(screen.getByText("Microsoft Store está trayendo una versión nueva")).toBeInTheDocument(); + expect(screen.getByText(/ni el icono de la bandeja/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Actualizar" })).toBeNull(); + cleanup(); + + show({ ...waiting, coming: "notYet", version: "2.1.0" }); + expect(screen.getByText("Versión 2.1.0 disponible")).toBeInTheDocument(); + expect(screen.getByText(/todavía no se la ofrece a este equipo/)).toBeInTheDocument(); + cleanup(); + + show({ ...waiting, coming: "paused" }); + expect(screen.getByText("Microsoft Store tiene una versión nueva")).toBeInTheDocument(); + expect(screen.getByText(/la tiene en pausa/)).toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "Abrir Microsoft Store" })); + expect(opened).toEqual(["ms-windows-store://downloadsandupdates"]); + }); + + it("says the store has nothing newer only once the store said so", async () => { + answers({ about: () => Promise.resolve({ ...BUILD, keptByTheStore: true }) }); + show(); + expect( + await screen.findByText(/Microsoft Store mantiene esta copia al día/), + ).toBeInTheDocument(); + + await userEvent.click(screen.getByRole("button", { name: "Buscar ahora" })); + expect( + await screen.findByText( + "Microsoft Store no tiene nada más nuevo para esta copia ahora mismo", + ), + ).toBeInTheDocument(); + }); + + it("tells a copy the store did not sell that the store does not update it", async () => { + answers({ + about: () => Promise.resolve({ ...BUILD, keptByTheStore: true, notSold: true }), + }); + show(); + expect(await screen.findByText(/Esta copia no vino de Microsoft Store/)).toBeInTheDocument(); + }); + + it("says plainly when the store did not answer a press", async () => { + answers({ update_ready: () => Promise.reject("updateUnanswered") }); + show(); + await userEvent.click(screen.getByRole("button", { name: "Buscar ahora" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Microsoft Store no respondió"); + }); + it("looks again when the offer it pressed is off the feed, and shows what is out now", async () => { answers({ update_install: () => Promise.reject("updateMoved:2.1.1"), diff --git a/app/src/settings/About.tsx b/app/src/settings/About.tsx index 8e5a644..17dc900 100644 --- a/app/src/settings/About.tsx +++ b/app/src/settings/About.tsx @@ -10,7 +10,7 @@ import { offerMoved, saidPlainly } from "../refusal"; import { CloudOff, Code, Gift, Key as KeyIcon } from "./Icons"; import { Card, Line, Switch } from "./parts"; import Star from "./Star"; -import type { Ready, Underway } from "./update"; +import type { Look, Ready, StoreWait, Underway } from "./update"; const REPO = "https://github.com/rgdevment/LinkUnbound"; const COFFEE = "https://buymeacoffee.com/rgdevment"; @@ -18,6 +18,7 @@ const COPANDA = "https://www.copanda.app/"; const TISTY = "https://www.tisty.app/"; const SPONSOR = "https://github.com/sponsors/rgdevment"; const RATING = "ms-windows-store://review/?ProductId=9N9F7C8Q43KC"; +const SHELF = "ms-windows-store://downloadsandupdates"; const ALTERNATIVETO = "https://alternativeto.net/software/linkunbound/"; type Build = { @@ -27,14 +28,28 @@ type Build = { candidates: boolean; candidatesApply: boolean; keptByTheStore: boolean; + notSold?: boolean; +}; + +const WAITS: Record = { + queued: "updateComingWhy", + paused: "updatePausedWhy", + notYet: "updateNotYetWhy", }; -/// What happens on «Actualizar» — or, when there is no button, what the person has to do instead: -/// a copy the store keeps but did not sell cannot be installed from here, and one running from -/// the disk image it was downloaded as cannot replace itself. function howItInstalls(newer: Ready): Key { if (newer.installs) return newer.route === "store" ? "updateStore" : "updateAsk"; - return newer.route === "store" ? "updateStoreByHand" : "updateFromMount"; + if (newer.coming) return WAITS[newer.coming]; + return newer.route === "store" ? "updateLanded" : "updateFromMount"; +} + +function headline(newer: Ready): Key { + return newer.installs || newer.coming === "paused" ? "updateOffered" : "updateComing"; +} + +function nothingFound(build: Build | null): Key { + if (!build?.keptByTheStore) return "lookNowNone"; + return build.notSold ? "lookNotSold" : "lookNowNoneStore"; } function External({ href, children }: { href: string; children: string }) { @@ -135,25 +150,30 @@ function Pip({ ok }: { ok?: boolean }) { function Offer({ ready, step, + build, onProblem, onSettled, onLook, }: { ready: Ready | null; step: Underway | null; + build: Build | null; onProblem: (why: string | null) => void; onSettled: () => void; - onLook: (nowPlease?: boolean) => Promise; + onLook: (how?: Look) => Promise; }) { const t = useWords(); const language = useSpoken(); const [looking, setLooking] = useState(false); const [asked, setAsked] = useState(false); + const [nothingSaid, setNothingSaid] = useState(false); const lookAgain = () => { setLooking(true); onProblem(null); - onLook(true) + setNothingSaid(false); + onLook("pressed") + .then((one) => setNothingSaid(!one)) .catch((e: unknown) => onProblem(saidPlainly(language, e))) .finally(() => setLooking(false)); }; @@ -165,7 +185,15 @@ function Offer({
- {looking ? t("lookingNow") : t("lookNowNone")} + + {looking + ? t("lookingNow") + : t( + nothingSaid || !build?.keptByTheStore || build.notSold + ? nothingFound(build) + : "lookStoreKeeps", + )} + + )} {!step && newer.installs && (