Skip to content

Commit 4cd2b85

Browse files
authored
feat: automatic update check via npm registry and gitHub releases (#63)
1 parent e3fe862 commit 4cd2b85

21 files changed

Lines changed: 1606 additions & 31 deletions

‎apps/desktop/src/bridge.rs‎

Lines changed: 233 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1680,10 +1680,23 @@ pub async fn list_workspaces() -> Result<Vec<Value>, String> {
16801680
Ok(s) => s,
16811681
Err(_) => continue,
16821682
};
1683-
let meta: Value = match serde_json::from_str(&raw) {
1683+
let mut meta: Value = match serde_json::from_str(&raw) {
16841684
Ok(v) => v,
16851685
Err(_) => continue,
16861686
};
1687+
// Annotate whether the project directory still exists. Entries whose
1688+
// directory was removed externally (deleted repo, cleaned /tmp, …)
1689+
// must not be switchable — the UI offers "remove stale entry"
1690+
// instead, so clicking the row never reaches init_sidecar's
1691+
// "Directory does not exist" error.
1692+
let dir_exists = meta
1693+
.get("cwd")
1694+
.and_then(|v| v.as_str())
1695+
.map(|cwd| std::path::Path::new(cwd).is_dir())
1696+
.unwrap_or(false);
1697+
if let Some(obj) = meta.as_object_mut() {
1698+
obj.insert("dir_exists".to_string(), Value::Bool(dir_exists));
1699+
}
16871700
workspaces.push(meta);
16881701
}
16891702

@@ -3787,3 +3800,222 @@ pub async fn list_auth_options(app: AppHandle) -> Result<Vec<AuthLoginOption>, S
37873800
}
37883801
Ok(options)
37893802
}
3803+
3804+
// ─── App update check ───────────────────────────────────────────────────────
3805+
//
3806+
// The desktop app is distributed via GitHub release installers
3807+
// (Pizza_<version>_<platform>_<arch>.<ext>). There is no in-app self-update
3808+
// (the installers are not updater-signed), so "update" means: detect a newer
3809+
// release and point the user at the download page / platform asset.
3810+
3811+
/// Result of a desktop update check. Always succeeds — a failed network probe
3812+
/// is reported through `error` so the UI can show a friendly message instead
3813+
/// of an error dialog.
3814+
#[derive(serde::Serialize)]
3815+
#[serde(rename_all = "camelCase")]
3816+
pub struct AppUpdateInfo {
3817+
/// Version of the running app (from tauri.conf.json).
3818+
pub current_version: String,
3819+
/// Latest published release version, when the registry was reachable.
3820+
pub latest_version: Option<String>,
3821+
pub update_available: bool,
3822+
/// Browser URL of the latest release page.
3823+
pub release_url: String,
3824+
/// Direct download URL for the platform installer, when one exists.
3825+
pub download_url: Option<String>,
3826+
/// When the latest release was published (ISO 8601).
3827+
pub published_at: Option<String>,
3828+
/// Network/parse error, if any.
3829+
pub error: Option<String>,
3830+
}
3831+
3832+
/// Parse a `x.y.z` version tag (with optional leading `v`) into numbers.
3833+
/// Returns None when the tag isn't a plain semver triple.
3834+
fn parse_version_tag(tag: &str) -> Option<(u64, u64, u64)> {
3835+
let cleaned = tag.trim().trim_start_matches('v');
3836+
let mut parts = cleaned.split('.');
3837+
let major = parts.next()?.parse().ok()?;
3838+
let minor = parts.next()?.parse().ok()?;
3839+
let patch = parts.next()?.parse().ok()?;
3840+
if parts.next().is_some() {
3841+
return None;
3842+
}
3843+
Some((major, minor, patch))
3844+
}
3845+
3846+
/// Compare two semver triples: -1 / 0 / 1.
3847+
fn compare_versions(a: (u64, u64, u64), b: (u64, u64, u64)) -> i32 {
3848+
if a.0 != b.0 {
3849+
return if a.0 > b.0 { 1 } else { -1 };
3850+
}
3851+
if a.1 != b.1 {
3852+
return if a.1 > b.1 { 1 } else { -1 };
3853+
}
3854+
if a.2 != b.2 {
3855+
return if a.2 > b.2 { 1 } else { -1 };
3856+
}
3857+
0
3858+
}
3859+
3860+
/// Pick the installer asset for the current platform from the release's asset
3861+
/// list, following the `Pizza_<version>_<platform>_<arch>.<ext>` naming scheme
3862+
/// produced by the desktop release workflow.
3863+
fn pick_platform_asset(asset_urls: &[String]) -> Option<String> {
3864+
let (os, arch): (&str, &str) = if cfg!(target_os = "macos") {
3865+
(
3866+
"macos",
3867+
if cfg!(target_arch = "aarch64") {
3868+
"arm64"
3869+
} else {
3870+
"x64"
3871+
},
3872+
)
3873+
} else if cfg!(target_os = "windows") {
3874+
("windows", "x64")
3875+
} else {
3876+
("linux", "x64")
3877+
};
3878+
let platform = format!("_{os}_{arch}");
3879+
// Preference order per platform: dmg / nsis setup / deb. msi and rpm are
3880+
// kept as fallbacks for users on those ecosystems.
3881+
let suffixes: &[&str] = if cfg!(target_os = "macos") {
3882+
&[".dmg"]
3883+
} else if cfg!(target_os = "windows") {
3884+
&["-setup.exe", ".exe", ".msi"]
3885+
} else {
3886+
&[".deb", ".rpm", ".AppImage"]
3887+
};
3888+
for suffix in suffixes {
3889+
if let Some(url) = asset_urls
3890+
.iter()
3891+
.find(|u| u.contains(&platform) && u.ends_with(suffix))
3892+
{
3893+
return Some(url.clone());
3894+
}
3895+
}
3896+
None
3897+
}
3898+
3899+
const GITHUB_LATEST_RELEASE_API: &str =
3900+
"https://api.github.com/repos/tomsun28/pizza/releases/latest";
3901+
const GITHUB_RELEASES_PAGE: &str = "https://github.com/tomsun28/pizza/releases/latest";
3902+
3903+
/// Check GitHub releases for a newer desktop app version. Never fails hard —
3904+
/// network problems come back as `AppUpdateInfo.error` so the caller can
3905+
/// render them inline.
3906+
#[tauri::command]
3907+
pub async fn check_app_update(app: AppHandle) -> Result<AppUpdateInfo, String> {
3908+
let current_version = app.package_info().version.to_string();
3909+
3910+
let client = reqwest::Client::builder()
3911+
.user_agent(format!("pizza-desktop/{current_version}"))
3912+
.timeout(Duration::from_secs(8))
3913+
.build()
3914+
.map_err(|e| format!("HTTP client error: {e}"))?;
3915+
3916+
let res = match client
3917+
.get(GITHUB_LATEST_RELEASE_API)
3918+
.header("Accept", "application/json")
3919+
.send()
3920+
.await
3921+
{
3922+
Ok(res) => res,
3923+
Err(e) => {
3924+
return Ok(AppUpdateInfo {
3925+
current_version,
3926+
latest_version: None,
3927+
update_available: false,
3928+
release_url: GITHUB_RELEASES_PAGE.to_string(),
3929+
download_url: None,
3930+
published_at: None,
3931+
error: Some(format!("network error: {e}")),
3932+
});
3933+
}
3934+
};
3935+
3936+
if !res.status().is_success() {
3937+
return Ok(AppUpdateInfo {
3938+
current_version,
3939+
latest_version: None,
3940+
update_available: false,
3941+
release_url: GITHUB_RELEASES_PAGE.to_string(),
3942+
download_url: None,
3943+
published_at: None,
3944+
error: Some(format!("GitHub returned status {}", res.status())),
3945+
});
3946+
}
3947+
3948+
let body: serde_json::Value = match res.json().await {
3949+
Ok(v) => v,
3950+
Err(e) => {
3951+
return Ok(AppUpdateInfo {
3952+
current_version,
3953+
latest_version: None,
3954+
update_available: false,
3955+
release_url: GITHUB_RELEASES_PAGE.to_string(),
3956+
download_url: None,
3957+
published_at: None,
3958+
error: Some(format!("bad JSON: {e}")),
3959+
});
3960+
}
3961+
};
3962+
3963+
let tag = body
3964+
.get("tag_name")
3965+
.and_then(|v| v.as_str())
3966+
.unwrap_or_default()
3967+
.to_string();
3968+
if tag.is_empty() {
3969+
return Ok(AppUpdateInfo {
3970+
current_version,
3971+
latest_version: None,
3972+
update_available: false,
3973+
release_url: GITHUB_RELEASES_PAGE.to_string(),
3974+
download_url: None,
3975+
published_at: None,
3976+
error: Some("release has no tag_name".to_string()),
3977+
});
3978+
}
3979+
3980+
let release_url = body
3981+
.get("html_url")
3982+
.and_then(|v| v.as_str())
3983+
.unwrap_or(GITHUB_RELEASES_PAGE)
3984+
.to_string();
3985+
let published_at = body
3986+
.get("published_at")
3987+
.and_then(|v| v.as_str())
3988+
.map(|s| s.to_string());
3989+
let asset_urls: Vec<String> = body
3990+
.get("assets")
3991+
.and_then(|v| v.as_array())
3992+
.map(|assets| {
3993+
assets
3994+
.iter()
3995+
.filter_map(|a| {
3996+
a.get("browser_download_url")
3997+
.and_then(|v| v.as_str())
3998+
.map(|s| s.to_string())
3999+
})
4000+
.collect()
4001+
})
4002+
.unwrap_or_default();
4003+
4004+
let latest_version = tag.trim_start_matches('v').to_string();
4005+
let update_available = match (parse_version_tag(&tag), parse_version_tag(&current_version)) {
4006+
(Some(latest), Some(current)) => compare_versions(latest, current) > 0,
4007+
// Unparseable versions: fall back to a plain inequality so a surprise
4008+
// tag format still surfaces an update.
4009+
_ => latest_version != current_version,
4010+
};
4011+
4012+
Ok(AppUpdateInfo {
4013+
current_version,
4014+
latest_version: Some(latest_version),
4015+
update_available,
4016+
release_url,
4017+
download_url: pick_platform_asset(&asset_urls),
4018+
published_at,
4019+
error: None,
4020+
})
4021+
}

‎apps/desktop/src/gateway_channel.rs‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -391,28 +391,56 @@ pub fn ensure_gateway(
391391
{
392392
std::thread::sleep(std::time::Duration::from_secs(1));
393393
}
394-
// Graceful shutdown, then clean any residual socket file.
394+
if status_has_busy_agents(&status) {
395+
// Agents are STILL busy after the drain window.
396+
// Replacing the gateway now would kill mid-turn tasks;
397+
// keep the older daemon instead. Version skew is
398+
// harmless — the channel protocol is version-tolerant
399+
// and the next idle start will upgrade it.
400+
return Ok(());
401+
}
402+
// Graceful shutdown. If the gateway refuses to die, REUSE
403+
// it — force-unlinking a live gateway's socket orphans the
404+
// daemon (and its pooled agents) while a fresh gateway
405+
// spawns besides it; duplicate gateways then fight over
406+
// workspaces (observed: reconnect storms in the desktop).
395407
let stopped = shutdown_gateway(socket_path);
396408
if !stopped {
397-
clean_stale_socket(socket_path);
409+
return Ok(());
398410
}
411+
clean_stale_socket(socket_path);
399412
// Fall through to spawn a fresh gateway.
400413
} else {
401414
return Ok(());
402415
}
403416
} else {
404417
// Status query failed but ping succeeded — the gateway is
405418
// likely an old version that doesn't report `version` in
406-
// status. Treat it as outdated and replace it.
419+
// status. Try to replace it, but never force-unlink a live
420+
// socket (see the version-mismatch branch above).
407421
let stopped = shutdown_gateway(socket_path);
408422
if !stopped {
409-
clean_stale_socket(socket_path);
423+
return Ok(());
410424
}
425+
clean_stale_socket(socket_path);
411426
}
412427
} else {
413428
return Ok(());
414429
}
415430
}
431+
// Not ready — but "no answer" may be a transient miss (a busy gateway
432+
// fanning out agent events can miss a 2s ping). Re-probe briefly before
433+
// deciding the daemon is gone: spawning beside a live gateway is how
434+
// duplicate daemons (and duplicate agents) accumulate.
435+
{
436+
let probe_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
437+
while std::time::Instant::now() < probe_deadline {
438+
std::thread::sleep(std::time::Duration::from_millis(300));
439+
if gateway_ready(socket_path) {
440+
return Ok(());
441+
}
442+
}
443+
}
416444
let env_pizza = std::env::var("PIZZA_BIN").ok();
417445
// Resolve the main agent directory so the gateway can pass --main to
418446
// sub-agents spawned for that cwd. The gateway itself does NOT run as

‎apps/desktop/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ fn main() {
4949
bridge::oauth_login_answer,
5050
bridge::oauth_login_cancel,
5151
bridge::list_auth_options,
52+
bridge::check_app_update,
5253
])
5354
.setup(|app| {
5455
bridge::start_scheduler_sidecar_guard(app.handle().clone());

0 commit comments

Comments
 (0)