Bind Developer Build installs to the shown offer; finish wait and hold recovery

- Command::InstallOffer carries the exact release a card shows; Native refuses it
  visibly, before any reservation, descriptor or package request, when the one
  exact capture differs. App-only Install keeps its meaning for headless callers;
  Stable refuses the new command.
- A server's descriptor Retry-After on the recorded build keeps the current listing
  eligible (time hold only); malformed/other verification failures, an expired or
  replaced listing and a storage failure stay blocked; the next click after the
  deadline verifies the descriptor again.
- The ArtCraft throttle's catalog hold reaches CheckFinished (catalog deadline only),
  and the page's hold line uses the neutral "Next check at" wording.
- Signed-expiry revalidation never shortens the one-minute coalescing window, in
  Native and in the UI's mirrored request gate.
- Native test-support feature (test-only, off by default) and a non-wasm UI
  dev-dependency let UI tests run on events a real Native backend produces.
This commit is contained in:
skylartaylor committed 2026-11-29 04:23:50 +01:00
1 parent 0426517966
commit cfc04ea607
12 files changed
+452 -49

No files matched your search

Generated
+1
View File
@@ -375,6 +375,7 @@ name = "artcraft-launcher-ui-egui"
version = "0.20.4"
dependencies = [
"artcraft-launcher-core",
"artcraft-launcher-native",
"craft-font-manager",
"craft-font-store",
"craft-host",
+8
View File
@@ -29,6 +29,14 @@ pub enum Command {
Install {
app: String,
},
/// A Developer Build `Install`/`Update` for exactly the build the person was shown (`offer` is
/// the `Latest` release on its card). Refused before anything is reserved or fetched when
/// the current offer differs in any way (tag, packages, checksums, sizes, addresses). Stable
/// backends refuse it; `Install` keeps its app-only meaning for every channel.
InstallOffer {
app: String,
offer: Box<Release>,
},
/// Install or update every app in `apps` together: their downloads run as for [`Command::Install`],
/// but where the platform needs a permission prompt (polkit on Linux, elevation on Windows)
/// the batch shares one prompt instead of one per app. Apps already running a job are left out.
+4
View File
@@ -15,6 +15,10 @@ workspace = true
# (`cargo xtask local serve`). Development only: release builds never enable it, so a shipped
# launcher can't be steered away from GitHub's releases by an environment variable.
local-mirror = ["craft-update/local-mirror"]
# Test infrastructure only: `backend::test_support` and the in-memory HTTP transport it needs, so
# another crate's tests (the UI's) can drive a real Developer Builds backend with Native-produced
# events. Only the UI's non-wasm dev-dependency enables it; production, desktop and wasm builds never do.
test-support = []
[dependencies]
artcraft-launcher-core = { workspace = true }
+40 -4
View File
@@ -1073,7 +1073,13 @@ impl NativeBackend {
}
}
drop(lease);
let retry = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).backoff(crate::now());
// A catalog server backoff or the ArtCraft throttle's hold: both mean "ask again at this
// time". A build's descriptor wait is not a catalog hold and stays in its status.
let retry = {
let state = shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner);
let now = crate::now();
state.backoff(now).into_iter().chain(state.catalog_hold(now)).max()
};
shared.emit(Event::CheckFinished {
at: crate::now(),
source: if used_catalog { Source::Feed } else { Source::Cache },
@@ -1235,6 +1241,13 @@ impl NativeBackend {
/// entry and the place back. A batch prepares every member before starting any, so no worker
/// can reach a free download slot ahead of a row above it that hasn't taken its place yet.
fn prepare_job(&self, app_id: &str, work: Work) -> Option<Box<dyn FnOnce() + Send>> {
self.prepare_job_expecting(app_id, work, None)
}
/// [`Self::prepare_job`] for a Developer Build install bound to the `offer` its card showed
/// ([`Command::InstallOffer`]): the one exact capture must still be that release, or the job
/// is refused before any reservation, descriptor or package request.
fn prepare_job_expecting(&self, app_id: &str, work: Work, offer: Option<&Release>) -> Option<Box<dyn FnOnce() + Send>> {
// This is also called by bulk installs: a guard only in start_job is bypassable.
if self.refuse_unavailable_nightly_job(app_id, &work) {
return None;
@@ -1242,6 +1255,11 @@ impl NativeBackend {
let nightly_candidate =
if self.shared.channel == artcraft_launcher_core::nightly::InstallChannel::Nightly && matches!(work, Work::Install(None)) {
match selected_nightly(CraftApp::by_id(app_id)?, &self.shared, self.platform?) {
Ok(selected) if offer.is_some_and(|offer| *offer != selected.release) => {
let error = "The Developer Build changed after it was shown. Review the updated build, then install it.".into();
self.shared.emit(Event::NightlyJobRefused { app: app_id.into(), operation: work.nightly_operation(), error });
return None;
}
Ok(selected) => Some(selected),
Err(error) => {
self.shared.emit(Event::NightlyJobRefused { app: app_id.into(), operation: work.nightly_operation(), error });
@@ -1795,11 +1813,13 @@ fn publish_nightly_result(
shared.latest.lock().unwrap_or_else(PoisonError::into_inner).remove(app.id);
Some(LatestRelease::None)
}
Outcome::Indeterminate(error) | Outcome::VerificationFailed { error, .. } => {
// An install's descriptor verification is not catalog discovery: the recorded result (a
// stale selection, or a time hold the status carries) is published below, and the job
// reports its own error.
Outcome::VerificationFailed { .. } => None,
Outcome::Indeterminate(error) => {
record.complete = false;
record.message = Some(error.why.clone());
// An install's descriptor verification is not catalog discovery: the build's status
// and wait are published below, and the job reports its own error.
verification.is_none().then_some(LatestRelease::Failed(error.why))
}
};
@@ -3495,6 +3515,18 @@ impl Backend for NativeBackend {
Command::Install { app } => {
self.start_job(&app, Work::Install(None));
}
Command::InstallOffer { app, offer } => {
if self.shared.channel == artcraft_launcher_core::nightly::InstallChannel::Nightly {
if let Some(spawn) = self.prepare_job_expecting(&app, Work::Install(None), Some(&offer)) {
spawn();
}
} else {
self.shared.emit(Event::JobFinished {
app,
result: Err("This install request is only for Developer Builds; nothing was changed.".into()),
});
}
}
Command::InstallAll { apps } => self.install_all(&apps),
Command::Replace { app, path } => {
self.start_job(&app, Work::Replace(path));
@@ -6351,6 +6383,10 @@ mod shared_selection_tests;
#[path = "backend_nightly_catalog_demand_tests.rs"]
mod nightly_catalog_demand_tests;
#[cfg(feature = "test-support")]
#[path = "backend_test_support.rs"]
pub mod test_support;
#[cfg(test)]
fn review_after_scheduling_failure() {
REVIEW_AFTER_SCHEDULING_FAILURE.with(|hook| {
@@ -931,8 +931,10 @@ fn review_followup_descriptor_failure_updates_the_build_status_without_a_catalog
let events = backend.poll();
let now = crate::now();
assert!(app_events(&events).any(|event| matches!(event, Event::NightlyJobFinished { operation: NightlyOperation::Install, result: Err(_), .. })));
// The build's own status carries the server's wait (a genuine Retry-After is a time hold, so no
// failure message is recorded against the still-current listing).
assert!(app_events(&events).any(|event| matches!(event,
Event::NightlyStatus { status, .. } if status.message.is_some() && status.verification_retry_at.is_some_and(|until| until > now))));
Event::NightlyStatus { status, .. } if status.verification_retry_at.is_some_and(|until| until > now))));
assert!(
!app_events(&events).any(|event| matches!(event, Event::Latest { latest: LatestRelease::Failed(_), .. })),
"an install's descriptor verification is not a catalog check failure: {events:?}"
@@ -1124,6 +1126,62 @@ fn review_followup_held_catalog_deadline_reaches_check_completion_and_gates_auto
assert_eq!(requests.lock().unwrap().len(), 2);
}
#[test]
fn review_followup_install_offer_must_be_the_build_the_card_showed() {
let (_temp, mut backend, requests) = setup();
let (_, _, shown) = selection(&backend, 20);
// Same tag, one package checksum changed by a later signed publication.
let mut same_tag = shown.clone();
same_tag.assets[0].sha256 = Some("c".repeat(64));
for current in [Some(30), None] {
let (_temp, mut backend, requests) = setup();
selection(&backend, 20);
match current {
Some(run) => {
selection(&backend, run);
}
None => {
let mut listing = backend.shared.nightly_listings.lock().unwrap()[app().id].clone();
listing.release = same_tag.clone();
let generation = backend.shared.nightly_state.lock().unwrap().generation;
finish_nightly_result(
app(),
backend.platform.unwrap(),
generation,
Outcome::Listed(Box::new(listing)),
Origin::ArtCraftApi,
&backend.shared,
&backend.paths,
);
}
}
backend.poll();
backend.http = Some(Http::new().unwrap().with_test_transport(requests.clone(), |url, _| panic!("a refused offer fetched {url}")));
backend.send(Command::InstallOffer { app: app().id.into(), offer: Box::new(shown.clone()) });
let events = backend.poll();
assert!(
events.iter().any(|event| matches!(event,
Event::NightlyJobRefused { app: id, operation: NightlyOperation::Install, error } if id == app().id && error.contains("changed after it was shown"))),
"the shown build must be refused visibly once the offer changed: {events:?}"
);
assert!(!events.iter().any(|event| matches!(event, Event::JobFinished { .. } | Event::NightlyJobFinished { .. } | Event::Progress { .. })));
assert!(!backend.has_active_jobs(), "nothing is reserved");
assert!(requests.lock().unwrap().is_empty(), "no descriptor or package request");
}
// The exact current offer proceeds to its own descriptor, then its package.
let (descriptor_url, body, current) = selection(&backend, 30);
let payload = listed_nightly_asset(app(), &current, backend.platform.unwrap()).unwrap().url.clone();
let expected = descriptor_url.clone();
backend.http = Some(Http::new().unwrap().with_test_transport(requests.clone(), move |url, _| {
assert_eq!(url, expected);
Ok(Some(body.clone()))
}));
backend.send(Command::InstallOffer { app: app().id.into(), offer: Box::new(current) });
assert_eq!(*requests.lock().unwrap(), [descriptor_url, payload]);
// The app-only command keeps its meaning for headless callers.
assert!(backend.shared.events.lock().unwrap().iter().all(|event| !matches!(event, Event::NightlyJobRefused { .. })));
}
#[test]
fn review_followup_server_retry_after_keeps_the_current_offer_and_the_next_click_verifies_again() {
let (_temp, mut backend, requests) = setup();
@@ -1144,7 +1202,7 @@ fn review_followup_server_retry_after_keeps_the_current_offer_and_the_next_click
let deadline = status.verification_retry_at.unwrap();
assert!(deadline > now);
assert!(!backend.start_job(app().id, Work::Install(None)), "admission holds the build until its deadline");
assert_eq!(*requests.lock().unwrap(), [descriptor_url.clone()]);
assert_eq!(requests.lock().unwrap().as_slice(), std::slice::from_ref(&descriptor_url));
// Native's time passes the deadline (the stored deadline is moved into the past).
let mut saved: serde_json::Value = serde_json::from_slice(&std::fs::read(backend.paths.nightly_checks()).unwrap()).unwrap();
let key = nightly_lookup::key(app(), backend.platform.unwrap());
+107
View File
@@ -0,0 +1,107 @@
//! Test-only bridge, compiled only with the `test-support` feature (enabled solely by another
//! crate's non-wasm dev-dependency; never by production, desktop or wasm builds). It builds a real
//! Developer Builds backend whose every HTTP request goes to an in-memory answer, so UI tests are
//! driven by events Native itself produces rather than hand-written ones. Payload downloads are
//! still intercepted and nothing is installed or executed.
use std::sync::{Arc, Mutex, PoisonError};
use artcraft_launcher_core::protocol::{Origin, VersionTrack};
use artcraft_launcher_core::{CraftApp, Platform, Release, version};
use super::{NativeBackend, finish_nightly_result};
use crate::http::{FeedError, Http};
use crate::paths::Paths;
/// What [`developer_builds_backend`] sets up. Times are Unix seconds.
pub struct Scenario {
/// Every request is answered with the server asking to retry after this many seconds.
pub retry_after: i64,
/// When the signed catalog last reconciled the one PhotoCraft offer.
pub reconciled_at: i64,
/// When the catalog check that published that offer started.
pub checked_at: i64,
/// A persisted ArtCraft throttle hold on catalog requests until this time, if any.
pub catalog_held_until: Option<i64>,
}
impl Default for Scenario {
fn default() -> Self {
let now = crate::now();
Self { retry_after: 600, reconciled_at: now, checked_at: now, catalog_held_until: None }
}
}
/// A synthetic PhotoCraft Linux x64 Developer Build release, with its package, detached signature
/// and checksum-bound `NIGHTLY.json` asset. Metadata only: no body of it is ever served.
fn synthetic_release(app: &CraftApp, tag: &str) -> Result<Release, String> {
use sha2::Digest as _;
let version = version::parse(tag).ok_or("The fixture tag is not a version.")?;
let name = format!("photocraft-{version}-linux-x86_64-nightly.tar.gz");
let prefix = format!("https://github.com/{}/releases/download/{tag}/", app.repo);
let descriptor = format!("{{\"schema\":\"craft-nightly/v2\",\"tag\":\"{tag}\"}}");
let item = serde_json::json!({"draft":false,"prerelease":true,"tag_name":tag,"published_at":"2026-11-20T16:00:00Z","assets":[
{"name":name,"browser_download_url":format!("{prefix}{name}"),"size":123,"digest":format!("sha256:{}","a".repeat(64))},
{"name":format!("{name}.asc"),"browser_download_url":format!("{prefix}{name}.asc"),"size":123,"digest":format!("sha256:{}","b".repeat(64))},
{"name":"NIGHTLY.json","browser_download_url":format!("{prefix}NIGHTLY.json"),"size":descriptor.len(),
"digest":format!("sha256:{:x}", sha2::Sha256::digest(descriptor.as_bytes()))}]});
artcraft_launcher_core::release::parse_github_release(&item.to_string(), app.repo)
}
/// A Developer Builds backend under `root` for Linux x64 with consent on and jobs run on the
/// caller's thread. Every request is recorded in `requests` and answered as `scenario` says. One
/// PhotoCraft offer is published the way a completed catalog check publishes it (the sweep's own
/// scheduling steps and result publication); that release is returned.
pub fn developer_builds_backend(
root: &std::path::Path,
requests: Arc<Mutex<Vec<String>>>,
scenario: &Scenario,
) -> Result<(NativeBackend, Release), String> {
let channel = artcraft_launcher_core::nightly::InstallChannel::Nightly;
let paths = Paths::under(root).for_channel(channel);
if let Some(until) = scenario.catalog_held_until {
if let Some(folder) = paths.feed_throttle().parent() {
std::fs::create_dir_all(folder).map_err(|e| e.to_string())?;
}
let saved = serde_json::json!({ "not_before": until, "failures": 1, "throttles": 0 }).to_string();
std::fs::write(paths.feed_throttle(), saved).map_err(|e| e.to_string())?;
}
let mut backend = NativeBackend::with_paths(channel, || {}, paths);
let platform = Platform { os: artcraft_launcher_core::Os::Linux, arch: artcraft_launcher_core::Arch::X64 };
backend.platform = Some(platform);
backend.spawn = Arc::new(|task| task());
let retry_after = scenario.retry_after;
backend.http = Some(Http::new()?.with_test_transport(requests, move |_, _| {
Err(FeedError { why: "The server asked to retry later.".into(), throttled: true, retry_after: Some(retry_after) })
}));
{
// Consent on, already in the shape the Developer Builds context's Configure normalizes to,
// so the UI's first Configure is not a settings change that starts a catalog check.
let mut options = backend.shared.options.lock().unwrap_or_else(PoisonError::into_inner);
options.nightly_enabled = true;
options.prereleases = true;
options.launcher_version = VersionTrack::Nightly;
options.versions = artcraft_launcher_core::hosted_catalog::apps()
.iter()
.filter(|app| app.kind == artcraft_launcher_core::catalog::AppKind::Official)
.map(|app| (app.id.into(), VersionTrack::Nightly))
.collect();
}
let app = CraftApp::by_id("photocraft").ok_or("PhotoCraft is not in the catalog.")?;
let release = synthetic_release(app, "v1.0.0-nightly.20261120.20.1.gabcdefabcdef")?;
let key = crate::nightly_lookup::key(app, platform);
let generation = {
let mut state = backend.shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner);
let keys = std::slice::from_ref(&key);
let none = std::collections::BTreeMap::new();
state.begin_at(keys, &std::collections::BTreeSet::new(), &none, scenario.checked_at, true, true);
state.catalog_started();
state.attempt(&key, scenario.checked_at);
state.generation
};
let listing = crate::nightly_lookup::Listing { release: release.clone(), reconciled_at: scenario.reconciled_at };
let outcome = crate::nightly_lookup::Outcome::Listed(Box::new(listing));
finish_nightly_result(app, platform, generation, outcome, Origin::ArtCraftApi, &backend.shared, &backend.paths);
backend.shared.nightly_state.lock().unwrap_or_else(PoisonError::into_inner).finish();
Ok((backend, release))
}
+8 -8
View File
@@ -45,15 +45,15 @@ pub struct Http {
direct_download: ureq::Agent,
token: Option<String>,
nightly_mirror: Option<NightlyMirror>,
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
test_transport: Option<TestTransport>,
/// Shared by every clone, so every GitHub API request counts against the one budget.
budget: std::sync::Arc<crate::github_budget::GitHubBudget>,
}
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
type TestGet = dyn Fn(&str, usize) -> Result<Option<Vec<u8>>, FeedError> + Send + Sync;
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
#[derive(Clone)]
struct TestTransport {
get: std::sync::Arc<TestGet>,
@@ -227,7 +227,7 @@ impl Http {
direct_download,
token,
nightly_mirror: None,
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
test_transport: None,
budget,
})
@@ -250,7 +250,7 @@ impl Http {
Ok(self)
}
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn with_test_transport(
mut self,
requests: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
@@ -266,7 +266,7 @@ impl Http {
}
fn request<'a>(&'a self, logical: &'a str, default: &'a ureq::Agent) -> Result<(std::borrow::Cow<'a, str>, &'a ureq::Agent), String> {
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
if let Some(transport) = &self.test_transport {
transport.requests.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(logical.into());
return Err("Test transport intercepted the payload; no synthetic program is installed or executed.".into());
@@ -418,7 +418,7 @@ impl Http {
timeout: Duration,
receipt_now: impl Fn() -> i64,
) -> Result<Option<Vec<u8>>, NightlyHttpError> {
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
if let Some(transport) = &self.test_transport {
transport.requests.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(url.into());
return (transport.get)(url, max).map_err(|error| NightlyHttpError {
@@ -505,7 +505,7 @@ impl Http {
}
pub(crate) fn get_catalog_feed_bytes(&self, url: &str, max: usize) -> Result<Option<Vec<u8>>, FeedError> {
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
if let Some(transport) = &self.test_transport {
transport.requests.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(url.into());
return (transport.get)(url, max);
+18 -5
View File
@@ -349,12 +349,13 @@ impl Record {
/// `expires` is the last second the signed source behind this record is current (its
/// status's `valid_until`). An offer or omission that expired after the last attempt is
/// revalidated at once rather than after the cadence; one attempt after expiry ends that.
/// revalidated rather than waiting out the cadence; one attempt after expiry ends that. It
/// never shortens the manual coalescing window, so two sweeps are never a minute apart.
fn due(&self, now: i64, manual: bool, installed: bool, expires: Option<i64>) -> bool {
if self.retry_at.is_some_and(|at| now < at) {
return false;
}
if expires.is_some_and(|until| now > until && self.attempted_at.is_none_or(|at| at <= until)) {
if expires.is_some_and(|until| now > until && self.attempted_at.is_none_or(|at| at <= until && now.saturating_sub(at) >= MANUAL_COALESCE)) {
return true;
}
let wait = if manual {
@@ -576,6 +577,11 @@ impl State {
self.held_until = Some(until);
}
/// The ArtCraft throttle's hold on catalog requests, while it lasts.
pub(crate) fn catalog_hold(&self, now: i64) -> Option<i64> {
self.held_until.filter(|until| *until > now)
}
pub(crate) fn catalog_started(&mut self) {
if self.in_flight {
self.startup = false;
@@ -684,12 +690,19 @@ impl State {
record.complete = (0..2 * 60 * 60).contains(&now.saturating_sub(*published_at));
}
Outcome::VerificationFailed { tag, error } => {
let until = record.verification_retry(tag, now).into_iter().chain(error.retry_at).filter(|at| *at > now).max();
let server_wait = error.retry_at.filter(|at| *at > now);
let until = record.verification_retry(tag, now).into_iter().chain(server_wait).max();
if let Some(until) = until {
record.verification = Some(VerificationRetry { tag: tag.clone(), until });
}
record.message = Some(error.why.chars().take(120).collect());
record.complete = false;
// A server's Retry-After on this exact recorded build is a time hold, not evidence
// against its signed listing: the listing stays current and the hold is published
// by its deadline; the next admitted click verifies the descriptor again. Any other
// verification failure leaves the selection stale until a catalog check.
if server_wait.is_none() || record.tag.as_deref() != Some(tag.as_str()) {
record.message = Some(error.why.chars().take(120).collect());
record.complete = false;
}
}
#[cfg(test)]
Outcome::NoCompatibleBuild => {
+5
View File
@@ -51,3 +51,8 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# Real fonts for the Fonts page's fake font store: egui's Ubuntu Light.
epaint_default_fonts = "0.37"
# Test infrastructure only (never a normal or wasm dependency): Developer Builds UI tests driven by
# a real Native backend's events through its `test-support` bridge.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
artcraft-launcher-native = { workspace = true, features = ["test-support"] }
+191 -25
View File
@@ -71,14 +71,14 @@ fn nightly_job_progress(phase: JobPhase) -> (Option<f32>, String) {
}
}
/// The line the Developer Builds page shows while the launcher's own GitHub budget is holding the
/// next check back: the same "next check" wording the stable page uses for the same kind of hold.
/// `None` when there is no hold in the future, so the page says what it knows.
/// The line the Developer Builds page shows while a catalog hold (a server backoff or the ArtCraft
/// throttle) is holding the next check back. Developer Builds discovery never asks GitHub, so it
/// uses the stable page's neutral short wording. `None` when there is no hold in the future.
fn held_back_line(until: Option<i64>, now: i64) -> Option<String> {
use crate::i18n::fmt;
let until = until.filter(|until| *until > now)?;
let (hour, minute) = crate::local_time::clock(until);
Some(fmt(tl!("Next GitHub check at {time}"), &[("time", &format!("{hour:02}:{minute:02}"))]))
Some(fmt(tl!("Next check at {time}"), &[("time", &format!("{hour:02}:{minute:02}"))]))
}
fn nightly_ago(at: i64, now: i64) -> String {
@@ -239,9 +239,6 @@ pub(crate) struct NightlyState {
attempted_at: Option<i64>,
// Request throttling is not evidence that Native actually attempted a lookup.
requested_at: Option<i64>,
/// The latest signed-source expiry already answered with a revalidation request, so one that
/// Native could not act on is not asked about again before the hourly gate.
revalidated_for: Option<i64>,
statuses: BTreeMap<String, NightlyStatus>,
checking: bool,
// Only live check failures, never replayed statuses, should raise a toast.
@@ -275,7 +272,6 @@ impl NightlyState {
held_back_until: None,
attempted_at: None,
requested_at: None,
revalidated_for: None,
statuses: BTreeMap::new(),
checking: false,
check_failure: None,
@@ -327,6 +323,7 @@ impl NightlyState {
&& matches!(
&command,
Command::Install { .. }
| Command::InstallOffer { .. }
| Command::InstallChosen { .. }
| Command::InstallAll { .. }
| Command::Replace { .. }
@@ -454,14 +451,12 @@ impl NightlyState {
// nothing is asked even if the hourly gate would say yes; once it passes, ask at once rather
// than wait out the hour of a sweep that never ran. Consent, coalescing and server backoff
// still guard the request. A sweep that completed without a hold keeps the hourly gate.
// A signed offer or omission that expired after its last check is revalidated at once, as
// Native schedules it, rather than waiting out the hour; each expiry is asked about once.
let expired = self
.statuses
.values()
.filter_map(|status| status.valid_until.filter(|&until| now > until && status.attempted_at.is_none_or(|at| at <= until)))
.max();
let expiry_due = expired.is_some_and(|until| self.revalidated_for.is_none_or(|asked| asked < until));
// A signed offer or omission that expired after its last check is revalidated without
// waiting out the hour, by Native's own rule: only once its last attempt is a minute old,
// and only until an attempt lands after the expiry. A catalog hold still decides first.
let expiry_due = self.statuses.values().any(|status| {
status.valid_until.is_some_and(|until| now > until && status.attempted_at.is_none_or(|at| at <= until && now.saturating_sub(at) >= 60))
});
let due = match self.held_back_until {
Some(until) => now >= until,
None => hourly_due || expiry_due,
@@ -473,7 +468,6 @@ impl NightlyState {
if self.available && settings.nightly_enabled && !self.checking && due && request_allowed && retry_allowed {
// A request is not a successful verification, including when Native coalesces it.
self.requested_at = Some(now);
self.revalidated_for = self.revalidated_for.max(expired);
// The hold has been answered: a fresh hold, if any, arrives with the next CheckFinished.
self.held_back_until = None;
backend.send(Command::CheckForUpdates { force: false });
@@ -913,8 +907,12 @@ impl LauncherUi {
} else {
egui::Button::new(RichText::new(label).color(tokens.invert_fg)).fill(tokens.invert_bg)
};
if ui.add(button).clicked() {
self.act(UiAction::NightlyCommand(Command::Install { app: entry.app.id.into() }));
if ui.add(button).clicked()
&& let Some(LatestRelease::Found(offer)) = &entry.latest
{
// Bound to the build this card shows: Native refuses if its offer changed since.
let offer = Box::new(offer.clone());
self.act(UiAction::NightlyCommand(Command::InstallOffer { app: entry.app.id.into(), offer }));
}
}
if installed {
@@ -1566,7 +1564,7 @@ mod status_tests {
harness.get_by_label("Install").focus();
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
let installs = || fake.sent.borrow().iter().filter(|command| matches!(command, Command::Install { .. })).count();
let installs = || fake.sent.borrow().iter().filter(|command| matches!(command, Command::InstallOffer { .. })).count();
assert!(installs() > 0, "the last accepted second still offers the exact-build install command");
let before = installs();
fake.now.set(until + 1);
@@ -1645,7 +1643,7 @@ mod status_tests {
install.expect("the wait ending restores Install without another backend event").focus();
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert!(fake.sent.borrow().iter().any(|command| matches!(command, Command::Install { .. })));
assert!(fake.sent.borrow().iter().any(|command| matches!(command, Command::InstallOffer { .. })));
}
}
}
@@ -1847,9 +1845,9 @@ mod status_tests {
fake.events.borrow_mut().extend([Event::CheckStarted, hold]);
let mut state = NightlyState::new(Some(Box::new(fake.clone())), None);
state.logic(&Settings::default());
assert_eq!(state.held_back_until, Some(1000 + 60 * 60), "a held-back sweep says when GitHub is asked again");
assert_eq!(state.held_back_until, Some(1000 + 60 * 60), "a held-back sweep says when the catalog is asked again");
let (hour, minute) = crate::local_time::clock(1000 + 60 * 60);
assert_eq!(held_back_line(state.held_back_until, 1000).as_deref(), Some(format!("Next GitHub check at {hour:02}:{minute:02}").as_str()));
assert_eq!(held_back_line(state.held_back_until, 1000).as_deref(), Some(format!("Next check at {hour:02}:{minute:02}").as_str()));
assert_eq!(held_back_line(state.held_back_until, 1000 + 60 * 60), None, "a hold that has passed says nothing");
fake.events.borrow_mut().push(Event::CheckStarted);
state.logic(&Settings::default());
@@ -2435,7 +2433,7 @@ mod polish_tests {
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert!(sent.borrow().iter().any(|command| matches!(command, Command::CheckForUpdates { force: true })));
assert!(!sent.borrow().iter().any(|command| matches!(command, Command::Install { .. })));
assert!(!sent.borrow().iter().any(|command| matches!(command, Command::Install { .. } | Command::InstallOffer { .. })));
}
#[test]
@@ -2484,7 +2482,7 @@ mod polish_tests {
button.focus();
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert!(sent.borrow().iter().any(|cmd| matches!(cmd, Command::Install { app } if app == "photocraft")), "{name}");
assert!(sent.borrow().iter().any(|cmd| matches!(cmd, Command::InstallOffer { app, .. } if app == "photocraft")), "{name}");
} else {
assert!(button.is_none(), "unavailable or redundant install action: {name}");
}
@@ -3092,3 +3090,171 @@ mod trust_gate_tests {
assert!(!harness.state().as_ref().unwrap().settings.nightly_enabled);
}
}
/// Developer Builds UI driven by a real Native backend's own events (Native's `test-support`
/// bridge; Linux, where its fixture's signing trust is configured). Only the UI's clock is injected.
#[cfg(test)]
#[cfg(target_os = "linux")]
mod native_bridge_tests {
use super::*;
use artcraft_launcher_core::protocol::Capabilities;
use artcraft_launcher_native::backend::test_support::{Scenario, developer_builds_backend};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
struct Host;
impl crate::Host for Host {}
struct Stable;
impl Backend for Stable {
fn send(&mut self, _: Command) {}
fn poll(&mut self) -> Vec<Event> {
Vec::new()
}
fn capabilities(&self) -> Capabilities {
Capabilities { manage_apps: true, reveal_label: "Show", self_update: false, desktop_shortcuts: false }
}
fn platform(&self) -> Option<Platform> {
None
}
fn now(&self) -> i64 {
0
}
}
/// The real Native backend, with every command it is sent recorded and the UI's clock injected.
struct Clocked {
native: artcraft_launcher_native::NativeBackend,
now: Rc<Cell<i64>>,
sent: Rc<RefCell<Vec<Command>>>,
}
impl Backend for Clocked {
fn has_active_jobs(&self) -> bool {
self.native.has_active_jobs()
}
fn nightly_available(&self) -> bool {
self.native.nightly_available()
}
fn send(&mut self, command: Command) {
self.sent.borrow_mut().push(command.clone());
self.native.send(command);
}
fn poll(&mut self) -> Vec<Event> {
self.native.poll()
}
fn capabilities(&self) -> Capabilities {
self.native.capabilities()
}
fn platform(&self) -> Option<Platform> {
self.native.platform()
}
fn now(&self) -> i64 {
self.now.get()
}
}
struct Bridge {
harness: Harness<'static, Option<LauncherUi>>,
clock: Rc<Cell<i64>>,
sent: Rc<RefCell<Vec<Command>>>,
requests: Arc<Mutex<Vec<String>>>,
offer: artcraft_launcher_core::Release,
root: std::path::PathBuf,
}
impl Drop for Bridge {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
fn bridge(name: &str, scenario: &Scenario) -> Bridge {
let root = std::env::temp_dir().join(format!("artcraft-ui-native-bridge-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let root = root.canonicalize().unwrap();
let requests = Arc::new(Mutex::new(Vec::new()));
let (native, offer) = developer_builds_backend(&root, requests.clone(), scenario).unwrap();
let clock = Rc::new(Cell::new(artcraft_launcher_native::now()));
let sent: Rc<RefCell<Vec<Command>>> = Rc::default();
let mut backend = Some(Clocked { native, now: clock.clone(), sent: sent.clone() });
let mut harness =
Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1180.0, 900.0)).build_ui_state(
move |ui, state: &mut Option<LauncherUi>| {
let launcher = state.get_or_insert_with(|| {
let mut launcher = LauncherUi::new(
ui.ctx(),
Box::new(Stable),
Settings { language: "en".into(), nightly_enabled: true, notify: false, ..Default::default() },
);
let native = backend.take().map(|backend| Box::new(backend) as Box<dyn Backend>);
launcher.nightly = NightlyState::new(native, None);
launcher.nightly.active = true;
launcher
});
launcher.logic(&ui.ctx().clone(), &mut Host);
launcher.ui(ui, &mut Host);
},
None,
);
harness.run_steps(5);
Bridge { harness, clock, sent, requests, offer, root }
}
fn checks(sent: &RefCell<Vec<Command>>) -> usize {
sent.borrow().iter().filter(|command| matches!(command, Command::CheckForUpdates { .. })).count()
}
#[test]
fn review_followup_real_native_retry_after_holds_install_until_its_deadline_without_a_refresh() {
let mut b = bridge("retry-after", &Scenario { retry_after: 600, ..Default::default() });
b.harness.get_by_label("Install").focus();
b.harness.key_press(egui::Key::Enter);
b.harness.run_steps(5);
assert_eq!(b.requests.lock().unwrap().len(), 1, "the click asked only for the selected build's descriptor: {:?} {:?}", b.requests, b.sent);
assert!(b.harness.query_by_label("Install").is_none(), "Native's real Retry-After holds Install");
let deadline = b.harness.state().as_ref().unwrap().nightly.statuses["photocraft"].verification_retry_at.unwrap();
b.clock.set(deadline - 1);
b.harness.run_steps(3);
assert!(b.harness.query_by_label("Install").is_none());
b.clock.set(deadline);
b.harness.run_steps(3);
b.harness.get_by_label("Install").focus();
b.harness.key_press(egui::Key::Enter);
b.harness.run_steps(3);
let offers: Vec<_> = b
.sent
.borrow()
.iter()
.filter_map(|command| match command {
Command::InstallOffer { offer, .. } => Some((**offer).clone()),
_ => None,
})
.collect();
assert_eq!(offers, [b.offer.clone(), b.offer.clone()], "the same current offer returns at the deadline");
assert_eq!(checks(&b.sent), 0, "no catalog refresh restored it");
}
#[test]
fn review_followup_real_native_catalog_hold_retries_an_expired_offer_exactly_at_its_deadline() {
let now = artcraft_launcher_native::now();
let held = now + 900;
let scenario =
Scenario { reconciled_at: now - 2 * 60 * 60 - 10, checked_at: now - 120, catalog_held_until: Some(held), ..Default::default() };
let mut b = bridge("catalog-hold", &scenario);
assert_eq!(checks(&b.sent), 1, "the expired offer was revalidated before the hourly gate: {:?}", b.sent);
assert!(b.requests.lock().unwrap().is_empty(), "the ArtCraft throttle held that request");
assert_eq!(b.harness.state().as_ref().unwrap().nightly.held_back_until, Some(held), "Native reported the hold's deadline");
for at in [now + 60, now + 300, held - 1] {
b.clock.set(at);
b.harness.run_steps(2);
assert_eq!(checks(&b.sent), 1, "no request before the hold ends ({at})");
}
b.clock.set(held);
b.harness.run_steps(3);
assert_eq!(checks(&b.sent), 2, "exactly one automatic retry at the deadline");
assert!(!b.sent.borrow().iter().any(|command| matches!(command, Command::CheckForUpdates { force: true })), "no manual action");
}
}
+1
View File
@@ -29,6 +29,7 @@ The product name in user-facing text is ArtCraft Launcher, and the suite is the
- Errors use each crate's error type and `?`. Production crate roots (`lib.rs`, each binary's `main.rs`, `xtask`) carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
- Release parsing and asset picking in `core` are tested with real GitHub release JSON fixtures, small and committed under `crates/core/tests/fixtures/`.
- `artcraft-launcher-native`'s `test-support` feature (off by default) exposes `backend::test_support`, a real Developer Builds backend with an in-memory transport, so `ui-egui` tests (its only user, a non-wasm dev-dependency) are driven by events Native produces. Production, desktop and wasm builds never enable it.
## Look and feel
+9 -5
View File
@@ -86,15 +86,19 @@ network refresh. Opening the page, scheduled checks and Refresh never ask GitHub
release pages or isolation descriptors. Missing, stale, invalid or offline catalog answers do not
fall back to GitHub. Stale cached listings remain visible but cannot start an install. When a
listing's signed freshness ends, the next scheduled check revalidates it rather than waiting for
the app's usual cadence; a catalog request the ArtCraft throttle holds back costs no app its turn.
the app's usual cadence (never sooner than a minute after the last check); a catalog request the
ArtCraft throttle holds back costs no app its turn, and the page asks again when the hold ends.
A listing is not an installation token. Install and Update capture the selected exact catalog
release and consent generation before reserving their job. Only that release's `NIGHTLY.json`
A listing is not an installation token. A card's Install and Update name the exact release it
shows (`Command::InstallOffer`); if the current offer differs in any way, the click is refused
visibly before anything is reserved or fetched. Install and Update capture the selected exact
catalog release and consent generation before reserving their job. Only that release's `NIGHTLY.json`
is fetched on demand and verified against the signed catalog hash, the descriptor's exact
release identity and the source-owned platform/profile/package row. No other apps or releases
are enumerated. Missing or changed evidence fails without requesting a payload, and a job that
waited for its download turn compares the selected build and package again first. A server wait on
the descriptor holds only that build's Install, by its deadline. The existing
waited for its download turn compares the selected build and package again first. A server's
Retry-After on the descriptor holds only that build's Install, by its deadline: the listing stays
current, and the next click after the deadline verifies the descriptor again. The existing
payload checksum, platform signature, private destination and transaction checks still run before
installation; opting out continues to leave owned copies and their data available.