Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(console): make in-app update failures visible (#1167)

Laasya Bangaloreebe214ff792d
diff --git a/console/AGENTS.md b/console/AGENTS.md
index cf4db9b01..87c6823ce 100644
--- a/console/AGENTS.md
+++ b/console/AGENTS.md
@@ -673,7 +673,7 @@ pnpm run test
- App updates in dev: the update service is inert outside packaged builds, so the
"update available" UI cannot be exercised by `pnpm run dev` alone. Set
`SWITCHDASH_FAKE_UPDATE` to replay the lifecycle against a simulated release —
- `available`, `download-error`, `check-error`, `auth-required`, or `up-to-date`.
+ `available`, `install-error`, `download-error`, `check-error`, or `up-to-date`.
An unrecognised value fails at startup rather than silently doing nothing.
`SWITCHDASH_FAKE_UPDATE_VERSION` overrides the offered version (default: the
current minor, bumped) and `SWITCHDASH_FAKE_UPDATE_MS` the simulated download
diff --git a/console/agents/risky-areas/updater.md b/console/agents/risky-areas/updater.md
index 7536cacb4..eeb20333e 100644
--- a/console/agents/risky-areas/updater.md
+++ b/console/agents/risky-areas/updater.md
@@ -116,6 +116,36 @@ child process it spawns — including `gh` itself, which prefers `GH_TOKEN` over
keyring — so a token parked there outlives the login it came from and shadows the next
one until the app restarts.
+## When an install does not happen
+
+On macOS, Squirrel.Mac replaces the running bundle after the app hands over, and a
+failure there can be silent: the app relaunches on the old version. So
+`update-service.ts` treats an install as unconfirmed until the next launch:
+
+- `pending-install.ts` records the **target version** and the version that hands
+ over. The handover waits for this write. The next launch shows "didn't install"
+ only when the app comes back on the version that handed over. Any other version
+ means an install happened, by the updater or by hand.
+- An updater error while installing, a handover that throws, and the two-minute
+ restart guard all end in the same `install-failed` state. None of them goes back
+ to "ready to install", because restarting again fails the same way. A failed
+ check does not replace this state, and the failed version is not downloaded
+ again.
+- Before the download, `install-preflight.ts` checks that the bundle is not
+ translocated. It does not check ownership or write access: Squirrel.Mac asks for
+ an admin password when it cannot write the bundle, and the next launch reports
+ an install that still failed.
+- After an install fails, the updater no longer installs on quit, so the quit
+ from "Download manually" does not start a second, silent install. On macOS,
+ Squirrel.Mac can already hold a staged update, so this is not complete there.
+- `install-failed` offers "Download manually" (`manual-download.ts`), which opens the
+ newest release on the build's channel and quits. The link is read from GitHub,
+ never built from a version: stable opens `/releases/latest`, and canary looks up
+ the newest canary tag. A version can name a release that is gone, because the
+ workflow prunes old canaries and the dev harness invents versions. A check that
+ finds the same version again keeps showing the failure; a newer version is
+ offered as usual.
+
## Current Notes
- macOS and Linux release builds rebuild native modules for the target Electron version,
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
index 707d51dd9..c4ea16cb7 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
@@ -450,7 +450,8 @@ export type TelemetryEventMap = {
* Deliberately named for what it can actually observe. A successful install
* quits the app, so there is no moment afterwards in which to report one; what
* this counts is the point the update was handed to the installer. Whether it
- * worked is answered by `update_installed` on the next launch.
+ * worked is answered by `update_installed` on the next launch. A launch that
+ * comes back on the old version reports this event again, as a failure.
*/
update_install_started: {
outcome: TelemetryOutcome;
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/canary-feed.ts b/console/apps/switch-console-desktop/src/main/core/updates/canary-feed.ts
index 4ded2300a..e895dc31b 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/canary-feed.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/canary-feed.ts
@@ -18,8 +18,7 @@ interface GitHubRelease {
}
/**
- * The download URL of the newest published canary release, for electron-updater's
- * generic provider to read `canary*.yml` and the installers from.
+ * The tag of the newest published canary release.
*
* electron-updater's own GitHub provider finds a prerelease through the releases
* Atom feed, which lists only the ten newest releases of the repo. The agents
@@ -29,7 +28,7 @@ interface GitHubRelease {
*
* GitHub lists releases newest first, so the first canary found is the latest.
*/
-export async function resolveCanaryFeedUrl(): Promise<string> {
+export async function findLatestCanaryTag(): Promise<string> {
for (let page = 1; page <= MAX_PAGES; page++) {
const response = await fetch(`${RELEASES_API_URL}?per_page=${PAGE_SIZE}&page=${page}`, {
headers: { Accept: 'application/vnd.github+json', 'Cache-Control': 'no-cache' },
@@ -39,10 +38,18 @@ export async function resolveCanaryFeedUrl(): Promise<string> {
}
const releases = (await response.json()) as GitHubRelease[];
const canary = releases.find((r) => !r.draft && CANARY_TAG.test(r.tag_name));
- if (canary) return `${RELEASES_DOWNLOAD_URL}/${canary.tag_name}`;
+ if (canary) return canary.tag_name;
if (releases.length < PAGE_SIZE) break;
}
throw new Error(
`No published canary release among the newest ${MAX_PAGES * PAGE_SIZE} releases of the repo`
);
}
+
+/**
+ * The download URL of the newest published canary release, for electron-updater's
+ * generic provider to read `canary*.yml` and the installers from.
+ */
+export async function resolveCanaryFeedUrl(): Promise<string> {
+ return `${RELEASES_DOWNLOAD_URL}/${await findLatestCanaryTag()}`;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/controller.ts b/console/apps/switch-console-desktop/src/main/core/updates/controller.ts
index 9106ce75e..83c60b26b 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/controller.ts
@@ -1,8 +1,10 @@
-import { app, shell } from 'electron';
+import { app } from 'electron';
+import { appService } from '@main/core/app/service';
import type { TelemetryUpdateTrigger } from '@main/core/telemetry/events';
import { updateService } from '@main/core/updates/update-service';
+import { IS_CANARY } from '@shared/app-identity';
import { createRPCController } from '@shared/lib/ipc/rpc';
-import { SWITCH_CONSOLE_RELEASES_URL } from '@shared/urls';
+import { manualDownloadUrl } from './manual-download';
import { formatUpdaterError } from './utils';
export const updateController = createRPCController({
@@ -33,9 +35,13 @@ export const updateController = createRPCController({
}
},
+ /**
+ * Hand the update to the user: open the page of this channel's newest release
+ * and quit, so the app can be replaced while it is not running.
+ */
openLatest: async () => {
try {
- await shell.openExternal(SWITCH_CONSOLE_RELEASES_URL);
+ await appService.openExternal(await manualDownloadUrl(IS_CANARY));
setTimeout(() => {
try {
app.quit();
@@ -47,6 +53,15 @@ export const updateController = createRPCController({
}
},
+ openReleaseNotes: async () => {
+ try {
+ await appService.openExternal(await updateService.releaseNotesUrl());
+ return { success: true };
+ } catch (error) {
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
+ }
+ },
+
getState: async () => {
try {
const state = updateService.getState();
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/dev-harness.ts b/console/apps/switch-console-desktop/src/main/core/updates/dev-harness.ts
index f7ffdb39b..29f33f4f7 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/dev-harness.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/dev-harness.ts
@@ -16,6 +16,8 @@ export const FAKE_UPDATE_DURATION_ENV_VAR = 'SWITCHDASH_FAKE_UPDATE_MS';
export const FAKE_UPDATE_SCENARIOS = [
/** Check finds an update; download succeeds; install rolls back (dev cannot restart). */
'available',
+ /** Check finds an update; download succeeds; the install fails. */
+ 'install-error',
/** Check finds an update; the download fails part-way. */
'download-error',
/** The check itself fails. */
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/install-preflight.test.ts b/console/apps/switch-console-desktop/src/main/core/updates/install-preflight.test.ts
new file mode 100644
index 000000000..1055bf740
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/updates/install-preflight.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { isTranslocated } from './install-preflight';
+
+describe('isTranslocated', () => {
+ it('finds an app that Gatekeeper runs from a randomised mount', () => {
+ expect(
+ isTranslocated(
+ '/private/var/folders/x/T/AppTranslocation/1A2B/d/Switch Console.app/Contents/MacOS/Switch Console'
+ )
+ ).toBe(true);
+ });
+
+ it('passes an app in the Applications folder', () => {
+ expect(isTranslocated('/Applications/Switch Console.app/Contents/MacOS/Switch Console')).toBe(
+ false
+ );
+ });
+
+ it('passes an app run from a user folder', () => {
+ expect(
+ isTranslocated('/Users/me/Downloads/Switch Console.app/Contents/MacOS/Switch Console')
+ ).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/install-preflight.ts b/console/apps/switch-console-desktop/src/main/core/updates/install-preflight.ts
new file mode 100644
index 000000000..899537d51
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/updates/install-preflight.ts
@@ -0,0 +1,14 @@
+/**
+ * Whether macOS runs this copy of the app from a translocated path.
+ *
+ * Gatekeeper runs a downloaded app that was not moved out of its download
+ * folder from a randomised read-only mount. Squirrel.Mac cannot replace a
+ * bundle there, and the failure comes after the app has handed over.
+ *
+ * Ownership and write access are not checked: Squirrel.Mac asks for an admin
+ * password when it cannot write the bundle, and the launch after a handover
+ * reports an install that still failed.
+ */
+export function isTranslocated(executablePath: string): boolean {
+ return executablePath.includes('/AppTranslocation/');
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/manual-download.test.ts b/console/apps/switch-console-desktop/src/main/core/updates/manual-download.test.ts
new file mode 100644
index 000000000..fd2e14e21
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/updates/manual-download.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type * as CanaryFeed from './canary-feed';
+
+const h = vi.hoisted(() => ({ findLatestCanaryTag: vi.fn() }));
+
+vi.mock('./canary-feed', () => ({
+ findLatestCanaryTag: h.findLatestCanaryTag,
+}));
+vi.mock('@main/lib/logger', () => ({
+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+const { log } = await import('@main/lib/logger');
+const actualCanaryFeed = await vi.importActual<typeof CanaryFeed>('./canary-feed');
+const { manualDownloadUrl } = await import('./manual-download');
+
+const RELEASES = 'https://github.com/sandbox-quantum/switch/releases';
+
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('manualDownloadUrl', () => {
+ it('sends a stable build to the release GitHub marks Latest', async () => {
+ await expect(manualDownloadUrl(false)).resolves.toBe(`${RELEASES}/latest`);
+ expect(h.findLatestCanaryTag).not.toHaveBeenCalled();
+ });
+
+ it('sends a canary build to the newest canary that exists', async () => {
+ h.findLatestCanaryTag.mockResolvedValue('v0.41.0-canary.1');
+
+ await expect(manualDownloadUrl(true)).resolves.toBe(`${RELEASES}/tag/v0.41.0-canary.1`);
+ });
+
+ it('falls back to the releases list, and says so, when the lookup fails', async () => {
+ h.findLatestCanaryTag.mockRejectedValue(new Error('GitHub answered HTTP 403'));
+
+ await expect(manualDownloadUrl(true)).resolves.toBe(RELEASES);
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ errorCode: 'canary_lookup_failed' })
+ );
+ });
+});
+
+describe('manualDownloadUrl against the real canary lookup', () => {
+ function lookUpForReal(fetchImpl: () => Promise<Response>): void {
+ h.findLatestCanaryTag.mockImplementation(actualCanaryFeed.findLatestCanaryTag);
+ vi.stubGlobal('fetch', vi.fn(fetchImpl));
+ }
+
+ it('falls back to the releases list when GitHub cannot be reached', async () => {
+ lookUpForReal(() => Promise.reject(new TypeError('fetch failed')));
+
+ await expect(manualDownloadUrl(true)).resolves.toBe(RELEASES);
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ errorCode: 'canary_lookup_failed',
+ error: expect.stringContaining('fetch failed'),
+ })
+ );
+ });
+
+ it('falls back to the releases list when GitHub answers with an error', async () => {
+ lookUpForReal(async () => new Response('rate limited', { status: 403 }));
+
+ await expect(manualDownloadUrl(true)).resolves.toBe(RELEASES);
+ });
+
+ it('falls back to the releases list when no canary is published', async () => {
+ lookUpForReal(
+ async () =>
+ new Response(JSON.stringify([{ tag_name: 'switch-console-v1.0.0', draft: false }]), {
+ status: 200,
+ })
+ );
+
+ await expect(manualDownloadUrl(true)).resolves.toBe(RELEASES);
+ });
+
+ it('skips a draft canary, which has no page to open', async () => {
+ lookUpForReal(
+ async () =>
+ new Response(
+ JSON.stringify([
+ { tag_name: 'v0.42.0-canary.1', draft: true },
+ { tag_name: 'v0.41.0-canary.3', draft: false },
+ ]),
+ { status: 200 }
+ )
+ );
+
+ await expect(manualDownloadUrl(true)).resolves.toBe(`${RELEASES}/tag/v0.41.0-canary.3`);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/manual-download.ts b/console/apps/switch-console-desktop/src/main/core/updates/manual-download.ts
new file mode 100644
index 000000000..4473fdb29
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/updates/manual-download.ts
@@ -0,0 +1,31 @@
+import { log } from '@main/lib/logger';
+import { SWITCH_CONSOLE_RELEASES_URL } from '@shared/urls';
+import { findLatestCanaryTag } from './canary-feed';
+
+/**
+ * The page to download this channel's newest release from by hand.
+ *
+ * Read from GitHub, never built from a version number. A version can name a
+ * release that is not there: the dev harness makes its versions up, and the
+ * release workflow deletes all but the newest canaries.
+ *
+ * Stable needs no lookup. `/releases/latest` redirects to the release GitHub
+ * marks Latest, and the release workflow gives that mark only to stable Switch
+ * Console releases. Canaries are prereleases, so the newest one is looked up.
+ */
+export async function manualDownloadUrl(isCanary: boolean): Promise<string> {
+ if (!isCanary) return `${SWITCH_CONSOLE_RELEASES_URL}/latest`;
+
+ try {
+ return `${SWITCH_CONSOLE_RELEASES_URL}/tag/${await findLatestCanaryTag()}`;
+ } catch (error) {
+ // The list of releases still has the canary, among other components' builds.
+ log.warn('Could not find the newest canary; opening the releases list instead', {
+ event: 'update.manual_download',
+ stage: 'resolve',
+ errorCode: 'canary_lookup_failed',
+ error: String(error),
+ });
+ return SWITCH_CONSOLE_RELEASES_URL;
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/pending-install.db.test.ts b/console/apps/switch-console-desktop/src/main/core/updates/pending-install.db.test.ts
new file mode 100644
index 000000000..df6e58024
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/updates/pending-install.db.test.ts
@@ -0,0 +1,128 @@
+import { openFixture } from '@tooling/utils/db';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AppDb } from '@main/db/client';
+import { kv } from '@main/db/schema';
+
+const mocks = vi.hoisted(() => ({
+ db: undefined as AppDb | undefined,
+}));
+
+vi.mock('@main/db/client', () => ({
+ get db() {
+ if (!mocks.db) throw new Error('Test database not initialized');
+ return mocks.db;
+ },
+}));
+
+/**
+ * The marker as one run of the app sees it. `take()` keeps its answer for the
+ * whole run, so each launch is a fresh copy of the module.
+ */
+async function launch() {
+ vi.resetModules();
+ return (await import('./pending-install')).pendingInstall;
+}
+
+describe('the pending-install marker', () => {
+ let fixture: Awaited<ReturnType<typeof openFixture>>;
+
+ let pendingInstall: Awaited<ReturnType<typeof launch>>;
+
+ beforeEach(async () => {
+ fixture = await openFixture('empty');
+ mocks.db = fixture.db;
+ pendingInstall = await launch();
+ });
+
+ afterEach(() => {
+ fixture.close();
+ mocks.db = undefined;
+ });
+
+ it('is empty on an ordinary launch', async () => {
+ await expect(pendingInstall.take()).resolves.toBeNull();
+ });
+
+ it('returns the version handed over, and the one it replaces, once', async () => {
+ await pendingInstall.set('1.3.0', '1.2.3');
+
+ await expect(pendingInstall.take()).resolves.toEqual({
+ targetVersion: '1.3.0',
+ fromVersion: '1.2.3',
+ });
+ // The next launch finds nothing.
+ await expect((await launch()).take()).resolves.toBeNull();
+ });
+
+ it('gives every caller in a run the same answer', async () => {
+ // The update service and the launch report both ask. Whichever is second
+ // must not read the record that the first one cleared.
+ await pendingInstall.set('1.3.0', '1.2.3');
+
+ const [first, second] = await Promise.all([pendingInstall.take(), pendingInstall.take()]);
+
+ expect(first).toEqual({ targetVersion: '1.3.0', fromVersion: '1.2.3' });
+ expect(second).toEqual(first);
+ });
+
+ it('is gone after an attempt is abandoned', async () => {
+ await pendingInstall.set('1.3.0', '1.2.3');
+ await pendingInstall.clear();
+
+ await expect(pendingInstall.take()).resolves.toBeNull();
+ });
+
+ it('reads the marker a build without target versions wrote', async () => {
+ // The first launch of this build follows an install handed over by the
+ // build before it, which wrote only `true`.
+ await fixture.db
+ .insert(kv)
+ .values({ key: 'updates:pending-install:handover', value: 'true', updatedAt: Date.now() });
+
+ await expect(pendingInstall.take()).resolves.toEqual({
+ targetVersion: null,
+ fromVersion: null,
+ });
+ await expect((await launch()).take()).resolves.toBeNull();
+ });
+
+ it('reports the latest version when a second attempt overwrites the first', async () => {
+ await pendingInstall.set('1.3.0', '1.2.3');
+ await pendingInstall.set('1.4.0', '1.2.3');
+
+ await expect(pendingInstall.take()).resolves.toEqual({
+ targetVersion: '1.4.0',
+ fromVersion: '1.2.3',
+ });
+ });
+
+ it('prefers the version, and clears both, when both markers are present', async () => {
+ await fixture.db
+ .insert(kv)
+ .values({ key: 'updates:pending-install:handover', value: 'true', updatedAt: Date.now() });
+ await pendingInstall.set('1.3.0', '1.2.3');
+
+ await expect(pendingInstall.take()).resolves.toEqual({
+ targetVersion: '1.3.0',
+ fromVersion: '1.2.3',
+ });
+ await expect((await launch()).take()).resolves.toBeNull();
+ });
+
+ it('clears the legacy marker too when an attempt is abandoned', async () => {
+ await fixture.db
+ .insert(kv)
+ .values({ key: 'updates:pending-install:handover', value: 'true', updatedAt: Date.now() });
+ await pendingInstall.clear();
+
+ await expect(pendingInstall.take()).resolves.toBeNull();
+ });
+
+ it('fails loud when the marker cannot be written', async () => {
+ // A handover with no marker could fail without anyone finding out, so the
+ // caller has to hear about it.
+ mocks.db = undefined;
+
+ await expect(pendingInstall.set('1.3.0', '1.2.3')).rejects.toThrow();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/pending-install.test.ts b/console/apps/switch-console-desktop/src/main/core/updates/pending-install.test.ts
index 973042c16..539053bf4 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/pending-install.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/pending-install.test.ts
@@ -15,6 +15,9 @@ vi.mock('@main/db/kv', () => ({
async del(key: string) {
h.values.delete(key);
}
+ async clear() {
+ h.values.clear();
+ }
},
}));
@@ -38,13 +41,16 @@ describe('the handover marker', () => {
// The update service and the launch report both ask; whichever is second
// must not read the record the first one cleared and answer no.
- expect([first, second]).toEqual([true, true]);
- expect(await marker.pendingInstall.take()).toBe(true);
+ // A marker from a build that recorded no version.
+ const handover = { targetVersion: null, fromVersion: null };
+ expect([first, second]).toEqual([handover, handover]);
+ expect(await marker.pendingInstall.take()).toEqual(handover);
expect(h.values.has('handover')).toBe(false);
- expect(h.reads).toBe(1);
+ // One read of each of the three keys, once for the whole run.
+ expect(h.reads).toBe(3);
});
it('answers no when the previous run handed nothing over', async () => {
- expect(await marker.pendingInstall.take()).toBe(false);
+ expect(await marker.pendingInstall.take()).toBeNull();
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/pending-install.ts b/console/apps/switch-console-desktop/src/main/core/updates/pending-install.ts
index e46f48899..a2bbe4ca8 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/pending-install.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/pending-install.ts
@@ -5,39 +5,65 @@ import { KV } from '@main/db/kv';
*
* An install that works ends this process, so the only way to report that one
* happened is to write it down first and read it back in the process that comes
- * after. The marker is set immediately before the handover and cleared by the
- * rollback, so on the next launch its presence means the app really did go down
- * for an installer rather than unwinding back to "ready to install".
+ * after. The marker is set immediately before the handover and cleared when an
+ * install attempt is abandoned, so on the next launch its presence means the app
+ * really did go down for an installer rather than unwinding back to "ready to install".
*
- * It says only that a handover happened — not that the new version is running.
- * That question is answered by the version `app_launched` carries.
+ * It records the version being installed and the version it replaces, because
+ * going down for the installer is not the same as coming back on the new
+ * version: on macOS, Squirrel.Mac can fail to replace the bundle and relaunch
+ * the old one without a word.
*/
-const store = new KV<Record<string, boolean>>('updates:pending-install');
+const store = new KV<{
+ /** Written by builds that did not record a target version. */
+ handover: boolean;
+ target: string;
+ from: string;
+}>('updates:pending-install');
-const KEY = 'handover';
+export interface PendingHandover {
+ /** The version handed to the installer; null for a marker an older build wrote. */
+ targetVersion: string | null;
+ /** The version that handed over; null for a marker an older build wrote. */
+ fromVersion: string | null;
+}
/** This run's answer, once anything has asked. */
-let taken: Promise<boolean> | null = null;
+let taken: Promise<PendingHandover | null> | null = null;
export const pendingInstall = {
- set: (): Promise<void> => store.set(KEY, true),
- clear: (): Promise<void> => store.del(KEY),
+ /**
+ * Record a handover. Throws when the write fails, because a handover with no
+ * record can fail without anyone finding out.
+ */
+ set: async (targetVersion: string, fromVersion: string): Promise<void> => {
+ await store.setOrThrow('target', targetVersion);
+ await store.setOrThrow('from', fromVersion);
+ },
+
+ clear: (): Promise<void> => store.clear(),
/**
- * Whether the previous run handed an update over, clearing the record so a
- * launch is only ever counted once. Cleared before the caller reports, so a
- * report that fails to send loses one event rather than repeating it on every
- * launch from here on.
+ * The handover the previous run made, if any, clearing the record so a launch
+ * is only ever counted once. Cleared before the caller reports, so a report
+ * that fails to send loses one event rather than repeating it on every launch
+ * from here on.
*
* The same answer for every caller in this run: the update service reports
* the handover and the launch report says which kind of install it was, and
* whichever asks first must not leave the other reading a cleared record.
*/
- take(): Promise<boolean> {
+ take(): Promise<PendingHandover | null> {
taken ??= (async () => {
- if ((await store.get(KEY)) !== true) return false;
- await store.del(KEY);
- return true;
+ const target = await store.get('target');
+ const from = await store.get('from');
+ const legacy = await store.get('handover');
+ if (typeof target !== 'string' && legacy !== true) return null;
+ await pendingInstall.clear();
+ return {
+ targetVersion: typeof target === 'string' ? target : null,
+ fromVersion: typeof from === 'string' ? from : null,
+ };
})();
return taken;
},
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/update-service.test.ts b/console/apps/switch-console-desktop/src/main/core/updates/update-service.test.ts
index e86b18011..0081a840c 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/update-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/update-service.test.ts
@@ -15,8 +15,18 @@ const h = vi.hoisted(() => ({
downloadUpdate: vi.fn(),
quitAndInstall: vi.fn(),
trackEvent: vi.fn(),
+ isTranslocated: vi.fn(),
+ /** The flags the service sets on the updater. */
+ updater: { autoInstallOnAppQuit: true },
/** The handover marker, which outlives the process in the real thing. */
- pending: { handover: false },
+ pending: {
+ target: null as string | null,
+ from: null as string | null,
+ legacy: false,
+ failWrite: false,
+ /** While set, the marker write does not settle until this promise does. */
+ pendingWrite: null as Promise<void> | null,
+ },
}));
vi.mock('electron', async () => {
@@ -26,13 +36,13 @@ vi.mock('electron', async () => {
vi.mock('electron-updater', () => ({
default: {
- autoUpdater: {
+ autoUpdater: Object.assign(h.updater, {
on: (event: string, fn: (arg?: unknown) => void) => h.handlers.set(event, fn),
setFeedURL: h.setFeedURL,
checkForUpdatesAndNotify: h.checkForUpdatesAndNotify,
downloadUpdate: h.downloadUpdate,
quitAndInstall: h.quitAndInstall,
- },
+ }),
},
}));
@@ -41,19 +51,29 @@ vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent: h.trackEv
// app to open.
vi.mock('./pending-install', () => ({
pendingInstall: {
- set: async () => {
- h.pending.handover = true;
+ set: async (target: string, from: string) => {
+ if (h.pending.pendingWrite) await h.pending.pendingWrite;
+ if (h.pending.failWrite) throw new Error('SQLITE_FULL: database or disk is full');
+ h.pending.target = target;
+ h.pending.from = from;
},
clear: async () => {
- h.pending.handover = false;
+ h.pending.target = null;
+ h.pending.from = null;
+ h.pending.legacy = false;
},
take: async () => {
- const held = h.pending.handover;
- h.pending.handover = false;
- return held;
+ const { target, from, legacy } = h.pending;
+ h.pending.target = null;
+ h.pending.from = null;
+ h.pending.legacy = false;
+ return target !== null || legacy ? { targetVersion: target, fromVersion: from } : null;
},
},
}));
+// The real check reads the path of the running executable;
+// install-preflight.test.ts covers it.
+vi.mock('./install-preflight', () => ({ isTranslocated: h.isTranslocated }));
vi.mock('@main/core/app/utils', () => ({ resolveAppVersion: async () => '1.2.3' }));
vi.mock('@main/lib/events', () => ({ events: { emit: vi.fn() } }));
vi.mock('@main/lib/logger', () => ({
@@ -62,7 +82,9 @@ vi.mock('@main/lib/logger', () => ({
import type { EventEmitter } from 'node:events';
import { app } from 'electron';
+import { events } from '@main/lib/events';
import type * as AppIdentity from '@shared/app-identity';
+import { updateInstallFailedEvent } from '@shared/events/updateEvents';
import { updateService } from './update-service';
/** The app going down for the installer, as the service observes it. */
@@ -74,6 +96,37 @@ function installEvents(): unknown[] {
return h.trackEvent.mock.calls.filter(([name]) => name === 'update_install_started');
}
+function installFailures(): unknown[] {
+ return vi.mocked(events.emit).mock.calls.filter(([event]) => event === updateInstallFailedEvent);
+}
+
+/**
+ * Drive the service to "ready to install" through its own listeners: that state
+ * is not reachable any other way, and going round them would test a state the
+ * app cannot be in.
+ */
+async function downloadVersion(version: string): Promise<void> {
+ h.handlers.get('update-not-available')?.();
+ h.handlers.get('update-available')?.({ version });
+ h.handlers.get('update-downloaded')?.({ version });
+ await vi.advanceTimersByTimeAsync(0);
+}
+
+/** Drive the service to "available", the state a download starts from. */
+function offerVersion(version: string): void {
+ h.handlers.get('update-not-available')?.();
+ h.handlers.get('update-available')?.({ version });
+}
+
+/** Run a test as if on macOS, the one platform whose bundle is checked. */
+function onMac(): () => void {
+ const original = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ return () => {
+ if (original) Object.defineProperty(process, 'platform', original);
+ };
+}
+
beforeAll(async () => {
vi.useFakeTimers();
// The updater is inert outside a packaged build, and the dev harness is the
@@ -91,6 +144,11 @@ afterAll(() => {
beforeEach(() => {
h.trackEvent.mockClear();
+ vi.mocked(events.emit).mockClear();
+ h.isTranslocated.mockReset();
+ h.isTranslocated.mockReturnValue(false);
+ h.pending.failWrite = false;
+ h.pending.pendingWrite = null;
});
describe('what a check reports', () => {
@@ -174,24 +232,22 @@ describe('what a download reports', () => {
});
describe('what one install attempt reports', () => {
- beforeEach(() => {
- // Through the service's own listeners: "downloaded" is not reachable any
- // other way, and going round them would test a state the app cannot be in.
- h.handlers.get('update-available')?.({ version: '1.3.0' });
- h.handlers.get('update-downloaded')?.({ version: '1.3.0' });
+ beforeEach(async () => {
+ await downloadVersion('1.3.0');
h.quitAndInstall.mockReset();
h.trackEvent.mockClear();
+ vi.mocked(events.emit).mockClear();
});
- afterEach(() => {
+ afterEach(async () => {
// Unwind an attempt that is still open, so the next test is not refused as a
// duplicate. The latch means this adds nothing to what was already reported.
- vi.advanceTimersByTime(3 * 60 * 1000);
+ await vi.advanceTimersByTimeAsync(3 * 60 * 1000);
});
- it('says nothing about a handover from inside the process it ends', () => {
+ it('says nothing about a handover from inside the process it ends', async () => {
updateService.quitAndInstall();
- vi.advanceTimersByTime(250);
+ await vi.advanceTimersByTimeAsync(250);
quitApp();
// The shutdown handler calls `app.exit`, and a send is a consent read and an
@@ -199,38 +255,245 @@ describe('what one install attempt reports', () => {
// marker, which the next launch reports from.
expect(h.quitAndInstall).toHaveBeenCalled();
expect(installEvents()).toEqual([]);
- expect(h.pending.handover).toBe(true);
+ // The version, so the next launch can tell an install from a relaunch.
+ expect(h.pending.target).toBe('1.3.0');
});
- it('reports a handover that threw, and reports only that', () => {
+ it('reports a handover that threw, and reports only that', async () => {
h.quitAndInstall.mockImplementation(() => {
throw new Error('installer is missing');
});
updateService.quitAndInstall();
- vi.advanceTimersByTime(250);
+ await vi.advanceTimersByTimeAsync(250);
expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+ expect(updateService.getState()).toMatchObject({ status: 'install-failed' });
+ expect(updateService.getState().error).toContain('installer is missing');
});
- it('reports an install that never left as one failure', () => {
+ it('shows an installer error that arrives after the handover', async () => {
+ // Squirrel.Mac's failure to replace the bundle reaches the updater's error
+ // listener while the app is still on "installing".
updateService.quitAndInstall();
- vi.advanceTimersByTime(250);
- vi.advanceTimersByTime(2 * 60 * 1000);
+ await vi.advanceTimersByTimeAsync(250);
+ h.handlers.get('error')?.(new Error('Could not write the app bundle'));
+ expect(updateService.getState()).toMatchObject({
+ status: 'install-failed',
+ availableVersion: '1.3.0',
+ });
+ expect(installFailures()).toEqual([
+ [
+ updateInstallFailedEvent,
+ {
+ version: '1.3.0',
+ message: "Version 1.3.0 didn't install: Could not write the app bundle",
+ foundAtLaunch: false,
+ },
+ ],
+ ]);
expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+ expect(h.pending.target).toBeNull();
+
+ // The guard that would have fired later has nothing left to report.
+ await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
+ expect(installEvents()).toHaveLength(1);
+ expect(installFailures()).toHaveLength(1);
});
- it('adds nothing when the app quits long after an attempt was written off', () => {
+ it('reports an install that never left as one failure', async () => {
updateService.quitAndInstall();
- vi.advanceTimersByTime(250);
- vi.advanceTimersByTime(2 * 60 * 1000);
+ await vi.advanceTimersByTimeAsync(250);
+ await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
+
+ expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+ // Not back to "ready to install": restarting again would fail the same way.
+ expect(updateService.getState()).toMatchObject({ status: 'install-failed' });
+ expect(installFailures()).toHaveLength(1);
+ });
+
+ it('does not hand over after an installer error has already ended the attempt', async () => {
+ updateService.quitAndInstall();
+ // An error inside the 250 ms before the handover.
+ await vi.advanceTimersByTimeAsync(100);
+ h.handlers.get('error')?.(new Error('Could not write the app bundle'));
+ await vi.advanceTimersByTimeAsync(150);
+
+ expect(updateService.getState()).toMatchObject({ status: 'install-failed' });
+ // The panel says the update didn't install, so the app must not then go
+ // down for the installer anyway.
+ expect(h.quitAndInstall).not.toHaveBeenCalled();
+ });
+
+ it('refuses a second restart while one is in progress', async () => {
+ updateService.quitAndInstall();
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(h.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+
+ it('adds nothing when the app quits long after an attempt was written off', async () => {
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(250);
+ await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
quitApp();
expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
// An attempt that unwound leaves nothing for the next launch to find, or it
// would be reported as a success as well as a failure.
- expect(h.pending.handover).toBe(false);
+ expect(h.pending.target).toBeNull();
+ });
+ it('does not hand over when the marker cannot be written', async () => {
+ h.pending.failWrite = true;
+
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(h.quitAndInstall).not.toHaveBeenCalled();
+ expect(updateService.getState()).toMatchObject({ status: 'install-failed' });
+ expect(updateService.getState().error).toContain('could not save the update');
+ expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+ });
+
+ it('waits for the marker write before the handover', async () => {
+ let finishWrite = () => {};
+ h.pending.pendingWrite = new Promise((resolve) => {
+ finishWrite = resolve;
+ });
+
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(h.quitAndInstall).not.toHaveBeenCalled();
+
+ finishWrite();
+ await vi.advanceTimersByTimeAsync(250);
+ expect(h.quitAndInstall).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not hand over after dispose', async () => {
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(100);
+ updateService.dispose();
+ await vi.advanceTimersByTimeAsync(250);
+ const handovers = h.quitAndInstall.mock.calls.length;
+ // Dispose also cleared the restart guard, so only an error can end the
+ // attempt that the next test would otherwise see as still open.
+ h.handlers.get('error')?.(new Error('Could not write the app bundle'));
+
+ expect(handovers).toBe(0);
+ });
+
+ it('records the version that handed over next to the target', async () => {
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(h.pending).toMatchObject({ target: '1.3.0', from: '1.2.3' });
+ });
+
+ it('does not check for updates during an install', async () => {
+ // An error from that check would read as an installer error.
+ h.checkForUpdatesAndNotify.mockClear();
+ updateService.quitAndInstall();
+
+ await expect(updateService.checkForUpdates('scheduled')).resolves.toBeNull();
+ expect(h.checkForUpdatesAndNotify).not.toHaveBeenCalled();
+ });
+
+ it('checks again on schedule after an install that failed', async () => {
+ // A scheduled check that fires during the install is skipped, and the
+ // failed attempt must re-arm the timer, or a fixed release is never offered.
+ // Clear the timer that earlier checks left, so only the attempt can arm one.
+ updateService.dispose();
+ updateService.quitAndInstall();
+ await expect(updateService.checkForUpdates('scheduled')).resolves.toBeNull();
+ await vi.advanceTimersByTimeAsync(250);
+ h.handlers.get('error')?.(new Error('Could not write the app bundle'));
+ h.checkForUpdatesAndNotify.mockReset();
+ h.checkForUpdatesAndNotify.mockResolvedValue({ isUpdateAvailable: false });
+
+ await vi.advanceTimersByTimeAsync(60 * 60 * 1000);
+
+ expect(h.checkForUpdatesAndNotify).toHaveBeenCalled();
+ updateService.dispose();
+ h.checkForUpdatesAndNotify.mockReset();
+ });
+
+ it('stops installing on quit after a failure, until a newer version is downloaded', async () => {
+ updateService.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(250);
+ h.handlers.get('error')?.(new Error('Could not write the app bundle'));
+
+ // "Download manually" quits the app, and that quit must not start a
+ // second install that could fail without a word.
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+
+ // The installer on disk is still the one that failed.
+ h.handlers.get('update-available')?.({ version: '1.4.0' });
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+
+ h.handlers.get('update-downloaded')?.({ version: '1.4.0' });
+ expect(h.updater.autoInstallOnAppQuit).toBe(true);
+ });
+});
+
+describe('the translocation check', () => {
+ let restorePlatform: () => void;
+
+ beforeEach(() => {
+ restorePlatform = onMac();
+ h.downloadUpdate.mockReset();
+ h.downloadUpdate.mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ restorePlatform();
+ });
+
+ it('stops a translocated copy before the download', async () => {
+ h.isTranslocated.mockReturnValue(true);
+ offerVersion('1.4.0');
+
+ await updateService.downloadUpdate();
+
+ expect(h.downloadUpdate).not.toHaveBeenCalled();
+ expect(updateService.getState()).toMatchObject({ status: 'install-failed' });
+ expect(updateService.getState().error).toMatch(/Applications folder/);
+ expect(() => updateService.quitAndInstall()).toThrow(/install-failed/);
+ });
+
+ it('downloads for a copy that is not translocated', async () => {
+ offerVersion('1.5.0');
+
+ await updateService.downloadUpdate();
+
+ expect(h.isTranslocated).toHaveBeenCalledWith(process.execPath);
+ expect(h.downloadUpdate).toHaveBeenCalled();
+ });
+
+ it('is not run off macOS, because only macOS replaces the running bundle', async () => {
+ restorePlatform();
+ const original = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ try {
+ offerVersion('1.6.0');
+ await updateService.downloadUpdate();
+ } finally {
+ if (original) Object.defineProperty(process, 'platform', original);
+ restorePlatform = onMac();
+ }
+
+ expect(h.isTranslocated).not.toHaveBeenCalled();
+ expect(h.downloadUpdate).toHaveBeenCalled();
+ });
+
+ it('links the release notes of the version on offer', async () => {
+ await downloadVersion('1.4.0');
+
+ await expect(updateService.releaseNotesUrl()).resolves.toBe(
+ 'https://github.com/sandbox-quantum/switch/releases/tag/switch-console-v1.4.0'
+ );
});
});
@@ -241,18 +504,122 @@ describe('the launch after an install', () => {
});
it('reports the handover the previous run wrote down', async () => {
- h.pending.handover = true;
+ h.pending.target = '1.2.3';
+ h.pending.from = '1.2.2';
const { updateService: restarted } = await import('./update-service');
await restarted.initialize();
expect(installEvents()).toEqual([['update_install_started', { outcome: 'success' }]]);
+ expect(restarted.getState()).toMatchObject({ status: 'idle' });
// Taken, not just read: a launch is counted once, and a user who never
// updates again does not report this install on every start from here on.
- expect(h.pending.handover).toBe(false);
+ expect(h.pending.target).toBeNull();
+ });
+
+ it('counts a marker from a build that recorded no version as a success', async () => {
+ h.pending.legacy = true;
+ const { updateService: restarted } = await import('./update-service');
+ await restarted.initialize();
+
+ expect(installEvents()).toEqual([['update_install_started', { outcome: 'success' }]]);
+ expect(h.pending.legacy).toBe(false);
+ });
+
+ it('says the update did not install when the app came back on the old version', async () => {
+ // Squirrel.Mac can take the app down, fail to replace the bundle, and
+ // relaunch the old one with nothing on screen.
+ h.pending.target = '1.3.0';
+ h.pending.from = '1.2.3';
+ const { updateService: restarted } = await import('./update-service');
+ const { events: restartedEvents } = await import('@main/lib/events');
+ const { updateInstallFailedEvent: failedEvent } = await import('@shared/events/updateEvents');
+ vi.mocked(restartedEvents.emit).mockClear();
+ await restarted.initialize();
+ restarted.dispose();
+
+ expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+ expect(restarted.getState()).toMatchObject({
+ status: 'install-failed',
+ availableVersion: '1.3.0',
+ error: "Version 1.3.0 didn't install: Switch Console restarted on version 1.2.3.",
+ });
+ expect(restartedEvents.emit).toHaveBeenCalledWith(failedEvent, {
+ version: '1.3.0',
+ message: expect.stringContaining('1.3.0'),
+ foundAtLaunch: true,
+ });
+ expect(restarted.getState().installFailedAtLaunch).toBe(true);
+ // "Download manually" quits the app, and that quit must not start a second
+ // install. The updater is set up after the failure is found.
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+
+ // The check that follows finds the same release. Offering it again would
+ // only fail the same way, so the failure stays on screen.
+ h.checkForUpdatesAndNotify.mockImplementation(async () => {
+ h.handlers.get('checking-for-update')?.();
+ h.handlers.get('update-available')?.({ version: '1.3.0' });
+ return { isUpdateAvailable: true, updateInfo: { version: '1.3.0' } };
+ });
+ // A check that fails in between does not replace the reason.
+ h.checkForUpdatesAndNotify.mockImplementationOnce(async () => {
+ h.handlers.get('error')?.(new Error('getaddrinfo ENOTFOUND github.com'));
+ throw new Error('getaddrinfo ENOTFOUND github.com');
+ });
+ await expect(restarted.checkForUpdates('scheduled')).rejects.toThrow('ENOTFOUND');
+ expect(restarted.getState()).toMatchObject({ status: 'install-failed' });
+ vi.mocked(restartedEvents.emit).mockClear();
+ await restarted.checkForUpdates('scheduled');
+ // Shown again, but no longer news: no second toast an hour later.
+ expect(restartedEvents.emit).toHaveBeenCalledWith(failedEvent, {
+ version: '1.3.0',
+ message: expect.stringContaining('1.3.0'),
+ foundAtLaunch: false,
+ });
+ expect(restarted.getState().installFailedAtLaunch).toBe(false);
+ expect(restarted.getState()).toMatchObject({
+ status: 'install-failed',
+ error: "Version 1.3.0 didn't install: Switch Console restarted on version 1.2.3.",
+ });
+
+ // A newer release is a new chance, and is offered as usual.
+ h.checkForUpdatesAndNotify.mockImplementation(async () => {
+ h.handlers.get('update-available')?.({ version: '1.4.0' });
+ return { isUpdateAvailable: true, updateInfo: { version: '1.4.0' } };
+ });
+ await restarted.checkForUpdates('scheduled');
+ expect(restarted.getState()).toMatchObject({ status: 'available', availableVersion: '1.4.0' });
+ restarted.dispose();
+ h.checkForUpdatesAndNotify.mockReset();
+ });
+
+ it('shows no failure for a marker from a build that recorded no version', async () => {
+ h.pending.legacy = true;
+ const { updateService: restarted } = await import('./update-service');
+ const { events: restartedEvents } = await import('@main/lib/events');
+ vi.mocked(restartedEvents.emit).mockClear();
+ await restarted.initialize();
+ restarted.dispose();
+
+ expect(restarted.getState()).toMatchObject({ status: 'idle' });
+ expect(restarted.getState().installFailedAtLaunch).toBeUndefined();
+ expect(restartedEvents.emit).not.toHaveBeenCalled();
+ });
+
+ it('counts a launch on a version other than the one that handed over as a success', async () => {
+ // The handover to 1.3.0 did not take, and the user then installed 1.2.3 by
+ // hand. An install happened, so there is nothing to show.
+ h.pending.target = '1.3.0';
+ h.pending.from = '1.2.0';
+ const { updateService: restarted } = await import('./update-service');
+ await restarted.initialize();
+ restarted.dispose();
+
+ expect(installEvents()).toEqual([['update_install_started', { outcome: 'success' }]]);
+ expect(restarted.getState()).toMatchObject({ status: 'idle' });
});
it('reports nothing on an ordinary launch', async () => {
- h.pending.handover = false;
+ h.pending.target = null;
const { updateService: restarted } = await import('./update-service');
await restarted.initialize();
@@ -260,6 +627,70 @@ describe('the launch after an install', () => {
});
});
+describe('a failure that is still on screen', () => {
+ async function launchAfterSilentFailure() {
+ vi.resetModules();
+ h.pending.target = '1.3.0';
+ h.pending.from = '1.2.3';
+ const { updateService: restarted } = await import('./update-service');
+ await restarted.initialize();
+ restarted.dispose();
+ h.checkForUpdatesAndNotify.mockImplementationOnce(async () => {
+ h.handlers.get('error')?.(new Error('getaddrinfo ENOTFOUND github.com'));
+ throw new Error('getaddrinfo ENOTFOUND github.com');
+ });
+ await expect(restarted.checkForUpdates('scheduled')).rejects.toThrow('ENOTFOUND');
+ restarted.dispose();
+ return restarted;
+ }
+
+ afterEach(() => {
+ h.checkForUpdatesAndNotify.mockReset();
+ });
+
+ it('stays on screen while a check runs', async () => {
+ vi.resetModules();
+ h.pending.target = '1.3.0';
+ h.pending.from = '1.2.3';
+ const { updateService: restarted } = await import('./update-service');
+ const { events: restartedEvents } = await import('@main/lib/events');
+ const { updateCheckingEvent: checkingEvent } = await import('@shared/events/updateEvents');
+ await restarted.initialize();
+ restarted.dispose();
+ let duringCheck: string | undefined;
+ h.checkForUpdatesAndNotify.mockImplementationOnce(async () => {
+ h.handlers.get('checking-for-update')?.();
+ duringCheck = restarted.getState().status;
+ return { isUpdateAvailable: false };
+ });
+
+ await restarted.checkForUpdates('user');
+ restarted.dispose();
+
+ expect(duringCheck).toBe('install-failed');
+ expect(restartedEvents.emit).not.toHaveBeenCalledWith(checkingEvent, undefined);
+ });
+
+ it('is not replaced by a check that fails', async () => {
+ const restarted = await launchAfterSilentFailure();
+
+ // The renderer shows "Try again" for `error`, which downloads the version
+ // that already failed to install.
+ expect(restarted.getState()).toMatchObject({
+ status: 'install-failed',
+ error: "Version 1.3.0 didn't install: Switch Console restarted on version 1.2.3.",
+ });
+ });
+
+ it('is not downloaded again after a check fails', async () => {
+ const restarted = await launchAfterSilentFailure();
+ h.downloadUpdate.mockClear();
+
+ await expect(restarted.downloadUpdate()).rejects.toThrow();
+ expect(h.downloadUpdate).not.toHaveBeenCalled();
+ });
+});
+
describe('a canary build', () => {
afterEach(() => {
vi.doUnmock('@shared/app-identity');
@@ -321,6 +752,38 @@ describe('the dev harness', () => {
await vi.advanceTimersByTimeAsync(5_000);
expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+
+ // The harness's version has no release, so its release notes are the
+ // newest real release on the channel.
+ await expect(harnessed.releaseNotesUrl()).resolves.toBe(
+ 'https://github.com/sandbox-quantum/switch/releases/latest'
+ );
+ harnessed.dispose();
+ });
+
+ it('shows a simulated installer failure as install-failed', async () => {
+ vi.resetModules();
+ vi.stubEnv('DEV', true);
+ vi.stubEnv('SWITCHDASH_FAKE_UPDATE', 'install-error');
+ vi.stubEnv('SWITCHDASH_FAKE_UPDATE_MS', '100');
+
+ const { updateService: harnessed } = await import('./update-service');
+ await harnessed.initialize();
+
+ await vi.advanceTimersByTimeAsync(3_000);
+ const download = harnessed.downloadUpdate();
+ await vi.advanceTimersByTimeAsync(3_000);
+ await download;
+ expect(harnessed.getState()).toMatchObject({ status: 'downloaded' });
+
+ h.trackEvent.mockClear();
+ harnessed.quitAndInstall();
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ expect(harnessed.getState()).toMatchObject({ status: 'install-failed' });
+ expect(harnessed.getState().error).toContain('simulated installer failure');
+ expect(installEvents()).toEqual([['update_install_started', { outcome: 'failure' }]]);
+ expect(h.quitAndInstall).not.toHaveBeenCalled();
harnessed.dispose();
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/update-service.ts b/console/apps/switch-console-desktop/src/main/core/updates/update-service.ts
index e80873a9b..e5f7bbb0f 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/update-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/update-service.ts
@@ -12,6 +12,7 @@ import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
import {
IS_CANARY,
+ PRODUCT_NAME,
RELEASE_REPO_NAME,
RELEASE_REPO_OWNER,
UPDATE_CHANNEL,
@@ -22,11 +23,12 @@ import {
updateDownloadedEvent,
updateDownloadingEvent,
updateErrorEvent,
+ updateInstallFailedEvent,
updateInstallingEvent,
updateNotAvailableEvent,
updateProgressEvent,
} from '@shared/events/updateEvents';
-import { switchConsoleReleaseApiUrl } from '@shared/urls';
+import { switchConsoleReleaseApiUrl, switchConsoleReleaseUrl } from '@shared/urls';
import { resolveCanaryFeedUrl } from './canary-feed';
import {
FAKE_UPDATE_VERSION_ENV_VAR,
@@ -36,8 +38,10 @@ import {
readFakeDownloadDuration,
readFakeUpdateScenario,
} from './dev-harness';
-import { pendingInstall } from './pending-install';
-import { formatUpdaterError, sanitizeUpdaterLogArgs } from './utils';
+import { isTranslocated } from './install-preflight';
+import { manualDownloadUrl } from './manual-download';
+import { type PendingHandover, pendingInstall } from './pending-install';
+import { formatUpdaterError, sanitizeUpdaterLogArgs, updaterErrorCode } from './utils';
const { autoUpdater } = _electronUpdater;
@@ -51,8 +55,25 @@ const FAKE_STARTUP_DELAY_MS = 1_500;
/** Dev builds cannot restart into a new binary, so the fake install unwinds. */
const FAKE_INSTALL_ROLLBACK_MS = 3_000;
+/** Why an install did not happen, as logged with `event: 'update.install'`. */
+type InstallFailureCode =
+ | 'installer_error'
+ | 'restart_timeout'
+ | 'handover_threw'
+ | 'relaunched_unchanged'
+ | 'marker_write_failed'
+ | 'blocked_translocated';
+
export interface UpdateState {
- status: 'idle' | 'checking' | 'available' | 'downloading' | 'downloaded' | 'installing' | 'error';
+ status:
+ | 'idle'
+ | 'checking'
+ | 'available'
+ | 'downloading'
+ | 'downloaded'
+ | 'installing'
+ | 'install-failed'
+ | 'error';
lastCheck?: Date;
nextCheck?: Date;
currentVersion: string;
@@ -65,6 +86,8 @@ export interface UpdateState {
total: number;
};
error?: string;
+ /** With `install-failed`: the failure was found at launch, with no one watching. */
+ installFailedAtLaunch?: boolean;
rollbackVersion?: string;
releaseNotes?: string;
}
@@ -76,7 +99,14 @@ class UpdateService implements IInitializable, IDisposable {
private initialized = false;
private active = false;
private installRequested = false;
+ private installingVersion?: string;
+ /**
+ * The install that last failed. Offering the same version again would only
+ * fail the same way, so a check that finds it again shows the failure instead.
+ */
+ private installFailure?: { version: string; message: string };
private installRestartGuardTimer?: NodeJS.Timeout;
+ private installHandoverTimer?: NodeJS.Timeout;
private fake?: FakeUpdateDriver;
constructor() {
@@ -95,9 +125,8 @@ class UpdateService implements IInitializable, IDisposable {
// Before the dev-harness branch and before `active`: the install this
// reports belonged to the run that ended, and whether this one can check
// for updates has no bearing on it.
- if (await pendingInstall.take()) {
- trackEvent('update_install_started', { outcome: 'success' });
- }
+ const handover = await pendingInstall.take();
+ if (handover) this.reportHandover(handover);
if (import.meta.env.DEV) {
this.setupDevHarness();
@@ -144,9 +173,113 @@ class UpdateService implements IInitializable, IDisposable {
this.scheduleNextCheck(FAKE_STARTUP_DELAY_MS);
}
+ /**
+ * Report the install the previous run handed over. The app going down for the
+ * installer is not proof it came back on the new version: on macOS a
+ * Squirrel.Mac failure relaunches the old bundle without an error. Only a
+ * launch on the version that handed over is a failure. Any other version
+ * means an install happened, by the updater or by hand.
+ */
+ private reportHandover({ targetVersion, fromVersion }: PendingHandover): void {
+ const current = this.updateState.currentVersion;
+ if (targetVersion === null || current !== fromVersion) {
+ trackEvent('update_install_started', { outcome: 'success' });
+ return;
+ }
+ trackEvent('update_install_started', { outcome: 'failure' });
+ this.failInstall(
+ targetVersion,
+ 'relaunched_unchanged',
+ `Version ${targetVersion} didn't install: ${PRODUCT_NAME} restarted on version ${current}.`,
+ true
+ );
+ }
+
+ /**
+ * Record an install that did not happen, and show it until it is resolved.
+ * `foundAtLaunch` says nobody was watching it fail: the previous run handed
+ * over and this one came back on the old version. Only then does the
+ * renderer raise a toast, because otherwise the panel or the Settings card the
+ * user clicked already shows the failure.
+ */
+ private failInstall(
+ version: string,
+ errorCode: InstallFailureCode,
+ message: string,
+ foundAtLaunch: boolean
+ ): void {
+ log.error('Update did not install', {
+ event: 'update.install',
+ errorCode,
+ fromVersion: this.updateState.currentVersion,
+ toVersion: version,
+ message,
+ });
+ this.installFailure = { version, message };
+ this.setInstallOnQuit(false);
+ this.presentInstallFailure(this.installFailure, foundAtLaunch);
+ }
+
+ /**
+ * Whether the updater installs a downloaded update when the app quits. It is
+ * off after a failed install, because "Download manually" quits the app and a
+ * second install on that quit could fail without a word. Windows reads the
+ * flag at quit. On macOS, Squirrel.Mac can already hold a staged update, so
+ * the flag does not stop every install there. It comes back on only when a
+ * download replaces the failed installer, because until then a quit runs the
+ * failed installer. The updater reads the flag after it sends that event.
+ */
+ private setInstallOnQuit(on: boolean): void {
+ if (!this.fake) autoUpdater.autoInstallOnAppQuit = on;
+ }
+
+ private presentInstallFailure(
+ { version, message }: { version: string; message: string },
+ foundAtLaunch: boolean
+ ): void {
+ this.updateState.status = 'install-failed';
+ this.updateState.availableVersion = version;
+ this.updateState.error = message;
+ this.updateState.installFailedAtLaunch = foundAtLaunch;
+ events.emit(updateInstallFailedEvent, { version, message, foundAtLaunch });
+ }
+
+ /**
+ * Whether macOS runs this copy from a translocated path, where Squirrel.Mac
+ * cannot replace it. Checked before the download, so the user does not wait
+ * for an update that cannot install.
+ */
+ private isTranslocated(): boolean {
+ return !this.fake && process.platform === 'darwin' && isTranslocated(process.execPath);
+ }
+
+ /**
+ * End the install attempt in progress without the app having gone down. One
+ * attempt is one event: the app goes down for the installer, or it is still
+ * here afterwards, and the latch keeps a handover that later unwinds from
+ * being counted in both directions.
+ */
+ private abandonInstallAttempt(): void {
+ if (this.installRestartGuardTimer) {
+ clearTimeout(this.installRestartGuardTimer);
+ this.installRestartGuardTimer = undefined;
+ }
+ if (this.installHandoverTimer) {
+ clearTimeout(this.installHandoverTimer);
+ this.installHandoverTimer = undefined;
+ }
+ void pendingInstall.clear();
+ trackEvent('update_install_started', { outcome: 'failure' });
+ this.installRequested = false;
+ // A scheduled check skipped during the install did not re-arm the timer.
+ this.scheduleNextCheck();
+ }
+
private setupAutoUpdater(): void {
autoUpdater.autoDownload = false;
- autoUpdater.autoInstallOnAppQuit = true;
+ // Off when the launch found a failed install, for the same reason as
+ // `setInstallOnQuit`.
+ autoUpdater.autoInstallOnAppQuit = !this.installFailure;
autoUpdater.autoRunAppAfterInstall = true;
autoUpdater.allowPrerelease = ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = ALLOW_DOWNGRADE;
@@ -166,12 +299,22 @@ class UpdateService implements IInitializable, IDisposable {
*/
private readonly signals: UpdateSignals = {
checking: () => {
- this.updateState.status = 'checking';
this.updateState.lastCheck = new Date();
+ // A failed install stays on screen while the check runs. The result
+ // shows it again, or replaces it with a newer version or "up to date".
+ if (this.installFailure) return;
+ this.updateState.status = 'checking';
events.emit(updateCheckingEvent, undefined);
},
available: (info: UpdateInfo) => {
+ if (this.installFailure && info.version === this.installFailure.version) {
+ this.updateState.updateInfo = info;
+ this.presentInstallFailure(this.installFailure, false);
+ return;
+ }
+ // A newer version is a new chance.
+ this.installFailure = undefined;
this.updateState.status = 'available';
this.updateState.availableVersion = info.version;
this.updateState.updateInfo = info;
@@ -179,16 +322,37 @@ class UpdateService implements IInitializable, IDisposable {
},
notAvailable: () => {
+ this.installFailure = undefined;
this.updateState.status = 'idle';
events.emit(updateNotAvailableEvent, undefined);
},
failed: (err: unknown) => {
const errorMessage = formatUpdaterError(err);
- log.error('Auto-updater error:', errorMessage);
+ log.error('Auto-updater error', {
+ event: 'update.error',
+ errorCode: updaterErrorCode(err),
+ message: errorMessage,
+ });
+
+ // Squirrel.Mac reports a bundle it cannot replace here, after the
+ // handover and before the app would have quit.
+ if (this.installRequested && this.installingVersion) {
+ this.abandonInstallAttempt();
+ this.failInstall(
+ this.installingVersion,
+ 'installer_error',
+ `Version ${this.installingVersion} didn't install: ${errorMessage}`,
+ false
+ );
+ return;
+ }
- if (this.updateState.status === 'installing') {
- log.warn('Ignoring auto-updater error while install is in progress');
+ // A failed check does not hide a failed install. Its "Try again" would
+ // download the version that already failed.
+ const failure = this.installFailure;
+ if (failure && failure.version === this.updateState.availableVersion) {
+ this.presentInstallFailure(failure, false);
return;
}
@@ -213,6 +377,7 @@ class UpdateService implements IInitializable, IDisposable {
},
downloaded: (version: string) => {
+ this.setInstallOnQuit(true);
this.updateState.status = 'downloaded';
this.updateState.rollbackVersion = this.updateState.currentVersion;
events.emit(updateDownloadedEvent, { version });
@@ -262,7 +427,8 @@ class UpdateService implements IInitializable, IDisposable {
* of the check that actually ran — the alternative is counting one check twice.
*/
async checkForUpdates(trigger: TelemetryUpdateTrigger = 'user'): Promise<UpdateInfo | null> {
- if (!this.active) return null;
+ // During an install, an error from a check would read as an installer error.
+ if (!this.active || this.installRequested) return null;
if (this.currentCheckPromise) return this.currentCheckPromise;
this.currentCheckPromise = this._performCheck()
@@ -334,12 +500,27 @@ class UpdateService implements IInitializable, IDisposable {
throw new Error(`Cannot download: status is "${this.updateState.status}", not "available"`);
}
- if (!this.updateState.availableVersion) {
+ const version = this.updateState.availableVersion;
+ if (!version) {
throw new Error('No version information available for download');
}
+ if (this.installFailure?.version === version) {
+ throw new Error(`Cannot download: version ${version} already failed to install`);
+ }
+
+ if (this.isTranslocated()) {
+ this.failInstall(
+ version,
+ 'blocked_translocated',
+ `${PRODUCT_NAME} can't install version ${version} while macOS runs it from a ` +
+ 'temporary location. Move it to your Applications folder and open it from there.',
+ false
+ );
+ return;
+ }
this.updateState.status = 'downloading';
- events.emit(updateDownloadingEvent, { version: this.updateState.availableVersion });
+ events.emit(updateDownloadingEvent, { version });
trackEvent('update_download_started', {});
try {
@@ -349,7 +530,11 @@ class UpdateService implements IInitializable, IDisposable {
} catch (error: unknown) {
trackEvent('update_downloaded', { outcome: 'failure' });
const errorMessage = formatUpdaterError(error);
- log.error('Update download failed:', errorMessage, error);
+ log.error('Update download failed', {
+ event: 'update.download',
+ errorCode: updaterErrorCode(error),
+ message: errorMessage,
+ });
const version = this.updateState.availableVersion;
const info = this.updateState.updateInfo;
@@ -377,44 +562,37 @@ class UpdateService implements IInitializable, IDisposable {
);
}
+ const version = this.updateState.availableVersion;
+ if (!version) throw new Error('Cannot install update: no version was downloaded');
+
this.installRequested = true;
+ this.installingVersion = version;
this.updateState.status = 'installing';
events.emit(updateInstallingEvent, undefined);
log.info('Installing update', {
fromVersion: this.updateState.currentVersion,
- toVersion: this.updateState.availableVersion,
+ toVersion: version,
});
- // One attempt, one event. Only one of the two outcomes can happen — the app
- // goes down for the installer, or it is still here afterwards — and the
- // latch is what keeps a handover that later unwinds from being counted in
- // both directions.
- const rollback = (reason: string) => {
- clearGuard();
- void pendingInstall.clear();
- trackEvent('update_install_started', { outcome: 'failure' });
- this.installRequested = false;
- this.updateState.status = 'downloaded';
- if (this.updateState.availableVersion) {
- events.emit(updateDownloadedEvent, { version: this.updateState.availableVersion });
- }
- log.error(reason);
- };
-
- const clearGuard = () => {
- if (this.installRestartGuardTimer) {
- clearTimeout(this.installRestartGuardTimer);
- this.installRestartGuardTimer = undefined;
- }
- };
-
if (this.fake) {
// A dev build has no new binary to restart into. Unwind quickly so the
// "ready to install" state is reachable again instead of stranding the UI
// on "installing" until the two-minute guard fires.
this.installRestartGuardTimer = setTimeout(() => {
- rollback('[dev] Simulated install complete — no restart happens under the update harness');
+ this.abandonInstallAttempt();
+ if (this.fake?.scenario === 'install-error') {
+ this.failInstall(
+ version,
+ 'installer_error',
+ `Version ${version} didn't install: simulated installer failure`,
+ false
+ );
+ return;
+ }
+ this.updateState.status = 'downloaded';
+ events.emit(updateDownloadedEvent, { version });
+ log.info('[dev] Simulated install complete — no restart happens under the update harness');
}, FAKE_INSTALL_ROLLBACK_MS);
return;
}
@@ -425,21 +603,53 @@ class UpdateService implements IInitializable, IDisposable {
// handler that calls `app.exit`, and even first in the queue it would be
// racing a consent read and an HTTP post against the process ending. A
// record that survives the restart is the only version of this that is not
- // a guess, and the marker's absence is what `rollback` uses to say the
- // handover did not take.
- void pendingInstall.set();
+ // a guess, and the marker's absence is what an abandoned attempt uses to say
+ // the handover did not take. The handover waits for the write: without the
+ // marker, a failed install would go unreported.
+ const fromVersion = this.updateState.currentVersion;
+ pendingInstall.set(version, fromVersion).then(
+ () => {
+ if (!this.installRequested) return;
+ this.installHandoverTimer = setTimeout(() => this.handOver(version), 250);
+ },
+ (error: unknown) => {
+ if (!this.installRequested) return;
+ log.error('Could not write the handover marker', { error: String(error) });
+ this.abandonInstallAttempt();
+ this.failInstall(
+ version,
+ 'marker_write_failed',
+ `Version ${version} didn't install: ${PRODUCT_NAME} could not save the update ` +
+ 'before the restart.',
+ false
+ );
+ }
+ );
this.installRestartGuardTimer = setTimeout(() => {
- rollback('quitAndInstall timed out before app quit; allowing retry');
+ this.abandonInstallAttempt();
+ this.failInstall(
+ version,
+ 'restart_timeout',
+ `Version ${version} didn't install: ${PRODUCT_NAME} was still running two minutes after the restart.`,
+ false
+ );
}, INSTALL_RESTART_GUARD_TIMEOUT_MS);
+ }
- setTimeout(() => {
- try {
- autoUpdater.quitAndInstall(false, true);
- } catch (error) {
- rollback(`quitAndInstall threw: ${formatUpdaterError(error)}`);
- }
- }, 250);
+ private handOver(version: string): void {
+ this.installHandoverTimer = undefined;
+ try {
+ autoUpdater.quitAndInstall(false, true);
+ } catch (error) {
+ this.abandonInstallAttempt();
+ this.failInstall(
+ version,
+ 'handover_threw',
+ `Version ${version} didn't install: ${formatUpdaterError(error)}`,
+ false
+ );
+ }
}
async fetchReleaseNotes(): Promise<string | null> {
@@ -488,6 +698,23 @@ class UpdateService implements IInitializable, IDisposable {
}
}
+ /**
+ * The release page of the update being offered. The dev harness makes its
+ * versions up, so a page for one does not exist; under it this opens the
+ * newest real release on the channel instead, and says so.
+ */
+ async releaseNotesUrl(): Promise<string> {
+ const version = this.updateState.availableVersion;
+ if (this.fake) {
+ log.warn(
+ `[dev] Update harness version ${version ?? 'unknown'} has no release page; ` +
+ 'opening the newest real release instead'
+ );
+ return manualDownloadUrl(IS_CANARY);
+ }
+ return switchConsoleReleaseUrl(version);
+ }
+
getState(): UpdateState {
return { ...this.updateState };
}
@@ -502,6 +729,10 @@ class UpdateService implements IInitializable, IDisposable {
clearTimeout(this.installRestartGuardTimer);
this.installRestartGuardTimer = undefined;
}
+ if (this.installHandoverTimer) {
+ clearTimeout(this.installHandoverTimer);
+ this.installHandoverTimer = undefined;
+ }
}
}
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/utils.test.ts b/console/apps/switch-console-desktop/src/main/core/updates/utils.test.ts
new file mode 100644
index 000000000..53705b287
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/updates/utils.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it } from 'vitest';
+import { formatUpdaterError, sanitizeUpdaterLogArgs, updaterErrorCode } from './utils';
+
+/** The shape builder-util-runtime's `newError` gives electron-updater's own failures. */
+function updaterError(message: string, code: string): Error {
+ return Object.assign(new Error(message), { code });
+}
+
+/** The shape builder-util-runtime's `HttpError` gives a failed request. */
+function httpError(statusCode: number, description: string | null): Error {
+ return Object.assign(new Error(`HTTP error: ${statusCode}`), {
+ statusCode,
+ description,
+ code: `HTTP_ERROR_${statusCode}`,
+ });
+}
+
+describe('formatUpdaterError', () => {
+ it.each([
+ ['ERR_UPDATER_NO_PUBLISHED_VERSIONS', 'No published versions on GitHub'],
+ ['ERR_UPDATER_CHANNEL_FILE_NOT_FOUND', 'Cannot find latest-mac.yml in the latest release'],
+ ])('shows what the updater said for %s, not an HTTP status', (code, message) => {
+ const text = formatUpdaterError(updaterError(message, code));
+
+ expect(text).toBe(message);
+ expect(text).not.toContain('HTTP');
+ });
+
+ it('keeps the stack trace and feed XML of an unreadable feed out of the text', () => {
+ const error = updaterError(
+ 'Cannot parse releases feed: TypeError: x is null\n at parse (feed.js:1:1),\nXML:\n<?xml version="1.0"?><feed></feed>',
+ 'ERR_UPDATER_INVALID_RELEASE_FEED'
+ );
+
+ expect(formatUpdaterError(error)).toBe('Cannot parse releases feed: TypeError: x is null');
+ });
+
+ it('says HTTP for a numeric status code', () => {
+ expect(formatUpdaterError(httpError(503, 'Service Unavailable'))).toBe(
+ 'Update request failed with HTTP 503: Service Unavailable'
+ );
+ expect(formatUpdaterError(httpError(404, null))).toBe('Update request failed with HTTP 404');
+ });
+
+ it('shows the message for a network error code', () => {
+ const error = Object.assign(new Error('getaddrinfo ENOTFOUND github.com'), {
+ code: 'ENOTFOUND',
+ });
+
+ expect(formatUpdaterError(error)).toBe('getaddrinfo ENOTFOUND github.com');
+ });
+
+ it('does not call a non-numeric status an HTTP status', () => {
+ const error = Object.assign(new Error('the request was refused'), {
+ statusCode: 'nope',
+ });
+
+ expect(formatUpdaterError(error)).toBe('the request was refused');
+ });
+
+ it('describes a value that is not an error', () => {
+ expect(formatUpdaterError('plain text')).toBe('plain text');
+ expect(formatUpdaterError(undefined)).toBe('Unknown update error');
+ });
+});
+
+describe('formatUpdaterError at the edges', () => {
+ it('prefers the updater message to a status code on the same error', () => {
+ const error = Object.assign(updaterError('No published versions on GitHub', 'ERR_UPDATER_X'), {
+ statusCode: 404,
+ });
+
+ expect(formatUpdaterError(error)).toBe('No published versions on GitHub');
+ });
+
+ it('says it does not know when an updater error has no message', () => {
+ expect(formatUpdaterError(updaterError('', 'ERR_UPDATER_NO_PUBLISHED_VERSIONS'))).toBe(
+ 'Unknown update error'
+ );
+ });
+
+ it('drops the carriage return of a Windows line ending', () => {
+ const error = updaterError('Cannot find channel file\r\n at x (y.js:1:1)', 'ERR_UPDATER_X');
+
+ expect(formatUpdaterError(error)).toBe('Cannot find channel file');
+ });
+
+ it('truncates a long first line', () => {
+ const text = formatUpdaterError(updaterError('a'.repeat(300), 'ERR_UPDATER_X'));
+
+ expect(text).toBe(`${'a'.repeat(240)}…`);
+ });
+
+ it('keeps an HTML error page out of the status text', () => {
+ const error = Object.assign(new Error('HTTP error: 502'), {
+ statusCode: 502,
+ statusMessage: 'Bad Gateway <!DOCTYPE html><html><body>nginx</body></html>',
+ });
+
+ expect(formatUpdaterError(error)).toBe('Update request failed with HTTP 502: Bad Gateway');
+ });
+
+ it('prefers the status message to the description', () => {
+ const error = Object.assign(httpError(500, 'from description'), {
+ statusMessage: 'Internal Server Error',
+ });
+
+ expect(formatUpdaterError(error)).toBe(
+ 'Update request failed with HTTP 500: Internal Server Error'
+ );
+ });
+
+ it('does not take a numeric code for an HTTP status', () => {
+ const error = Object.assign(new Error('socket hang up'), { code: 404 });
+
+ expect(formatUpdaterError(error)).toBe('socket hang up');
+ expect(updaterErrorCode(error)).toBeUndefined();
+ });
+
+ it('skips an empty first line to find the sentence', () => {
+ const error = updaterError('\nCannot find channel file\n at x (y.js:1:1)', 'ERR_UPDATER_X');
+
+ expect(formatUpdaterError(error)).toBe('Cannot find channel file');
+ });
+
+ it('describes null like undefined', () => {
+ expect(formatUpdaterError(null)).toBe('Unknown update error');
+ });
+});
+
+describe('sanitizeUpdaterLogArgs', () => {
+ it('logs only the first line of an updater error', () => {
+ const error = updaterError(
+ 'Cannot parse feed\nXML:\n<feed/>',
+ 'ERR_UPDATER_INVALID_RELEASE_FEED'
+ );
+
+ expect(sanitizeUpdaterLogArgs(['Error:', error, 42])).toEqual([
+ 'Error:',
+ 'Cannot parse feed',
+ 42,
+ ]);
+ });
+});
+
+describe('updaterErrorCode', () => {
+ it('returns the code to log, when there is one', () => {
+ expect(updaterErrorCode(updaterError('x', 'ERR_UPDATER_NO_PUBLISHED_VERSIONS'))).toBe(
+ 'ERR_UPDATER_NO_PUBLISHED_VERSIONS'
+ );
+ expect(updaterErrorCode(new Error('x'))).toBeUndefined();
+ expect(updaterErrorCode(null)).toBeUndefined();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/updates/utils.ts b/console/apps/switch-console-desktop/src/main/core/updates/utils.ts
index bbcb16db8..574e2f6a1 100644
--- a/console/apps/switch-console-desktop/src/main/core/updates/utils.ts
+++ b/console/apps/switch-console-desktop/src/main/core/updates/utils.ts
@@ -8,25 +8,44 @@ function stripMarkupAndTruncate(raw: string): string {
return collapsed.length > 240 ? `${collapsed.slice(0, 240)}…` : collapsed;
}
+type UpdaterError = Error & {
+ statusCode?: unknown;
+ code?: unknown;
+ statusMessage?: string;
+ description?: string;
+};
+
+/**
+ * electron-updater's own failures (a feed it cannot parse, a release with no
+ * channel file) carry an `ERR_UPDATER_*` code and say what went wrong in the
+ * message. Their first line with text is the sentence; what follows is a stack trace or
+ * the feed XML the updater could not read.
+ */
+function isUpdaterErrorCode(code: unknown): code is string {
+ return typeof code === 'string' && code.startsWith('ERR_UPDATER_');
+}
+
+/** The error code to log next to a message, so failures can be counted. */
+export function updaterErrorCode(error: unknown): string | undefined {
+ const code = (error as UpdaterError | null)?.code;
+ return typeof code === 'string' ? code : undefined;
+}
+
export function formatUpdaterError(error: unknown): string {
- const err = error as Error & {
- statusCode?: number;
- code?: string;
- status?: number;
- statusMessage?: string;
- description?: string;
- };
- const status = err.statusCode || err.status;
- const statusText = err.statusMessage || err.description;
- if (status) {
- const base = `Update request failed with HTTP ${status}`;
+ const err = (error ?? {}) as UpdaterError;
+ const message = error instanceof Error ? error.message : String(error ?? 'Unknown update error');
+
+ if (isUpdaterErrorCode(err.code)) {
+ return stripMarkupAndTruncate(message.split('\n').find((line) => line.trim()) ?? '');
+ }
+
+ if (typeof err.statusCode === 'number') {
+ const base = `Update request failed with HTTP ${err.statusCode}`;
+ const statusText = err.statusMessage || err.description;
return statusText ? `${base}: ${stripMarkupAndTruncate(String(statusText))}` : base;
}
- const message = error instanceof Error ? error.message : String(error ?? 'Unknown update error');
- // electron-updater's own failures carry an ERR_UPDATER_* code, not an HTTP status.
- return err.code
- ? `${stripMarkupAndTruncate(message)} (${err.code})`
- : stripMarkupAndTruncate(message);
+
+ return stripMarkupAndTruncate(message);
}
export function sanitizeUpdaterLogArgs(args: unknown[]) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/UpdateCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/UpdateCard.tsx
index 0edfa6016..c66f7ef86 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/components/UpdateCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/UpdateCard.tsx
@@ -34,6 +34,7 @@ const ACTION_ICONS: Record<UpdateActionKind, React.ComponentType<{ className?: s
restart: RefreshCw,
retry: RefreshCw,
check: RefreshCw,
+ manual: ExternalLink,
};
export const UpdateCard = observer(function UpdateCard(): React.JSX.Element {
@@ -60,6 +61,9 @@ export const UpdateCard = observer(function UpdateCard(): React.JSX.Element {
case 'check':
void update.check();
break;
+ case 'manual':
+ void update.openLatest();
+ break;
default:
break;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx
index 893453860..051164e69 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/update-section.tsx
@@ -51,6 +51,7 @@ const ACTION_ICONS: Record<UpdateActionKind, React.ComponentType<{ className?: s
restart: RefreshCw,
retry: RefreshCw,
check: RefreshCw,
+ manual: ExternalLink,
};
export const UpdateSection = observer(function UpdateSection() {
@@ -77,6 +78,9 @@ export const UpdateSection = observer(function UpdateSection() {
case 'check':
void update.check();
break;
+ case 'manual':
+ void update.openLatest();
+ break;
default:
break;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/update-toast-action-label.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/update-toast-action-label.tsx
index a9396bb00..753e5e4c1 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/update-toast-action-label.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/update-toast-action-label.tsx
@@ -1,9 +1,10 @@
import { ArrowUpRight } from 'lucide-react';
-export function createUpdateToastActionLabel() {
+/** The action label of an update toast: the text, and an arrow that nudges on hover. */
+export function createUpdateToastActionLabel(text: string) {
return (
<span className="flex items-center gap-1.5">
- Update
+ {text}
<ArrowUpRight className="size-3.5 transition-transform duration-200 group-hover/action:translate-x-px group-hover/action:-translate-y-px" />
</span>
);
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.test.ts
index 10951168a..571f99f74 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.test.ts
@@ -1,20 +1,28 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { menuCheckForUpdatesChannel } from '@shared/events/appEvents';
import {
updateAvailableEvent,
+ updateCheckingEvent,
updateDownloadedEvent,
updateDownloadingEvent,
+ updateInstallFailedEvent,
updateInstallingEvent,
updateNotAvailableEvent,
} from '@shared/events/updateEvents';
const handlers = vi.hoisted(() => new Map<unknown, (payload?: unknown) => void>());
const toast = vi.hoisted(() => Object.assign(vi.fn(), { dismiss: vi.fn(), error: vi.fn() }));
+const rpcUpdate = vi.hoisted(() => ({
+ getState: vi.fn(),
+ check: vi.fn(),
+ openLatest: vi.fn(),
+ openReleaseNotes: vi.fn(),
+}));
vi.mock('sonner', () => ({ toast }));
vi.mock('@renderer/lib/components/update-toast-action-label', () => ({
- createUpdateToastActionLabel: () => 'Update',
+ createUpdateToastActionLabel: (text: string) => text,
}));
-vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl: vi.fn() }));
vi.mock('@renderer/lib/stores/app-state', () => ({
appState: { navigation: { navigate: vi.fn() } },
}));
@@ -26,10 +34,7 @@ vi.mock('@renderer/lib/ipc', () => ({
},
rpc: {
app: { getAppVersion: () => Promise.resolve('1.0.0') },
- update: {
- getState: () => Promise.resolve({ success: false }),
- check: () => Promise.resolve(null),
- },
+ update: rpcUpdate,
},
}));
@@ -41,7 +46,19 @@ vi.stubGlobal('localStorage', {
clear: () => stored.clear(),
});
-const { UPDATE_AVAILABLE_TOAST_ID, UpdateStore } = await import('./update-store');
+const {
+ UPDATE_AVAILABLE_TOAST_ID,
+ UPDATE_INSTALL_FAILED_TOAST_ID,
+ UpdateStore,
+ mainStateToRendererState,
+} = await import('./update-store');
+const { appState } = await import('@renderer/lib/stores/app-state');
+
+beforeEach(() => {
+ rpcUpdate.getState.mockResolvedValue({ success: false });
+ rpcUpdate.check.mockResolvedValue(null);
+ rpcUpdate.openLatest.mockResolvedValue({ success: true });
+});
function emit(event: unknown, payload?: unknown): void {
const handler = handlers.get(event);
@@ -49,6 +66,15 @@ function emit(event: unknown, payload?: unknown): void {
handler(payload);
}
+/** A started store, past the check that every start makes. */
+async function startedStore(): Promise<InstanceType<typeof UpdateStore>> {
+ const store = new UpdateStore();
+ store.start();
+ await vi.waitFor(() => expect(rpcUpdate.check).toHaveBeenCalledWith('startup'));
+ rpcUpdate.check.mockClear();
+ return store;
+}
+
describe('the "Update Available" toast', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -83,3 +109,203 @@ describe('the "Update Available" toast', () => {
}
});
});
+
+describe('an update that did not install', () => {
+ const message = "Version 2.0.0 didn't install: Switch Console restarted on version 1.0.0.";
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ handlers.clear();
+ localStorage.clear();
+ });
+
+ it('shows a failure after a click only where the user clicked', () => {
+ const store = new UpdateStore();
+ store.start();
+
+ emit(updateInstallFailedEvent, { version: '2.0.0', message, foundAtLaunch: false });
+
+ // The panel or the Settings card renders this state; a toast would repeat it.
+ expect(store.state).toEqual({ status: 'install-failed', message });
+ expect(store.latestVersion).toBe('2.0.0');
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('tells the user about a failure found at launch, and points at Settings', () => {
+ const store = new UpdateStore();
+ store.start();
+
+ emit(updateInstallFailedEvent, { version: '2.0.0', message, foundAtLaunch: true });
+
+ expect(toast.error).toHaveBeenCalledTimes(1);
+ expect(toast.error).toHaveBeenCalledWith(
+ "Update didn't install",
+ expect.objectContaining({ id: UPDATE_INSTALL_FAILED_TOAST_ID, description: message })
+ );
+
+ // "Download manually" quits the app, so the toast leads to the card that
+ // explains it rather than running it from a corner of the screen.
+ const [, options] = toast.error.mock.calls[0] as [
+ string,
+ { action: { label: unknown; onClick(): void } },
+ ];
+ expect(options.action.label).toBe('Details');
+ options.action.onClick();
+ expect(appState.navigation.navigate).toHaveBeenCalledWith('settings', { tab: 'status' });
+ expect(rpcUpdate.openLatest).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['found at launch', true, 1],
+ ['found after a click', false, 0],
+ ])(
+ 'on a renderer start, toasts a failure %s that main already holds',
+ async (_label, installFailedAtLaunch, toasts) => {
+ rpcUpdate.getState.mockResolvedValue({
+ success: true,
+ data: {
+ status: 'install-failed',
+ currentVersion: '1.0.0',
+ availableVersion: '2.0.0',
+ error: message,
+ installFailedAtLaunch,
+ },
+ });
+ const store = new UpdateStore();
+ store.start();
+
+ await vi.waitFor(() => expect(store.state.status).toBe('install-failed'));
+ expect(store.availableVersion).toBe('2.0.0');
+ expect(toast.error).toHaveBeenCalledTimes(toasts);
+ }
+ );
+
+ it('keeps the reason main gave when mapping its state', () => {
+ expect(
+ mainStateToRendererState({
+ status: 'install-failed',
+ currentVersion: '1.0.0',
+ error: message,
+ })
+ ).toEqual({ status: 'install-failed', message });
+ });
+});
+
+describe('a check that the user starts', () => {
+ const message = "Version 2.0.0 didn't install: Switch Console restarted on version 1.0.0.";
+ const failed = { version: '2.0.0', message, foundAtLaunch: false };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ handlers.clear();
+ localStorage.clear();
+ });
+
+ it.each([
+ ['fails', () => Promise.resolve({ success: false, error: 'getaddrinfo ENOTFOUND' })],
+ ['finds nothing', () => Promise.resolve({ success: true, result: null })],
+ ['gets no answer', () => Promise.resolve(null)],
+ ['rejects', () => Promise.reject(new Error('IPC closed'))],
+ ])('keeps install-failed when the check %s', async (_label, answer) => {
+ const store = await startedStore();
+ emit(updateInstallFailedEvent, failed);
+ rpcUpdate.check.mockImplementation(answer);
+
+ await store.check();
+
+ expect(rpcUpdate.check).toHaveBeenCalled();
+ expect(store.state).toEqual({ status: 'install-failed', message });
+ });
+
+ it('keeps showing install-failed while the check runs', async () => {
+ // The card and its "Download manually" button must not go away while the
+ // check is pending, not only after it ends.
+ const store = await startedStore();
+ emit(updateInstallFailedEvent, failed);
+ let duringCheck: unknown;
+ rpcUpdate.check.mockImplementation(async () => {
+ emit(updateCheckingEvent);
+ duringCheck = { ...store.state };
+ return { success: true, result: { version: '2.0.0' } };
+ });
+
+ await store.check();
+
+ expect(duringCheck).toEqual({ status: 'install-failed', message });
+ });
+
+ it('keeps install-failed when main sends it again during the check', async () => {
+ const store = await startedStore();
+ emit(updateInstallFailedEvent, failed);
+ rpcUpdate.check.mockImplementation(async () => {
+ emit(updateCheckingEvent);
+ emit(updateInstallFailedEvent, failed);
+ return { success: false, error: 'getaddrinfo ENOTFOUND' };
+ });
+
+ await store.check();
+
+ expect(store.state).toEqual({ status: 'install-failed', message });
+ });
+
+ it.each([
+ ['the store', (store: InstanceType<typeof UpdateStore>) => store.check()],
+ ['the menu', () => emit(menuCheckForUpdatesChannel)],
+ ])('does not ask main to check during an install, from %s', async (_label, startCheck) => {
+ const store = await startedStore();
+ emit(updateInstallingEvent);
+
+ await startCheck(store);
+
+ expect(rpcUpdate.check).not.toHaveBeenCalled();
+ expect(store.state).toEqual({ status: 'installing' });
+ });
+
+ it('keeps installing when an earlier check finds nothing', async () => {
+ const store = await startedStore();
+ rpcUpdate.check.mockImplementation(async () => {
+ emit(updateInstallingEvent);
+ return { success: true, result: null };
+ });
+
+ await store.check();
+
+ expect(store.state).toEqual({ status: 'installing' });
+ });
+});
+
+describe('the release notes link', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('asks main to open the page, since only main knows a version is made up', async () => {
+ rpcUpdate.openReleaseNotes.mockResolvedValue({ success: true });
+
+ await new UpdateStore().openReleasePage();
+
+ expect(rpcUpdate.openReleaseNotes).toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('says so when the page could not be opened', async () => {
+ rpcUpdate.openReleaseNotes.mockResolvedValue({ success: false, error: 'no browser' });
+
+ await new UpdateStore().openReleasePage();
+
+ expect(toast.error).toHaveBeenCalledWith('Could not open the release page', {
+ description: 'no browser',
+ });
+ });
+
+ it('says so when "Download manually" could not open the page', async () => {
+ // Main does not quit in this case, so without a toast nothing happens.
+ rpcUpdate.openLatest.mockResolvedValue({ success: false, error: 'no browser' });
+
+ await new UpdateStore().openLatest();
+
+ expect(toast.error).toHaveBeenCalledWith('Could not open the download page', {
+ description: 'no browser',
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.ts
index 12306e6c5..9aaa5bb0f 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/update-store.ts
@@ -2,7 +2,7 @@ import { action, computed, makeObservable, observable, runInAction } from 'mobx'
import { toast } from 'sonner';
import { createUpdateToastActionLabel } from '@renderer/lib/components/update-toast-action-label';
import { events, rpc } from '@renderer/lib/ipc';
-import { openExternalUrl } from '@renderer/lib/open-external';
+import { reportOpenAttempt } from '@renderer/lib/open-external';
import { appState } from '@renderer/lib/stores/app-state';
import { menuCheckForUpdatesChannel } from '@shared/events/appEvents';
import {
@@ -11,16 +11,23 @@ import {
updateDownloadedEvent,
updateDownloadingEvent,
updateErrorEvent,
+ updateInstallFailedEvent,
updateInstallingEvent,
updateNotAvailableEvent,
updateProgressEvent,
} from '@shared/events/updateEvents';
-import { switchConsoleReleaseUrl } from '@shared/urls';
const LAST_NOTIFIED_KEY = 'switchdash:update:lastNotified';
const SNOOZE_HOURS = 6;
/** One "Update Available" toast at a time: a repeat replaces it, and it goes once the update moves on. */
export const UPDATE_AVAILABLE_TOAST_ID = 'console-update-available';
+/** One "didn't install" toast at a time, however many times main repeats it. */
+export const UPDATE_INSTALL_FAILED_TOAST_ID = 'console-update-install-failed';
+/** Shared by the update toasts' action buttons, so they look and move alike. */
+const UPDATE_TOAST_CLASS_NAMES = {
+ actionButton:
+ 'group/action cursor-pointer transition-all duration-150 hover:bg-primary/85 active:scale-[0.97]',
+};
type DownloadProgress = {
percent?: number;
@@ -43,6 +50,8 @@ export type UpdateState =
| { status: 'downloading'; progress?: DownloadProgress }
| { status: 'downloaded' }
| { status: 'installing' }
+ /** The update was downloaded but cannot or did not install; it has to be downloaded by hand. */
+ | { status: 'install-failed'; message: string }
| { status: 'error'; message: string };
/** Statuses where main is mid-flight and a fresh check would interrupt it. */
@@ -58,12 +67,21 @@ const IN_FLIGHT_STATUSES: ReadonlySet<UpdateState['status']> = new Set([
* src/main/core/updates/update-service.ts.
*/
type MainUpdateState = {
- status: 'idle' | 'checking' | 'available' | 'downloading' | 'downloaded' | 'installing' | 'error';
+ status:
+ | 'idle'
+ | 'checking'
+ | 'available'
+ | 'downloading'
+ | 'downloaded'
+ | 'installing'
+ | 'install-failed'
+ | 'error';
currentVersion: string;
availableVersion?: string;
updateInfo?: { version: string; releaseDate?: string; releaseName?: string | null };
downloadProgress?: DownloadProgress;
error?: string;
+ installFailedAtLaunch?: boolean;
};
export function mainStateToRendererState(main: MainUpdateState): UpdateState {
@@ -87,6 +105,11 @@ export function mainStateToRendererState(main: MainUpdateState): UpdateState {
return { status: 'downloaded' };
case 'installing':
return { status: 'installing' };
+ case 'install-failed':
+ return {
+ status: 'install-failed',
+ message: main.error || "The update didn't install.",
+ };
case 'error':
return { status: 'error', message: main.error || 'The update could not be completed.' };
default:
@@ -108,7 +131,6 @@ export class UpdateStore {
hasUpdate: computed,
progressLabel: computed,
latestVersion: computed,
- releaseUrl: computed,
});
}
@@ -135,10 +157,6 @@ export class UpdateStore {
return this.availableVersion;
}
- get releaseUrl(): string {
- return switchConsoleReleaseUrl(this.latestVersion);
- }
-
start(): void {
void rpc.app.getAppVersion().then((v) => {
runInAction(() => {
@@ -147,6 +165,8 @@ export class UpdateStore {
});
events.on(updateCheckingEvent, () => {
+ // Keep the failure and its "Download manually" button while a check runs.
+ if (this.state.status === 'install-failed') return;
runInAction(() => {
this.state = { status: 'checking' };
});
@@ -210,6 +230,17 @@ export class UpdateStore {
});
});
+ events.on(updateInstallFailedEvent, (d) => {
+ this._dismissAvailableToast();
+ runInAction(() => {
+ this.availableVersion = d.version;
+ this.state = { status: 'install-failed', message: d.message };
+ });
+ // A failure after a click is already on the panel or the card that was
+ // clicked. Only one found at launch needs telling.
+ if (d.foundAtLaunch) this._toastInstallFailed(d.message);
+ });
+
events.on(updateErrorEvent, (d) => {
runInAction(() => {
this.state = { status: 'error', message: d.message };
@@ -242,6 +273,11 @@ export class UpdateStore {
this.availableVersion = main.availableVersion;
this.state = mainStateToRendererState(main);
});
+ // Main usually finds this out at launch before the window listens: the
+ // update the user restarted for did not take, and they should hear so.
+ if (this.state.status === 'install-failed' && main.installFailedAtLaunch) {
+ this._toastInstallFailed(this.state.message);
+ }
} catch {
// A failed resync is not itself an update failure — the check that
// follows will establish real state.
@@ -249,33 +285,44 @@ export class UpdateStore {
}
async check(): Promise<void> {
- runInAction(() => {
- this.state = { status: 'checking' };
- });
+ // Main refuses a check during an install, and that refusal reads as "nothing to install".
+ if (this.state.status === 'installing') return;
+ if (this.state.status !== 'install-failed') {
+ runInAction(() => {
+ this.state = { status: 'checking' };
+ });
+ }
try {
const res = await rpc.update.check();
if (!res) {
- runInAction(() => {
- this.state = { status: 'error', message: 'Update API unavailable' };
- });
+ this._setCheckResult({ status: 'error', message: 'Update API unavailable' });
return;
}
if (!res.success) {
- runInAction(() => {
- this.state = { status: 'error', message: res.error ?? 'Failed to check for updates' };
+ this._setCheckResult({
+ status: 'error',
+ message: res.error ?? 'Failed to check for updates',
});
} else if (res.result === null) {
- runInAction(() => {
- this.state = { status: 'idle' };
- });
+ this._setCheckResult({ status: 'idle' });
}
} catch {
- runInAction(() => {
- this.state = { status: 'error', message: 'Failed to check for updates' };
- });
+ this._setCheckResult({ status: 'error', message: 'Failed to check for updates' });
}
}
+ /**
+ * Main sends `installing` and `install-failed` itself, and it keeps them
+ * through a failed check. A check result must not replace them: "Try again" on
+ * an `error` state would download the version that already failed.
+ */
+ private _setCheckResult(state: UpdateState): void {
+ if (this.state.status === 'installing' || this.state.status === 'install-failed') return;
+ runInAction(() => {
+ this.state = state;
+ });
+ }
+
async download(): Promise<void> {
try {
const res = await rpc.update.download();
@@ -309,17 +356,28 @@ export class UpdateStore {
}
}
+ /**
+ * Open the release page to download the update by hand. Main quits the app
+ * after. If the page does not open, main does not quit, so say why.
+ */
async openLatest(): Promise<void> {
- try {
- await rpc.update.openLatest();
- } catch {
- // openLatest quits the app — errors are best-effort
- }
+ await reportOpenAttempt(
+ rpc.update.openLatest(),
+ 'Could not open the download page',
+ "Switch Console couldn't open the download page."
+ );
}
- /** Open this update's GitHub release page in the user's browser. */
+ /**
+ * Open this update's GitHub release page in the user's browser. Main picks the
+ * page, because only main knows when the version is the dev harness's own.
+ */
async openReleasePage(): Promise<void> {
- await openExternalUrl(this.releaseUrl, 'Could not open the release page');
+ await reportOpenAttempt(
+ rpc.update.openReleaseNotes(),
+ 'Could not open the release page',
+ 'The release page could not be opened.'
+ );
}
/**
@@ -334,6 +392,23 @@ export class UpdateStore {
toast.error('Update failed', { description: message, duration: 8_000 });
}
+ /**
+ * Point at the update card rather than repeat its button: "Download manually"
+ * quits the app, so it lives where the reason and the button are read together.
+ */
+ private _toastInstallFailed(message: string): void {
+ toast.error("Update didn't install", {
+ id: UPDATE_INSTALL_FAILED_TOAST_ID,
+ description: message,
+ duration: 10_000,
+ classNames: UPDATE_TOAST_CLASS_NAMES,
+ action: {
+ label: createUpdateToastActionLabel('Details'),
+ onClick: () => appState.navigation.navigate('settings', { tab: 'status' }),
+ },
+ });
+ }
+
private _maybeToastAvailable(version: string): void {
if (!this._shouldNotify(version)) return;
this._showAvailableToast(version);
@@ -345,12 +420,9 @@ export class UpdateStore {
id: UPDATE_AVAILABLE_TOAST_ID,
description: `Version ${version} is available to download and install.`,
duration: 10_000,
- classNames: {
- actionButton:
- 'group/action cursor-pointer transition-all duration-150 hover:bg-primary/85 active:scale-[0.97]',
- },
+ classNames: UPDATE_TOAST_CLASS_NAMES,
action: {
- label: createUpdateToastActionLabel(),
+ label: createUpdateToastActionLabel('Update'),
onClick: () => {
appState.navigation.navigate('settings', { tab: 'status' });
if (this.state.status === 'available') {
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.test.ts
index 4a94ed211..186a85911 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.test.ts
@@ -117,6 +117,22 @@ describe('presentUpdate', () => {
expect(failed.detail).toBe('The update could not be completed.');
});
+ it('offers a manual download, not another restart, for an update that did not install', () => {
+ const failed = present({
+ status: 'install-failed',
+ message: "Version 0.18.0 didn't install: Switch Console restarted on version 0.17.1.",
+ });
+
+ expect(failed.title).toBe("Update didn't install");
+ expect(failed.detail).toBe(
+ "Version 0.18.0 didn't install: Switch Console restarted on version 0.17.1."
+ );
+ expect(failed.actionKind).toBe('manual');
+ expect(failed.actionLabel).toBe('Download manually');
+ expect(failed.tone).toBe('warning');
+ expect(failed.indicatorIcon).toBe('alert');
+ });
+
it('makes failures visible in the indicator', () => {
const failed = present({ status: 'error', message: 'boom' });
@@ -135,6 +151,7 @@ describe('presentUpdate', () => {
{ status: 'downloading', progress: { percent: 1 } },
{ status: 'downloaded' },
{ status: 'installing' },
+ { status: 'install-failed', message: 'x' },
{ status: 'error', message: 'x' },
];
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.ts b/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.ts
index 14bea9b75..91c922737 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/updates/update-presentation.ts
@@ -14,7 +14,7 @@ export type UpdateTone = 'neutral' | 'info' | 'success' | 'warning';
export type UpdateIndicatorIcon = 'none' | 'available' | 'downloading' | 'restart' | 'alert';
-export type UpdateActionKind = 'none' | 'download' | 'restart' | 'retry' | 'check';
+export type UpdateActionKind = 'none' | 'download' | 'restart' | 'retry' | 'check' | 'manual';
export interface UpdatePresentation {
tone: UpdateTone;
@@ -153,6 +153,22 @@ export function presentUpdate(state: UpdateState, currentVersion: string): Updat
progressPercent: 100,
};
+ case 'install-failed':
+ return {
+ tone: 'warning',
+ indicatorLabel: 'Update failed',
+ indicatorIcon: 'alert',
+ actionable: true,
+ title: "Update didn't install",
+ detail: state.message,
+ // Restarting again would fail the same way. The release page has the
+ // installer, and the app quits so it can be replaced.
+ actionKind: 'manual',
+ actionLabel: 'Download manually',
+ busy: false,
+ progressPercent: null,
+ };
+
case 'error':
return {
tone: 'warning',
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
index 48f33fe09..e067dc461 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
@@ -25,7 +25,7 @@ vi.mock('@renderer/lib/ipc', () => ({
},
events: { on: () => () => {}, emit: () => {} },
}));
-vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl }));
+vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl, reportOpenAttempt: vi.fn() }));
vi.mock('@renderer/lib/modal/modal-provider', () => ({
useShowModal: (id: string) => (args: unknown) => showModal(id, args),
}));
diff --git a/console/apps/switch-console-desktop/src/shared/events/updateEvents.ts b/console/apps/switch-console-desktop/src/shared/events/updateEvents.ts
index fd29f53be..f92c3e50e 100644
--- a/console/apps/switch-console-desktop/src/shared/events/updateEvents.ts
+++ b/console/apps/switch-console-desktop/src/shared/events/updateEvents.ts
@@ -23,4 +23,16 @@ export const updateDownloadedEvent = defineEvent<{ version: string }>('update:do
export const updateInstallingEvent = defineEvent<void>('update:installing');
+/**
+ * An install did not happen: the installer failed, the app came back on the old
+ * version, or this copy of the app cannot be updated in place. The update has
+ * to be downloaded by hand.
+ */
+export const updateInstallFailedEvent = defineEvent<{
+ version: string;
+ message: string;
+ /** Found on the launch after a handover, rather than while someone watched. */
+ foundAtLaunch: boolean;
+}>('update:install-failed');
+
export const updateErrorEvent = defineEvent<{ message: string }>('update:error');
diff --git a/console/docs/INSTALL.md b/console/docs/INSTALL.md
index 6f91dce25..cf785600e 100644
--- a/console/docs/INSTALL.md
+++ b/console/docs/INSTALL.md
@@ -205,6 +205,8 @@ Artifacts land in `console/apps/switch-console-desktop/release/`.
`switch-console` as a new package rather than an upgrade of `switchdash`, so
remove the old one yourself (`sudo apt remove switchdash`) or the two sit
side by side.
-- Switch Console releases use the `switch-console-v*` tag prefix and are published with
- the repo-wide "Latest" badge **off**, so they never collide with other release
- streams in this repo.
+- Stable Switch Console releases use the `switch-console-v*` tag prefix and are
+ published as the repo's **Latest** release, because that is the release the
+ stable auto-updater reads. Every other release in this repo, Switch Console
+ canaries included, is published with "Latest" off so that it never becomes
+ the stable update feed.