Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions desktop/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,11 +291,11 @@ async fn update_check(
async fn update_install(
window: tauri::WebviewWindow,
app: tauri::AppHandle,
) -> Result<updater::PageUpdateStatus, String> {
) -> Result<updater::PageUpdateStatus, tauri::ipc::InvokeError> {
window::require_update_page(&window)?;
updater::install_pending(&app).await.map_err(|error| {
logging::log_once("updater install failed", &error);
"the update could not be installed; try again".to_owned()
error.log();
error.into()
})
}

Expand Down
2 changes: 1 addition & 1 deletion desktop/src-tauri/src/tray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> {
let app = app.clone();
tauri::async_runtime::spawn(async move {
if let Err(error) = updater::install_pending(&app).await {
crate::logging::log_once("updater install failed", &error);
error.log();
}
});
}
Expand Down
124 changes: 114 additions & 10 deletions desktop/src-tauri/src/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,70 @@ pub fn page_status(app: &AppHandle) -> PageUpdateStatus {
})
}

pub async fn install_pending(app: &AppHandle) -> Result<PageUpdateStatus, String> {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstallFailure {
message: String,
manual_download: bool,
#[serde(skip)]
diagnostic: Option<String>,
}

enum PackageStep {
Download,
Install,
}

impl InstallFailure {
fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
manual_download: false,
diagnostic: None,
}
}

fn package(step: PackageStep, error: tauri_plugin_updater::Error) -> Self {
use tauri_plugin_updater::Error;
let (message, manual_download) = match (step, &error) {
(
_,
Error::Minisign(_)
| Error::Base64(_)
| Error::SignatureUtf8(_)
| Error::SignedVersionMismatch { .. }
| Error::MissingSignedVersion,
) => (
"The update package failed signature verification. Installation was blocked.",
false,
),
(PackageStep::Download, Error::Network(_) | Error::Reqwest(_)) => {
("The update package could not be downloaded.", true)
}
(PackageStep::Download, _) => {
("The updater could not acquire the update package.", false)
}
(PackageStep::Install, _) => (
"The platform installer could not install the verified update package.",
false,
),
};
Self {
message: message.into(),
manual_download,
diagnostic: Some(error.to_string()),
}
}

pub fn log(&self) {
logging::log_once(
"updater install failed",
self.diagnostic.as_deref().unwrap_or(&self.message),
);
}
}

pub async fn install_pending(app: &AppHandle) -> Result<PageUpdateStatus, InstallFailure> {
let state = app.state::<tray::TrayState>();
let gate = app.state::<CheckGeneration>();
match gate.claim_install(
Expand All @@ -304,8 +367,10 @@ pub async fn install_pending(app: &AppHandle) -> Result<PageUpdateStatus, String
|| app.state::<DesktopUpdateState>().retain_phase("installing"),
) {
InstallClaim::Claimed => {}
InstallClaim::Busy => return Err("an update is already installing".into()),
InstallClaim::NoPending => return Err("no update is ready to install".into()),
InstallClaim::Busy => return Err(InstallFailure::new("An update is already installing.")),
InstallClaim::NoPending => {
return Err(InstallFailure::new("No update is ready to install."))
}
}
let pending = app.state::<PendingUpdate>();
let update = pending
Expand All @@ -319,7 +384,7 @@ pub async fn install_pending(app: &AppHandle) -> Result<PageUpdateStatus, String
app.state::<DesktopUpdateState>().retain_phase("current");
gate.queue_ui(UiProjection::Current);
});
return Err("no update is ready to install".into());
return Err(InstallFailure::new("No update is ready to install."));
};
let version = update.version.clone();
let retry_update = update.clone();
Expand Down Expand Up @@ -385,14 +450,14 @@ pub async fn check(app: &AppHandle) -> Result<Option<Update>, String> {
.map_err(|error| error.to_string())
}

pub async fn install(app: &AppHandle, update: Update) -> Result<(), String> {
pub async fn install(app: &AppHandle, update: Update) -> Result<(), InstallFailure> {
// Download and verify first, and separately from installing. The pinned updater checks the
// release signature inside `download`, so these bytes are the ones the key signed; nothing has
// been replaced yet, and a failure here costs only the download.
let package = update
.download(|_, _| {}, || {})
.await
.map_err(|error| error.to_string())?;
.map_err(|error| InstallFailure::package(PackageStep::Download, error))?;

// Then stop the runtime, and confirm it stopped, *before* anything is replaced. Asking for the
// restart after `install` is the shape that does not work: the pinned Windows installer hands off
Expand All @@ -404,17 +469,17 @@ pub async fn install(app: &AppHandle, update: Update) -> Result<(), String> {
// Not an ending after all: the app goes back to running, so a close hides again, Quit
// works and Install can be retried. A drain somebody else owns is left alone.
recover_after_failed_install(app);
return Err(format!(
"the update was downloaded but not installed: {}",
return Err(InstallFailure::new(format!(
"The update was downloaded and verified, but {}. Installation has not started.",
readiness.describe()
));
)));
}

if let Err(error) = crate::process_spawn::with_spawn(|| update.install(package)) {
// The installer returned a failure. The runtime was stopped for an install that did not
// happen, so the app brings one back instead of sitting drained.
recover_after_failed_install(app);
return Err(error.to_string());
return Err(InstallFailure::package(PackageStep::Install, error));
}
// Only reached where the installer returns. On Windows it does not.
crate::exit::complete_restart(app)
Expand Down Expand Up @@ -517,6 +582,45 @@ mod tests {
use std::sync::{mpsc, Arc};
use tauri_utils::config::BundleType;

#[test]
fn install_failures_publish_only_the_stage_and_download_advice() {
use super::{InstallFailure, PackageStep};
use tauri_plugin_updater::Error;
let private = "private-updater-detail";
for (step, error, stage, manual) in [
(
PackageStep::Download,
Error::Network(private.into()),
"downloaded",
true,
),
(
PackageStep::Download,
Error::SignatureUtf8(private.into()),
"signature",
false,
),
(
PackageStep::Install,
Error::MissingSignedVersion,
"signature",
false,
),
(
PackageStep::Install,
Error::Io(std::io::Error::other(private)),
"installer",
false,
),
] {
let value = serde_json::to_value(InstallFailure::package(step, error)).unwrap();
assert!(value["message"].as_str().unwrap().contains(stage));
assert_eq!(value["manualDownload"], manual);
assert_eq!(value.as_object().unwrap().len(), 2);
assert!(!value.to_string().contains(private));
}
}

#[test]
fn a_failed_install_restarts_the_runtime_only_when_the_drain_had_stopped_it() {
let coordinator = ExitCoordinator::new();
Expand Down
14 changes: 11 additions & 3 deletions desktop/ui/update.html
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,9 @@ <h1>OpenCodex update</h1>
});
}
function showError(cause, installFailed = false) {
const message = cause instanceof Error ? cause.message : String(cause);
const version = installFailed ? latest?.latestVersion : null;
const nativeFailure = installFailed && typeof cause?.message === "string" && typeof cause.manualDownload === "boolean";
const message = nativeFailure || cause instanceof Error ? cause.message : String(cause);
const version = nativeFailure && cause.manualDownload ? latest?.latestVersion : null;
const hint = version
? " If automatic download is slow or blocked by network, install the package manually from GitHub Releases (v" + version + ")."
: "";
Expand Down Expand Up @@ -176,7 +177,14 @@ <h1>OpenCodex update</h1>
manual.hidden = true;
state.textContent = "Installing update…";
try { render(await call("update_install")); }
catch (cause) { showError(cause, true); try { render(await call("update_status")); } catch (readError) { showError(readError, true); } }
catch (cause) {
showError(cause, true);
try { render(await call("update_status")); }
catch {
latest = null;
state.textContent = "Update status is unavailable. Check again before retrying.";
}
}
finally { busy = false; if (latest) render(latest); else check.disabled = false; }
});
back.addEventListener("click", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ Una configuración predeterminada de pnpm 11 o 12 supera esta comprobación y se

## La actualización de Desktop se detiene o falla en «Instalar actualización…»

En la aplicación de escritorio OpenCodex, **Instalar actualización** descarga el instalador desde GitHub Releases antes de reemplazar la aplicación y reiniciarla. Una descarga o instalación fallida con una versión conocida muestra una sugerencia de descarga manual y un enlace a la página de lanzamiento de esa versión.
En la aplicación de escritorio OpenCodex, **Instalar actualización** descarga el paquete desde GitHub Releases y verifica su firma. La ventana indica si falló la verificación, si no se pudo identificar o detener el proxy, si ya se estaba deteniendo o si falló el instalador. Si se agota el tiempo de espera, comprueba el estado antes de volver a intentarlo.

Si `Installing update…` no avanza o agota el plazo, es posible que la red esté ralentizando o bloqueando las descargas de GitHub Releases. Abre el enlace a la versión exacta que muestra el error, o busca esa misma versión en la [página de versiones de OpenCodex](https://github.com/lidge-jun/opencodex/releases). Descarga manualmente el instalador correspondiente a tu sistema operativo y arquitectura. Las versiones preview tienen sus propias páginas; elige la versión que ofrece la aplicación.
Si falla la descarga del paquete y se conoce la versión, la ventana muestra un enlace a esa versión. Abre el enlace o busca esa misma versión en la [página de versiones de OpenCodex](https://github.com/lidge-jun/opencodex/releases). Descarga el instalador correspondiente a tu sistema operativo y arquitectura. Elige la versión que ofrece la aplicación, incluida la de vista previa si corresponde.

Antes de ejecutar el instalador, detenga el proxy a través de su propietario y confirme que se ha detenido:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,12 @@ sürerse tam `ocx update` terminal çıktısı, `npm config get prefix` ve
## Masaüstü güncellemesi “Installing update…” aşamasında takılıyorsa

OpenCodex masaüstü uygulamasında **Install update**, uygulamayı değiştirmeden ve
yeniden başlatmadan önce yükleyiciyi GitHub Releases'ten indirir. Bilinen sürümde
indirme/kurulum başarısızsa elle indirme ipucu ve o sürümün yayın bağlantısı gösterilir.
yeniden başlatmadan önce yükleyiciyi GitHub Releases'ten indirir ve imzasını doğrular.
Pencere, imza doğrulama hatasını, proxy'nin belirlenemediğini veya durdurulamadığını,
durdurma işleminin zaten sürdüğünü ya da yükleyicinin başarısız olduğunu bildirir.
Zaman aşımı durumunda yeniden denemeden önce güncelleme durumunu kontrol edin.

“Installing update…” takılır veya zaman aşımına uğrarsa ağınız GitHub yayın
indirmelerini yavaşlatıyor veya engelliyor olabilir. Hatadaki bağlantıyı kullanın
Paket indirilemezse ve sürüm biliniyorsa pencere o sürümün bağlantısını gösterir. Bağlantıyı kullanın
ya da [yayınlar sayfasında](https://github.com/lidge-jun/opencodex/releases) aynı
sürümü bulup işletim sisteminize ve mimarinize uygun yükleyiciyi indirin.
Önizleme sürümlerinin ayrı sayfaları vardır; uygulamanın önerdiği sürümü seçin.
Expand Down
9 changes: 5 additions & 4 deletions docs-site/src/content/docs/troubleshooting/update-failed.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,11 +226,12 @@ A default pnpm 11 or 12 setup passes this check and updates normally with `ocx u
## Desktop app update stalls or fails on "Installing update…"

In the OpenCodex desktop app, **Install update** downloads the installer from GitHub
Releases before replacing the app and restarting. A failed download or installation with
a known version shows a manual-download hint and a link to that version's release page.
Releases and verifies its signature. The update window reports whether verification failed,
the runtime could not stop or be identified, another stop is in progress, or the platform
installer failed. If the window times out, check the update status before retrying.

If `Installing update…` stalls or times out, GitHub release downloads may be slow or
blocked by your network. Use the release link in the error, or find the same version on
If the package download fails, the window links to the offered version when it is known.
Use that link, or find the same version on
the [OpenCodex releases page](https://github.com/lidge-jun/opencodex/releases), and download
the installer for your operating system and architecture. Preview versions have their own
release pages; choose the version the app offered.
Expand Down
2 changes: 1 addition & 1 deletion structure/desktop-shell.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ commands. Tray and page installation share one atomic claim before taking `Pendi
a failed download or drain restores that pending signed update and reenables retry. The
page returns through the startup sequence's resolved dashboard URL, independently of the
one-time initial navigation claim. The loopback dashboard has no updater IPC permission.
Install/download failures with a known version show a manual-download hint and that version's GitHub release link; navigation errors do not.
Install errors identify the failed stage. Only a package download request failure with a known version shows the manual-download hint and release link. Signature, runtime and installer diagnostics use bounded messages on the page. The native log retains the detailed error.

The window may navigate to the `tauri://` scheme, to the loopback endpoint the sequence resolved,
and on Windows to `tauri.localhost`, which is where the pinned Tauri serves the app itself because
Expand Down
31 changes: 27 additions & 4 deletions tests/clients/desktop-update-surface.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,12 @@ describe("bundled desktop update surface", () => {
await settle();
expect(nodes.get("error")?.textContent).toContain("600000 ms");
expect(nodes.get("install")?.disabled).toBe(true);
expect(nodes.get("manual")?.hidden).toBe(true);
});
test("a failed download offers the known version's manual installer", async () => {
const status = { currentVersion: "2.65.0", latestVersion: "2.66.0-preview.1", available: true, installing: false, checking: false };
const { nodes, handlers } = evaluatePage(name => name === "update_install"
? Promise.reject(new Error("download failed")) : Promise.resolve(status));
? Promise.reject({ message: "download failed", manualDownload: true }) : Promise.resolve(status));
await settle();
handlers.get("install:click")?.();
await settle();
Expand All @@ -134,7 +135,7 @@ describe("bundled desktop update surface", () => {
test("an install failure without a known version has no manual hint", async () => {
const status = { currentVersion: "2.65.0", latestVersion: null, available: true, installing: false, checking: false };
const { nodes, handlers } = evaluatePage(name => name === "update_install"
? Promise.reject(new Error("install failed")) : Promise.resolve(status));
? Promise.reject({ message: "install failed", manualDownload: true }) : Promise.resolve(status));
await settle();
handlers.get("install:click")?.();
await settle();
Expand All @@ -144,8 +145,11 @@ describe("bundled desktop update surface", () => {
});
test("navigation and check failures clear a previous manual hint", async () => {
const status = { currentVersion: "2.65.0", latestVersion: "2.66.0", available: true, installing: false, checking: false };
const { nodes, handlers } = evaluatePage(name => name === "update_status"
? Promise.resolve(status) : Promise.reject(new Error(name + " failed")));
const { nodes, handlers } = evaluatePage(name => {
if (name === "update_status") return Promise.resolve(status);
if (name === "update_install") return Promise.reject({ message: "download failed", manualDownload: true });
return Promise.reject(new Error(name + " failed"));
});
await settle();
handlers.get("install:click")?.();
await settle();
Expand All @@ -159,6 +163,25 @@ describe("bundled desktop update surface", () => {
expect(nodes.get("error")?.textContent).toBe("update_check failed");
expect(nodes.get("manual")?.hidden).toBe(true);
});
test("a runtime refusal survives a failed status refresh without offering a manual install", async () => {
const status = { currentVersion: "2.65.0", latestVersion: "2.66.0", available: true, installing: false, checking: false };
const message = "The update was downloaded and verified, but the running proxy could not be identified. Installation has not started.";
let attempted = false;
const { nodes, handlers } = evaluatePage(name => {
if (name === "update_install") {
attempted = true;
return Promise.reject({ message, manualDownload: false });
}
return attempted ? Promise.reject(new Error("unavailable")) : Promise.resolve(status);
});
await settle();
await handlers.get("install:click")?.();
expect(nodes.get("error")?.textContent).toBe(message);
expect(nodes.get("manual")?.hidden).toBe(true);
expect(nodes.get("state")?.textContent).toContain("Check again");
expect(nodes.get("install")?.disabled).toBe(true);
expect(nodes.get("check")?.disabled).toBe(false);
});
test("a page check superseded by a tray check stays checking until the tray result settles", async () => {
const current = { currentVersion: "2.65.0", latestVersion: null, available: false, installing: false, checking: false };
const checking = { ...current, checking: true };
Expand Down
Loading