Skip to content

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

feat(switchdash): improve the "update available" UX (CHOO-1434) (#107)

Louis Amaudruz857e67f4af3e
diff --git a/dash/AGENTS.md b/dash/AGENTS.md
index 25748cc85..e05c811e1 100644
--- a/dash/AGENTS.md
+++ b/dash/AGENTS.md
@@ -442,8 +442,19 @@ pnpm run test
`.switchdash.json`.
- Optional environment variables:
`SWITCHDASH_DB_FILE`, `SWITCHDASH_DISABLE_NATIVE_DB`,
- `SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`, `CODEX_SANDBOX_MODE`,
+ `SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`,
+ `SWITCHDASH_FAKE_UPDATE`, `CODEX_SANDBOX_MODE`,
and `CODEX_APPROVAL_POLICY`.
+- 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`.
+ 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
+ duration. Nothing is downloaded or installed, and the harness cannot activate in
+ a packaged build. Example:
+ `SWITCHDASH_FAKE_UPDATE=available pnpm run dev`.
- Deeplinks in dev: `pnpm run dev` does **not** claim the `switchdash://` OS URL
scheme by default — doing so hijacks the handler from the installed app and the
registration outlives the dev process (on macOS it sticks in Launch Services),
diff --git a/dash/apps/switchdash-desktop/src/main/core/updates/dev-harness.test.ts b/dash/apps/switchdash-desktop/src/main/core/updates/dev-harness.test.ts
new file mode 100644
index 000000000..83991d82a
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/updates/dev-harness.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ FAKE_UPDATE_SCENARIOS,
+ FakeUpdateDriver,
+ type UpdateSignals,
+ nextFakeVersion,
+ readFakeDownloadDuration,
+ readFakeUpdateScenario,
+} from './dev-harness';
+
+function makeSignals(): UpdateSignals & { calls: string[] } {
+ const calls: string[] = [];
+ return {
+ calls,
+ checking: vi.fn(() => void calls.push('checking')),
+ available: vi.fn(() => void calls.push('available')),
+ notAvailable: vi.fn(() => void calls.push('notAvailable')),
+ progress: vi.fn(() => void calls.push('progress')),
+ downloaded: vi.fn(() => void calls.push('downloaded')),
+ failed: vi.fn(() => void calls.push('failed')),
+ authRequired: vi.fn(() => void calls.push('authRequired')),
+ };
+}
+
+describe('readFakeUpdateScenario', () => {
+ it('is off when the variable is absent or blank', () => {
+ expect(readFakeUpdateScenario({})).toBeNull();
+ expect(readFakeUpdateScenario({ SWITCHDASH_FAKE_UPDATE: ' ' })).toBeNull();
+ });
+
+ it('accepts every documented scenario', () => {
+ for (const scenario of FAKE_UPDATE_SCENARIOS) {
+ expect(readFakeUpdateScenario({ SWITCHDASH_FAKE_UPDATE: scenario })).toBe(scenario);
+ }
+ });
+
+ it('rejects a typo loudly rather than falling back to a default', () => {
+ expect(() => readFakeUpdateScenario({ SWITCHDASH_FAKE_UPDATE: 'availabel' })).toThrow(
+ /not a known scenario/
+ );
+ });
+});
+
+describe('readFakeDownloadDuration', () => {
+ it('defaults when unset', () => {
+ expect(readFakeDownloadDuration({})).toBeGreaterThan(0);
+ });
+
+ it('rejects values that would make the harness misbehave', () => {
+ expect(() => readFakeDownloadDuration({ SWITCHDASH_FAKE_UPDATE_MS: '0' })).toThrow();
+ expect(() => readFakeDownloadDuration({ SWITCHDASH_FAKE_UPDATE_MS: '-5' })).toThrow();
+ expect(() => readFakeDownloadDuration({ SWITCHDASH_FAKE_UPDATE_MS: 'soon' })).toThrow();
+ });
+});
+
+describe('nextFakeVersion', () => {
+ it('bumps the minor and resets the patch', () => {
+ expect(nextFakeVersion('0.17.1')).toBe('0.18.0');
+ expect(nextFakeVersion('1.2.3')).toBe('1.3.0');
+ });
+
+ it('still produces a newer-looking version from an unparseable one', () => {
+ expect(nextFakeVersion('unknown')).toBe('99.0.0');
+ });
+});
+
+describe('FakeUpdateDriver', () => {
+ it('reports an available update on the happy path', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('available', signals, '0.18.0', 40);
+
+ const info = await driver.check();
+
+ expect(signals.calls).toEqual(['checking', 'available']);
+ expect(info?.version).toBe('0.18.0');
+ });
+
+ it('drives progress to completion', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('available', signals, '0.18.0', 40);
+
+ await driver.download();
+
+ expect(signals.progress).toHaveBeenCalled();
+ expect(signals.calls.at(-1)).toBe('downloaded');
+
+ const lastProgress = vi.mocked(signals.progress).mock.lastCall?.[0];
+ expect(lastProgress?.percent).toBe(100);
+ expect(lastProgress?.transferred).toBe(lastProgress?.total);
+ });
+
+ it('throws part-way through the download-error scenario', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('download-error', signals, '0.18.0', 40);
+
+ await expect(driver.download()).rejects.toThrow(/connection reset/);
+ expect(signals.calls).not.toContain('downloaded');
+ });
+
+ it('signals a failed check', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('check-error', signals, '0.18.0', 40);
+
+ expect(await driver.check()).toBeNull();
+ expect(signals.calls).toEqual(['checking', 'failed']);
+ });
+
+ it('signals missing credentials', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('auth-required', signals, '0.18.0', 40);
+
+ expect(await driver.check()).toBeNull();
+ expect(signals.calls).toEqual(['checking', 'authRequired']);
+ });
+
+ it('signals up-to-date', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('up-to-date', signals, '0.18.0', 40);
+
+ expect(await driver.check()).toBeNull();
+ expect(signals.calls).toEqual(['checking', 'notAvailable']);
+ });
+
+ it('stops emitting once disposed', async () => {
+ const signals = makeSignals();
+ const driver = new FakeUpdateDriver('available', signals, '0.18.0', 400);
+
+ const pending = driver.download();
+ driver.dispose();
+ await pending;
+
+ expect(signals.calls).not.toContain('downloaded');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/updates/dev-harness.ts b/dash/apps/switchdash-desktop/src/main/core/updates/dev-harness.ts
new file mode 100644
index 000000000..519125c21
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/updates/dev-harness.ts
@@ -0,0 +1,197 @@
+import type { UpdateInfo } from 'electron-updater';
+
+/**
+ * Dev-only driver that replays the update lifecycle without a real release
+ * feed. The updater is inert outside packaged builds, so this is the only way
+ * to exercise the update UI locally.
+ *
+ * Enable with SWITCHDASH_FAKE_UPDATE=<scenario> in `pnpm dev`. It is refused in
+ * packaged builds — see updateService.initialize.
+ */
+
+export const FAKE_UPDATE_ENV_VAR = 'SWITCHDASH_FAKE_UPDATE';
+export const FAKE_UPDATE_VERSION_ENV_VAR = 'SWITCHDASH_FAKE_UPDATE_VERSION';
+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; the download fails part-way. */
+ 'download-error',
+ /** The check itself fails. */
+ 'check-error',
+ /** The check reports no GitHub credentials. */
+ 'auth-required',
+ /** Check finds nothing. */
+ 'up-to-date',
+] as const;
+
+export type FakeUpdateScenario = (typeof FAKE_UPDATE_SCENARIOS)[number];
+
+const DEFAULT_DOWNLOAD_MS = 6_000;
+const FAKE_TOTAL_BYTES = 68 * 1024 * 1024;
+const PROGRESS_STEPS = 24;
+
+/**
+ * Signals the driver raises. The real autoUpdater listeners feed the same
+ * methods, so fake and real runs move the service through identical states.
+ */
+export interface UpdateSignals {
+ checking(): void;
+ available(info: UpdateInfo): void;
+ notAvailable(): void;
+ progress(progress: {
+ bytesPerSecond: number;
+ percent: number;
+ transferred: number;
+ total: number;
+ }): void;
+ downloaded(version: string): void;
+ failed(error: unknown): void;
+ authRequired(): void;
+}
+
+export function isFakeUpdateScenario(value: string): value is FakeUpdateScenario {
+ return (FAKE_UPDATE_SCENARIOS as readonly string[]).includes(value);
+}
+
+/**
+ * Read the requested scenario, or null when the harness is off. Throws on an
+ * unrecognised value rather than silently running the default — a typo'd
+ * scenario should not look like a working update.
+ */
+export function readFakeUpdateScenario(env: NodeJS.ProcessEnv): FakeUpdateScenario | null {
+ const raw = env[FAKE_UPDATE_ENV_VAR]?.trim();
+ if (!raw) return null;
+
+ if (!isFakeUpdateScenario(raw)) {
+ throw new Error(
+ `${FAKE_UPDATE_ENV_VAR}="${raw}" is not a known scenario. Use one of: ${FAKE_UPDATE_SCENARIOS.join(', ')}`
+ );
+ }
+
+ return raw;
+}
+
+/** Next plausible version for the fake feed: bump the minor, reset the patch. */
+export function nextFakeVersion(currentVersion: string): string {
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(currentVersion);
+ if (!match) return '99.0.0';
+ return `${match[1]}.${Number(match[2]) + 1}.0`;
+}
+
+export function readFakeDownloadDuration(env: NodeJS.ProcessEnv): number {
+ const raw = env[FAKE_UPDATE_DURATION_ENV_VAR];
+ if (!raw) return DEFAULT_DOWNLOAD_MS;
+ const parsed = Number(raw);
+ if (!Number.isFinite(parsed) || parsed <= 0) {
+ throw new Error(`${FAKE_UPDATE_DURATION_ENV_VAR}="${raw}" is not a positive number of ms`);
+ }
+ return parsed;
+}
+
+export class FakeUpdateDriver {
+ private readonly pendingWaits = new Set<{ timer: NodeJS.Timeout; resolve: () => void }>();
+ private disposed = false;
+
+ constructor(
+ readonly scenario: FakeUpdateScenario,
+ private readonly signals: UpdateSignals,
+ readonly nextVersion: string,
+ private readonly downloadMs: number
+ ) {}
+
+ async check(): Promise<UpdateInfo | null> {
+ this.signals.checking();
+ await this.delay(500);
+ if (this.disposed) return null;
+
+ switch (this.scenario) {
+ case 'auth-required':
+ this.signals.authRequired();
+ return null;
+
+ case 'check-error':
+ this.signals.failed(new Error('Simulated update check failure (HTTP 503)'));
+ return null;
+
+ case 'up-to-date':
+ this.signals.notAvailable();
+ return null;
+
+ default: {
+ const info = this.buildUpdateInfo();
+ this.signals.available(info);
+ return info;
+ }
+ }
+ }
+
+ /**
+ * Mirrors autoUpdater.downloadUpdate: emits progress and either resolves or
+ * throws. The service's own error handling converts the throw into the error
+ * state, so the failure path is the real one.
+ */
+ async download(): Promise<void> {
+ const stepMs = Math.max(40, this.downloadMs / PROGRESS_STEPS);
+ const bytesPerSecond = FAKE_TOTAL_BYTES / (this.downloadMs / 1000);
+ const failAtStep = Math.ceil(PROGRESS_STEPS / 3);
+
+ for (let step = 1; step <= PROGRESS_STEPS; step++) {
+ await this.delay(stepMs);
+ if (this.disposed) return;
+
+ if (this.scenario === 'download-error' && step === failAtStep) {
+ throw new Error('Simulated download failure: connection reset by peer');
+ }
+
+ const fraction = step / PROGRESS_STEPS;
+ this.signals.progress({
+ percent: fraction * 100,
+ transferred: Math.round(FAKE_TOTAL_BYTES * fraction),
+ total: FAKE_TOTAL_BYTES,
+ bytesPerSecond,
+ });
+ }
+
+ this.signals.downloaded(this.nextVersion);
+ }
+
+ /**
+ * Resolve outstanding waits rather than just cancelling their timers, so an
+ * in-flight download settles instead of hanging forever on shutdown. The
+ * disposed flag stops the loop before it emits anything further.
+ */
+ dispose(): void {
+ this.disposed = true;
+ for (const wait of this.pendingWaits) {
+ clearTimeout(wait.timer);
+ wait.resolve();
+ }
+ this.pendingWaits.clear();
+ }
+
+ private buildUpdateInfo(): UpdateInfo {
+ return {
+ version: this.nextVersion,
+ files: [],
+ path: '',
+ sha512: '',
+ releaseDate: new Date().toISOString(),
+ releaseName: `Switchdash ${this.nextVersion}`,
+ } as UpdateInfo;
+ }
+
+ private delay(ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ const wait = {
+ resolve,
+ timer: setTimeout(() => {
+ this.pendingWaits.delete(wait);
+ resolve();
+ }, ms),
+ };
+ this.pendingWaits.add(wait);
+ });
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts b/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts
index 40be6633f..892998d5b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts
@@ -24,6 +24,14 @@ import {
updateNotAvailableEvent,
updateProgressEvent,
} from '@shared/events/updateEvents';
+import {
+ FAKE_UPDATE_VERSION_ENV_VAR,
+ FakeUpdateDriver,
+ type UpdateSignals,
+ nextFakeVersion,
+ readFakeDownloadDuration,
+ readFakeUpdateScenario,
+} from './dev-harness';
import { getGithubTokenFromGhCli } from './github-token';
import { formatUpdaterError, sanitizeUpdaterLogArgs } from './utils';
@@ -34,6 +42,10 @@ const ALLOW_DOWNGRADE = false;
const CHECK_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
const STARTUP_DELAY_MS = 30 * 1000; // 30 seconds
const INSTALL_RESTART_GUARD_TIMEOUT_MS = 2 * 60 * 1000;
+/** The dev harness checks promptly — nobody wants to wait 30s to see the UI. */
+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;
export interface UpdateState {
status:
@@ -69,6 +81,7 @@ class UpdateService implements IInitializable, IDisposable {
private active = false;
private installRequested = false;
private installRestartGuardTimer?: NodeJS.Timeout;
+ private fake?: FakeUpdateDriver;
constructor() {
this.updateState = {
@@ -83,7 +96,10 @@ class UpdateService implements IInitializable, IDisposable {
this.updateState.currentVersion = await resolveAppVersion();
- if (import.meta.env.DEV) return;
+ if (import.meta.env.DEV) {
+ this.setupDevHarness();
+ return;
+ }
this.setupAutoUpdater();
this.setupEventListeners();
@@ -97,6 +113,34 @@ class UpdateService implements IInitializable, IDisposable {
this.scheduleNextCheck(STARTUP_DELAY_MS);
}
+ /**
+ * Activate the dev harness when SWITCHDASH_FAKE_UPDATE names a scenario.
+ * Without it the service stays inert in dev, exactly as before.
+ */
+ private setupDevHarness(): void {
+ const scenario = readFakeUpdateScenario(process.env);
+ if (!scenario) return;
+
+ const nextVersion =
+ process.env[FAKE_UPDATE_VERSION_ENV_VAR]?.trim() ||
+ nextFakeVersion(this.updateState.currentVersion);
+
+ this.fake = new FakeUpdateDriver(
+ scenario,
+ this.signals,
+ nextVersion,
+ readFakeDownloadDuration(process.env)
+ );
+ this.active = true;
+
+ log.warn(
+ `[dev] Update harness ACTIVE — scenario "${scenario}", fake version ${nextVersion}. ` +
+ 'Updates are simulated; nothing is downloaded or installed.'
+ );
+
+ this.scheduleNextCheck(FAKE_STARTUP_DELAY_MS);
+ }
+
private setupAutoUpdater(): void {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;
@@ -113,26 +157,30 @@ class UpdateService implements IInitializable, IDisposable {
autoUpdater.logger = updaterLogger;
}
- private setupEventListeners(): void {
- autoUpdater.on('checking-for-update', () => {
+ /**
+ * State transitions, shared by the real autoUpdater listeners and the dev
+ * harness so both drive the app through identical states.
+ */
+ private readonly signals: UpdateSignals = {
+ checking: () => {
this.updateState.status = 'checking';
this.updateState.lastCheck = new Date();
events.emit(updateCheckingEvent, undefined);
- });
+ },
- autoUpdater.on('update-available', (info: UpdateInfo) => {
+ available: (info: UpdateInfo) => {
this.updateState.status = 'available';
this.updateState.availableVersion = info.version;
this.updateState.updateInfo = info;
events.emit(updateAvailableEvent, { version: info.version, updateInfo: info });
- });
+ },
- autoUpdater.on('update-not-available', () => {
+ notAvailable: () => {
this.updateState.status = 'idle';
events.emit(updateNotAvailableEvent, undefined);
- });
+ },
- autoUpdater.on('error', (err: Error) => {
+ failed: (err: unknown) => {
const errorMessage = formatUpdaterError(err);
log.error('Auto-updater error:', errorMessage);
@@ -153,29 +201,47 @@ class UpdateService implements IInitializable, IDisposable {
}
events.emit(updateErrorEvent, { message: errorMessage });
- });
+ },
- autoUpdater.on('download-progress', (progressObj: ProgressInfo) => {
+ progress: (progress) => {
this.updateState.status = 'downloading';
- this.updateState.downloadProgress = {
- bytesPerSecond: progressObj.bytesPerSecond,
- percent: progressObj.percent,
- transferred: progressObj.transferred,
- total: progressObj.total,
- };
- events.emit(updateProgressEvent, {
+ this.updateState.downloadProgress = progress;
+ events.emit(updateProgressEvent, progress);
+ },
+
+ downloaded: (version: string) => {
+ this.updateState.status = 'downloaded';
+ this.updateState.rollbackVersion = this.updateState.currentVersion;
+ events.emit(updateDownloadedEvent, { version });
+ },
+
+ authRequired: () => {
+ this.updateState.status = 'auth-required';
+ events.emit(updateAuthRequiredEvent, undefined);
+ },
+ };
+
+ private setupEventListeners(): void {
+ autoUpdater.on('checking-for-update', () => this.signals.checking());
+
+ autoUpdater.on('update-available', (info: UpdateInfo) => this.signals.available(info));
+
+ autoUpdater.on('update-not-available', () => this.signals.notAvailable());
+
+ autoUpdater.on('error', (err: Error) => this.signals.failed(err));
+
+ autoUpdater.on('download-progress', (progressObj: ProgressInfo) =>
+ this.signals.progress({
bytesPerSecond: progressObj.bytesPerSecond,
percent: progressObj.percent,
transferred: progressObj.transferred,
total: progressObj.total,
- });
- });
+ })
+ );
- autoUpdater.on('update-downloaded', (info: UpdateInfo) => {
- this.updateState.status = 'downloaded';
- this.updateState.rollbackVersion = this.updateState.currentVersion;
- events.emit(updateDownloadedEvent, { version: info.version });
- });
+ autoUpdater.on('update-downloaded', (info: UpdateInfo) =>
+ this.signals.downloaded(info.version)
+ );
}
private scheduleNextCheck(delay = CHECK_INTERVAL_MS): void {
@@ -208,13 +274,14 @@ class UpdateService implements IInitializable, IDisposable {
this.updateState.error = undefined;
}
+ if (this.fake) return this.fake.check();
+
// The switch release feed is a private repo, so the updater needs a token.
// Reuse the user's existing `gh` login rather than shipping a secret. Without
// a token we stay dormant (auth-required) instead of erroring every hour.
const token = await getGithubTokenFromGhCli();
if (!token) {
- this.updateState.status = 'auth-required';
- events.emit(updateAuthRequiredEvent, undefined);
+ this.signals.authRequired();
log.info('Skipping update check: no GitHub token from gh CLI (run `gh auth login`)');
return null;
}
@@ -264,7 +331,8 @@ class UpdateService implements IInitializable, IDisposable {
events.emit(updateDownloadingEvent, { version: this.updateState.availableVersion });
try {
- await autoUpdater.downloadUpdate();
+ if (this.fake) await this.fake.download();
+ else await autoUpdater.downloadUpdate();
} catch (error: unknown) {
const errorMessage = formatUpdaterError(error);
log.error('Update download failed:', errorMessage, error);
@@ -321,6 +389,16 @@ class UpdateService implements IInitializable, IDisposable {
log.error(reason);
};
+ 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');
+ }, FAKE_INSTALL_ROLLBACK_MS);
+ return;
+ }
+
this.installRestartGuardTimer = setTimeout(() => {
rollback('quitAndInstall timed out before app quit; allowing retry');
}, INSTALL_RESTART_GUARD_TIMEOUT_MS);
@@ -381,6 +459,7 @@ class UpdateService implements IInitializable, IDisposable {
}
dispose(): void {
+ this.fake?.dispose();
if (this.checkTimer) {
clearTimeout(this.checkTimer);
this.checkTimer = undefined;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/settings/components/UpdateCard.tsx b/dash/apps/switchdash-desktop/src/renderer/features/settings/components/UpdateCard.tsx
index 5f6cdd638..0edfa6016 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/settings/components/UpdateCard.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/settings/components/UpdateCard.tsx
@@ -1,16 +1,69 @@
-import { AlertCircle, CheckCircle2, Download, Loader2, RefreshCw } from 'lucide-react';
+import {
+ AlertTriangle,
+ ArrowRight,
+ CheckCircle2,
+ Download,
+ ExternalLink,
+ Loader2,
+ RefreshCw,
+} from 'lucide-react';
import { observer } from 'mobx-react-lite';
import React from 'react';
import { appState } from '@renderer/lib/stores/app-state';
import { Badge } from '@renderer/lib/ui/badge';
import { Button } from '@renderer/lib/ui/button';
-import { PRODUCT_NAME } from '@shared/app-identity';
+import { Progress } from '@renderer/lib/ui/progress';
+import {
+ type UpdateActionKind,
+ type UpdateTone,
+ presentUpdate,
+} from '@renderer/lib/updates/update-presentation';
+import { cn } from '@renderer/utils/utils';
import { SettingRow } from './SettingRow';
+const TONE_TEXT_STYLES: Record<UpdateTone, string> = {
+ neutral: 'text-muted-foreground',
+ info: 'text-muted-foreground',
+ success: 'text-foreground-success',
+ warning: 'text-foreground-warning',
+};
+
+const ACTION_ICONS: Record<UpdateActionKind, React.ComponentType<{ className?: string }> | null> = {
+ none: null,
+ download: Download,
+ restart: RefreshCw,
+ retry: RefreshCw,
+ check: RefreshCw,
+};
+
export const UpdateCard = observer(function UpdateCard(): React.JSX.Element {
const update = appState.update;
- const downloadProgress =
- update.state.status === 'downloading' ? update.state.progress : undefined;
+ const presentation = presentUpdate(update.state, update.currentVersion);
+ const ActionIcon = ACTION_ICONS[presentation.actionKind];
+
+ const isInstalling = update.state.status === 'installing';
+ const isDownloaded = update.state.status === 'downloaded';
+ const showRecheck = !isDownloaded && !isInstalling && presentation.actionKind !== 'check';
+
+ function runAction(): void {
+ switch (presentation.actionKind) {
+ case 'download':
+ void update.download();
+ break;
+ case 'restart':
+ void update.install();
+ break;
+ case 'retry':
+ if (update.latestVersion) void update.download();
+ else void update.check();
+ break;
+ case 'check':
+ void update.check();
+ break;
+ default:
+ break;
+ }
+ }
const versionTitle = (
<div className="flex items-center gap-2">
@@ -20,6 +73,17 @@ export const UpdateCard = observer(function UpdateCard(): React.JSX.Element {
v{update.currentVersion}
</Badge>
)}
+ {update.latestVersion && update.latestVersion !== update.currentVersion && (
+ <>
+ <ArrowRight className="size-3 text-foreground-passive" />
+ <Badge
+ variant="outline"
+ className="h-5 border-border-info bg-background-info px-2 font-mono text-xs text-foreground-info"
+ >
+ v{update.latestVersion}
+ </Badge>
+ </>
+ )}
</div>
);
@@ -27,149 +91,88 @@ export const UpdateCard = observer(function UpdateCard(): React.JSX.Element {
<div className="grid gap-3">
<SettingRow
title={versionTitle}
- description={renderStatusMessage()}
+ description={
+ <div className="flex flex-col gap-1">
+ <p
+ className={cn(
+ 'flex items-center gap-1.5 text-sm',
+ TONE_TEXT_STYLES[presentation.tone]
+ )}
+ >
+ {renderStatusIcon()}
+ {presentation.title}
+ </p>
+ {presentation.detail && (
+ <p className={cn('text-sm', TONE_TEXT_STYLES[presentation.tone])}>
+ {presentation.detail}
+ </p>
+ )}
+ {update.latestVersion && (
+ <button
+ type="button"
+ onClick={() => void update.openReleasePage()}
+ className="inline-flex w-fit cursor-pointer items-center gap-1 text-xs text-foreground-passive underline-offset-2 hover:text-foreground hover:underline"
+ >
+ Release notes
+ <ExternalLink className="size-3" />
+ </button>
+ )}
+ </div>
+ }
className="items-center rounded-lg border p-4"
control={
<div className="flex items-center gap-2">
- {update.state.status !== 'downloaded' && update.state.status !== 'installing' && (
+ {showRecheck && (
<Button
type="button"
variant="outline"
size="icon"
- onClick={() => update.check()}
+ onClick={() => void update.check()}
disabled={update.state.status === 'checking'}
aria-label="Check for updates"
>
<RefreshCw
- className={`size-4 ${update.state.status === 'checking' ? 'animate-spin' : ''}`}
+ className={cn('size-4', update.state.status === 'checking' && 'animate-spin')}
/>
</Button>
)}
- {renderAction()}
+ {presentation.actionLabel && (
+ <Button
+ variant={presentation.tone === 'warning' ? 'outline' : 'default'}
+ onClick={runAction}
+ disabled={presentation.busy}
+ >
+ {presentation.busy ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : (
+ ActionIcon && <ActionIcon className="size-4" />
+ )}
+ {presentation.actionLabel}
+ </Button>
+ )}
+ {presentation.busy && !presentation.actionLabel && (
+ <Button variant="outline" disabled>
+ <Loader2 className="size-4 animate-spin" />
+ {presentation.title}
+ </Button>
+ )}
</div>
}
/>
- {update.state.status === 'downloading' && downloadProgress && (
- <div className="bg-muted h-1.5 w-full overflow-hidden rounded-full">
- <div
- className="bg-primary h-full transition-all duration-300 ease-out"
- style={{ width: `${downloadProgress.percent || 0}%` }}
- />
- </div>
+ {update.state.status === 'downloading' && presentation.progressPercent !== null && (
+ <Progress value={presentation.progressPercent} />
)}
</div>
);
- function renderStatusMessage() {
- switch (update.state.status) {
- case 'checking':
- return (
- <p className="text-muted-foreground flex items-center gap-1 text-sm">
- <Loader2 className="h-3 w-3 animate-spin" />
- Checking for updates...
- </p>
- );
-
- case 'available':
- if (update.state.info?.version) {
- return (
- <p className="text-muted-foreground text-sm">
- Version {update.state.info.version} is available
- </p>
- );
- }
- return <p className="text-muted-foreground text-sm">An update is available</p>;
-
- case 'downloading':
- return (
- <p className="text-muted-foreground text-sm">
- Downloading update{update.progressLabel ? ` (${update.progressLabel})` : '...'}
- </p>
- );
-
- case 'downloaded':
- return (
- <p className="flex items-center gap-1 text-sm text-foreground-success">
- <CheckCircle2 className="h-3 w-3" />
- Update ready. Restart {PRODUCT_NAME} to use the new version.
- </p>
- );
-
- case 'installing':
- return (
- <p className="text-muted-foreground flex items-center gap-1 text-sm">
- <Loader2 className="h-3 w-3 animate-spin" />
- Installing update. {PRODUCT_NAME} will close and restart automatically — this may take a
- few seconds.
- </p>
- );
-
- case 'error':
- return (
- <Badge
- variant="outline"
- className="border-border-warning bg-background-warning text-foreground-warning"
- >
- <AlertCircle className="h-3 w-3" />
- Update temporarily unavailable — please try again later
- </Badge>
- );
-
- case 'auth-required':
- return (
- <p className="text-muted-foreground text-sm">
- Sign in to GitHub to enable updates — run{' '}
- <code className="font-mono text-xs">gh auth login</code> in a terminal, then recheck.
- </p>
- );
-
- default:
- return (
- <p className="text-muted-foreground flex items-center gap-1 text-sm">
- <CheckCircle2 className="h-3 w-3 text-foreground-success" />
- You're up to date.{' '}
- </p>
- );
- }
- }
-
- function renderAction() {
- switch (update.state.status) {
- case 'available':
- return (
- <Button variant="default" onClick={() => update.download()}>
- <Download className="size-4" />
- Download
- </Button>
- );
-
- case 'downloading':
- return (
- <Button variant="outline" disabled>
- <Loader2 className="size-4 animate-spin" />
- Downloading
- </Button>
- );
-
- case 'downloaded':
- return (
- <Button variant="default" onClick={() => update.install()}>
- <RefreshCw className="size-4" />
- Restart
- </Button>
- );
-
- case 'installing':
- return (
- <Button variant="outline" disabled>
- <Loader2 className="size-4 animate-spin" />
- Installing
- </Button>
- );
-
- default:
- return null;
+ function renderStatusIcon(): React.ReactNode {
+ if (presentation.busy) return <Loader2 className="size-3 animate-spin" />;
+ if (presentation.tone === 'warning') return <AlertTriangle className="size-3" />;
+ if (presentation.tone === 'success') return <CheckCircle2 className="size-3" />;
+ if (update.state.status === 'idle' || update.state.status === 'not-available') {
+ return <CheckCircle2 className="size-3 text-foreground-success" />;
}
+ return null;
}
});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/update-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/update-section.tsx
index e364c650f..7e209f31d 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/update-section.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/update-section.tsx
@@ -1,32 +1,169 @@
+import {
+ AlertTriangle,
+ ArrowRight,
+ ArrowUp,
+ Download,
+ ExternalLink,
+ Loader2,
+ RefreshCw,
+} from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import React from 'react';
import { appState } from '@renderer/lib/stores/app-state';
import { Button } from '@renderer/lib/ui/button';
-import { MicroLabel } from '@renderer/lib/ui/label';
+import {
+ Popover,
+ PopoverContent,
+ PopoverDescription,
+ PopoverHeader,
+ PopoverTitle,
+ PopoverTrigger,
+} from '@renderer/lib/ui/popover';
+import { Progress } from '@renderer/lib/ui/progress';
+import {
+ type UpdateActionKind,
+ type UpdateIndicatorIcon,
+ type UpdateTone,
+ presentUpdate,
+} from '@renderer/lib/updates/update-presentation';
+import { cn } from '@renderer/utils/utils';
+
+const TONE_TRIGGER_STYLES: Record<UpdateTone, string> = {
+ neutral: 'text-foreground-passive hover:text-foreground',
+ info: 'border border-border-info bg-background-info text-foreground-info hover:bg-background-info-hover',
+ success:
+ 'border border-border-success bg-background-success text-foreground-success hover:bg-background-success-hover',
+ warning:
+ 'border border-border-warning bg-background-warning text-foreground-warning hover:bg-background-warning-hover',
+};
+
+const INDICATOR_ICONS: Record<UpdateIndicatorIcon, React.ComponentType<{ className?: string }>> = {
+ none: () => null,
+ available: ArrowUp,
+ downloading: Loader2,
+ restart: RefreshCw,
+ alert: AlertTriangle,
+};
+
+const ACTION_ICONS: Record<UpdateActionKind, React.ComponentType<{ className?: string }> | null> = {
+ none: null,
+ download: Download,
+ restart: RefreshCw,
+ retry: RefreshCw,
+ check: RefreshCw,
+};
export const UpdateSection = observer(function UpdateSection() {
const update = appState.update;
- const { navigate } = useNavigate();
-
- if (update.hasUpdate) {
- return (
- <Button
- variant="outline"
- size="xs"
- onClick={() =>
- navigate('settings', {
- tab: 'general',
- })
- }
- >
- Update
- </Button>
- );
+ const presentation = presentUpdate(update.state, update.currentVersion);
+ const IndicatorIcon = INDICATOR_ICONS[presentation.indicatorIcon];
+ const ActionIcon = ACTION_ICONS[presentation.actionKind];
+ const isNeutral = presentation.tone === 'neutral';
+
+ function runAction(): void {
+ switch (presentation.actionKind) {
+ case 'download':
+ void update.download();
+ break;
+ case 'restart':
+ void update.install();
+ break;
+ case 'retry':
+ // A failed download can be retried directly; a failed check has no
+ // version to retry against, so go back through the check.
+ if (update.latestVersion) void update.download();
+ else void update.check();
+ break;
+ case 'check':
+ void update.check();
+ break;
+ default:
+ break;
+ }
}
return (
- <MicroLabel className="inline-flex h-6 items-center text-foreground-passive lowercase">
- v{update.currentVersion}
- </MicroLabel>
+ <Popover>
+ <PopoverTrigger
+ aria-label={`${presentation.title}. Open update details.`}
+ className={cn(
+ 'relative inline-flex h-6 cursor-pointer items-center gap-1.5 overflow-hidden rounded-full px-2 text-[11px] font-medium transition-colors',
+ isNeutral && 'lowercase',
+ TONE_TRIGGER_STYLES[presentation.tone]
+ )}
+ >
+ {/* While downloading, the fill doubles as the progress bar so the row
+ reports progress without needing the panel open. */}
+ {presentation.progressPercent !== null && presentation.busy && (
+ <span
+ aria-hidden
+ className="absolute inset-y-0 left-0 bg-foreground-info/15 transition-[width] duration-300 ease-out"
+ style={{ width: `${presentation.progressPercent}%` }}
+ />
+ )}
+ <span className="relative inline-flex items-center gap-1.5">
+ <IndicatorIcon
+ className={cn('size-3', presentation.indicatorIcon === 'downloading' && 'animate-spin')}
+ />
+ {presentation.indicatorLabel}
+ </span>
+ </PopoverTrigger>
+
+ {/* Kept narrower than the sidebar so it can align to the indicator
+ instead of being flipped away from it to avoid overflow. */}
+ <PopoverContent side="top" align="end" sideOffset={8} className="w-64 gap-3">
+ <PopoverHeader>
+ <PopoverTitle className="flex items-center gap-2">
+ {presentation.busy && <Loader2 className="size-3.5 animate-spin" />}
+ {presentation.title}
+ </PopoverTitle>
+
+ {update.state.status === 'available' && update.latestVersion ? (
+ <div className="flex items-center gap-2 font-mono text-xs">
+ <span className="text-foreground-passive">v{update.currentVersion}</span>
+ <ArrowRight className="size-3 text-foreground-passive" />
+ <span className="text-foreground">v{update.latestVersion}</span>
+ </div>
+ ) : (
+ presentation.detail && (
+ <PopoverDescription
+ className={cn(
+ 'text-xs',
+ presentation.tone === 'warning' && 'text-foreground-warning'
+ )}
+ >
+ {presentation.detail}
+ </PopoverDescription>
+ )
+ )}
+ </PopoverHeader>
+
+ {presentation.progressPercent !== null && update.state.status === 'downloading' && (
+ <Progress value={presentation.progressPercent} />
+ )}
+
+ {/* Stacked rather than side by side: the panel is narrower than the
+ sidebar, and the two labels do not fit on one row. */}
+ <div className="flex flex-col gap-2">
+ {presentation.actionLabel && (
+ <Button size="xs" variant="default" className="w-full" onClick={runAction}>
+ {ActionIcon && <ActionIcon className="size-3.5" />}
+ {presentation.actionLabel}
+ </Button>
+ )}
+
+ {update.latestVersion && (
+ <button
+ type="button"
+ onClick={() => void update.openReleasePage()}
+ className="inline-flex cursor-pointer items-center justify-center gap-1 text-xs text-foreground-passive underline-offset-2 hover:text-foreground hover:underline"
+ >
+ Release notes
+ <ExternalLink className="size-3" />
+ </button>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
);
});
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/update-store.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/update-store.ts
index 3b895894a..16381e8d9 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/update-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/update-store.ts
@@ -15,6 +15,7 @@ import {
updateNotAvailableEvent,
updateProgressEvent,
} from '@shared/events/updateEvents';
+import { switchdashReleaseUrl } from '@shared/urls';
const LAST_NOTIFIED_KEY = 'switchdash:update:lastNotified';
const SNOOZE_HOURS = 6;
@@ -26,10 +27,16 @@ type DownloadProgress = {
bytesPerSecond?: number;
};
+export type UpdateReleaseInfo = {
+ version: string;
+ releaseDate?: string;
+ releaseName?: string | null;
+};
+
export type UpdateState =
| { status: 'idle' }
| { status: 'checking' }
- | { status: 'available'; info?: { version: string } }
+ | { status: 'available'; info?: UpdateReleaseInfo }
| { status: 'not-available' }
| { status: 'downloading'; progress?: DownloadProgress }
| { status: 'downloaded' }
@@ -37,6 +44,65 @@ export type UpdateState =
| { status: 'error'; message: string }
| { status: 'auth-required' };
+/** Statuses where main is mid-flight and a fresh check would interrupt it. */
+const IN_FLIGHT_STATUSES: ReadonlySet<UpdateState['status']> = new Set([
+ 'downloading',
+ 'downloaded',
+ 'installing',
+]);
+
+/**
+ * Shape of the main-process update state, described structurally so the
+ * renderer does not import from @main. Keep in sync with UpdateState in
+ * src/main/core/updates/update-service.ts.
+ */
+type MainUpdateState = {
+ status:
+ | 'idle'
+ | 'checking'
+ | 'available'
+ | 'downloading'
+ | 'downloaded'
+ | 'installing'
+ | 'error'
+ | 'auth-required';
+ currentVersion: string;
+ availableVersion?: string;
+ updateInfo?: { version: string; releaseDate?: string; releaseName?: string | null };
+ downloadProgress?: DownloadProgress;
+ error?: string;
+};
+
+export function mainStateToRendererState(main: MainUpdateState): UpdateState {
+ switch (main.status) {
+ case 'checking':
+ return { status: 'checking' };
+ case 'available':
+ return {
+ status: 'available',
+ info: main.availableVersion
+ ? {
+ version: main.availableVersion,
+ releaseDate: main.updateInfo?.releaseDate,
+ releaseName: main.updateInfo?.releaseName,
+ }
+ : undefined,
+ };
+ case 'downloading':
+ return { status: 'downloading', progress: main.downloadProgress };
+ case 'downloaded':
+ return { status: 'downloaded' };
+ case 'installing':
+ return { status: 'installing' };
+ case 'error':
+ return { status: 'error', message: main.error || 'The update could not be completed.' };
+ case 'auth-required':
+ return { status: 'auth-required' };
+ default:
+ return { status: 'idle' };
+ }
+}
+
export class UpdateStore {
state: UpdateState = { status: 'idle' };
currentVersion = '';
@@ -50,6 +116,8 @@ export class UpdateStore {
setState: action,
hasUpdate: computed,
progressLabel: computed,
+ latestVersion: computed,
+ releaseUrl: computed,
});
}
@@ -68,6 +136,18 @@ export class UpdateStore {
return `${p.toFixed(0)}%`;
}
+ /** Version being offered/downloaded, independent of the current status. */
+ get latestVersion(): string | undefined {
+ if (this.state.status === 'available' && this.state.info?.version) {
+ return this.state.info.version;
+ }
+ return this.availableVersion;
+ }
+
+ get releaseUrl(): string {
+ return switchdashReleaseUrl(this.latestVersion);
+ }
+
start(): void {
void rpc.app.getAppVersion().then((v) => {
runInAction(() => {
@@ -84,7 +164,14 @@ export class UpdateStore {
events.on(updateAvailableEvent, (d) => {
runInAction(() => {
this.availableVersion = d.version;
- this.state = { status: 'available', info: { version: d.version } };
+ this.state = {
+ status: 'available',
+ info: {
+ version: d.version,
+ releaseDate: d.updateInfo?.releaseDate,
+ releaseName: d.updateInfo?.releaseName,
+ },
+ };
});
this._maybeToastAvailable(d.version);
});
@@ -115,8 +202,9 @@ export class UpdateStore {
});
});
- events.on(updateDownloadedEvent, () => {
+ events.on(updateDownloadedEvent, (d) => {
runInAction(() => {
+ if (d?.version) this.availableVersion = d.version;
this.state = { status: 'downloaded' };
});
});
@@ -140,10 +228,35 @@ export class UpdateStore {
});
events.on(menuCheckForUpdatesChannel, () => {
+ void this.check();
+ });
+
+ // Adopt whatever main already knows before kicking off a new check: a
+ // renderer reload during a download would otherwise show idle while the
+ // download continues in the background.
+ void this._resyncFromMain().then(() => {
+ if (IN_FLIGHT_STATUSES.has(this.state.status)) return;
rpc.update.check().catch(() => {});
});
+ }
+
+ private async _resyncFromMain(): Promise<void> {
+ try {
+ const res = await rpc.update.getState();
+ if (!res?.success || !res.data) return;
+ const main = res.data;
- rpc.update.check().catch(() => {});
+ runInAction(() => {
+ if (main.currentVersion && main.currentVersion !== 'unknown') {
+ this.currentVersion = main.currentVersion;
+ }
+ this.availableVersion = main.availableVersion;
+ this.state = mainStateToRendererState(main);
+ });
+ } catch {
+ // A failed resync is not itself an update failure — the check that
+ // follows will establish real state.
+ }
}
async check(): Promise<void> {
@@ -182,21 +295,14 @@ export class UpdateStore {
try {
const res = await rpc.update.download();
if (!res) {
- runInAction(() => {
- this.state = { status: 'error', message: 'Update API unavailable' };
- });
+ this._failUserAction('Update API unavailable');
return;
}
if (!res.success) {
- const message = res.error ?? 'Failed to download update';
- runInAction(() => {
- this.state = { status: 'error', message };
- });
+ this._failUserAction(res.error ?? 'Failed to download update');
}
} catch {
- runInAction(() => {
- this.state = { status: 'error', message: 'Failed to download update' };
- });
+ this._failUserAction('Failed to download update');
}
}
@@ -207,20 +313,14 @@ export class UpdateStore {
try {
const res = await rpc.update.quitAndInstall();
if (!res) {
- runInAction(() => {
- this.state = { status: 'error', message: 'Update API unavailable' };
- });
+ this._failUserAction('Update API unavailable');
return;
}
if (!res.success) {
- runInAction(() => {
- this.state = { status: 'error', message: res.error ?? 'Failed to install update' };
- });
+ this._failUserAction(res.error ?? 'Failed to install update');
}
} catch {
- runInAction(() => {
- this.state = { status: 'error', message: 'Failed to install update' };
- });
+ this._failUserAction('Failed to install update');
}
}
@@ -232,6 +332,28 @@ export class UpdateStore {
}
}
+ /** Open this update's GitHub release page in the user's browser. */
+ async openReleasePage(): Promise<void> {
+ const url = this.releaseUrl;
+ try {
+ await rpc.app.openExternal(url);
+ } catch {
+ toast.error('Could not open the release page', { description: url });
+ }
+ }
+
+ /**
+ * Record a failure the user personally triggered. Background check failures
+ * only tint the sidebar indicator; a click that fails gets a toast, because
+ * the user is waiting on an answer.
+ */
+ private _failUserAction(message: string): void {
+ runInAction(() => {
+ this.state = { status: 'error', message };
+ });
+ toast.error('Update failed', { description: message, duration: 8_000 });
+ }
+
private _maybeToastAvailable(version: string): void {
if (!this._shouldNotify(version)) return;
this._showAvailableToast(version);
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/ui/progress.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/ui/progress.tsx
index b18bfa35f..f7caacbd5 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/ui/progress.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/ui/progress.tsx
@@ -23,7 +23,7 @@ function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) {
return (
<ProgressPrimitive.Track
className={cn(
- 'relative flex h-1.5 w-full items-center overflow-x-hidden rounded-full bg-muted',
+ 'relative flex h-1.5 w-full items-center overflow-x-hidden rounded-full bg-border',
className
)}
data-slot="progress-track"
@@ -36,7 +36,7 @@ function ProgressIndicator({ className, ...props }: ProgressPrimitive.Indicator.
return (
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
- className={cn('h-full bg-primary transition-all', className)}
+ className={cn('h-full rounded-full bg-foreground-info transition-all', className)}
{...props}
/>
);
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/updates/update-presentation.test.ts b/dash/apps/switchdash-desktop/src/renderer/lib/updates/update-presentation.test.ts
new file mode 100644
index 000000000..e78b5c37d
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/updates/update-presentation.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from 'vitest';
+import type { UpdateState } from '@renderer/lib/stores/update-store';
+import { formatMegabytes, formatTransferRate, presentUpdate } from './update-presentation';
+
+const CURRENT = '0.17.1';
+
+function present(state: UpdateState) {
+ return presentUpdate(state, CURRENT);
+}
+
+describe('presentUpdate', () => {
+ it('shows the plain current version when there is nothing to do', () => {
+ const idle = present({ status: 'idle' });
+
+ expect(idle.tone).toBe('neutral');
+ expect(idle.indicatorLabel).toBe('v0.17.1');
+ expect(idle.indicatorIcon).toBe('none');
+ expect(idle.actionable).toBe(false);
+ expect(idle.progressPercent).toBeNull();
+ });
+
+ it('treats not-available the same as idle', () => {
+ expect(present({ status: 'not-available' })).toEqual(present({ status: 'idle' }));
+ });
+
+ it('advertises the target version rather than a bare "Update"', () => {
+ const available = present({ status: 'available', info: { version: '0.18.0' } });
+
+ expect(available.indicatorLabel).toBe('v0.18.0');
+ expect(available.detail).toBe('v0.17.1 → v0.18.0');
+ expect(available.actionKind).toBe('download');
+ expect(available.actionable).toBe(true);
+ });
+
+ it('still offers a download when the version is unknown', () => {
+ const available = present({ status: 'available' });
+
+ expect(available.indicatorLabel).toBe('Update');
+ expect(available.actionKind).toBe('download');
+ });
+
+ describe('the three mid-flight states read differently', () => {
+ const downloading = present({
+ status: 'downloading',
+ progress: {
+ percent: 42.4,
+ transferred: 13_000_000,
+ total: 71_000_000,
+ bytesPerSecond: 3_200_000,
+ },
+ });
+ const downloaded = present({ status: 'downloaded' });
+ const available = present({ status: 'available', info: { version: '0.18.0' } });
+
+ it('gives each a distinct indicator label', () => {
+ const labels = [
+ available.indicatorLabel,
+ downloading.indicatorLabel,
+ downloaded.indicatorLabel,
+ ];
+ expect(new Set(labels).size).toBe(3);
+ });
+
+ it('reports real progress numbers while downloading', () => {
+ expect(downloading.indicatorLabel).toBe('42%');
+ expect(downloading.progressPercent).toBeCloseTo(42.4);
+ expect(downloading.detail).toBe('12.4 MB of 67.7 MB · 3.1 MB/s');
+ expect(downloading.busy).toBe(true);
+ });
+
+ it('offers a restart once downloaded, and mentions the install-on-quit fallback', () => {
+ expect(downloaded.actionKind).toBe('restart');
+ expect(downloaded.tone).toBe('success');
+ expect(downloaded.busy).toBe(false);
+ expect(downloaded.detail).toMatch(/next time you quit/i);
+ });
+ });
+
+ it('degrades to a percentage when byte counts are missing', () => {
+ const downloading = present({ status: 'downloading', progress: { percent: 7 } });
+
+ expect(downloading.detail).toBe('7% downloaded');
+ expect(downloading.detail).not.toMatch(/NaN/);
+ });
+
+ it('handles a download that reports no progress at all', () => {
+ const downloading = present({ status: 'downloading' });
+
+ expect(downloading.indicatorLabel).toBe('0%');
+ expect(downloading.detail).toBe('0% downloaded');
+ });
+
+ it('locks out actions while installing', () => {
+ const installing = present({ status: 'installing' });
+
+ expect(installing.actionKind).toBe('none');
+ expect(installing.actionLabel).toBeNull();
+ expect(installing.busy).toBe(true);
+ expect(installing.actionable).toBe(false);
+ });
+
+ describe('failures', () => {
+ it('surfaces the real error message instead of a generic line', () => {
+ const failed = present({
+ status: 'error',
+ message: 'Update request failed with HTTP 503',
+ });
+
+ expect(failed.detail).toBe('Update request failed with HTTP 503');
+ expect(failed.tone).toBe('warning');
+ expect(failed.actionKind).toBe('retry');
+ });
+
+ it('falls back to a generic line only when no message was given', () => {
+ const failed = present({ status: 'error', message: '' });
+
+ expect(failed.detail).toBe('The update could not be completed.');
+ });
+
+ it('makes failures visible in the indicator', () => {
+ const failed = present({ status: 'error', message: 'boom' });
+
+ expect(failed.indicatorIcon).toBe('alert');
+ expect(failed.indicatorLabel).toBe('Update failed');
+ expect(failed.actionable).toBe(true);
+ });
+
+ it('treats missing credentials as a fixable prompt, not a failure', () => {
+ const auth = present({ status: 'auth-required' });
+
+ expect(auth.title).toMatch(/sign in/i);
+ expect(auth.detail).toMatch(/gh auth login/);
+ expect(auth.actionKind).toBe('check');
+ });
+ });
+
+ it('never renders an empty indicator label once a version is known', () => {
+ const states: UpdateState[] = [
+ { status: 'idle' },
+ { status: 'checking' },
+ { status: 'available', info: { version: '0.18.0' } },
+ { status: 'not-available' },
+ { status: 'downloading', progress: { percent: 1 } },
+ { status: 'downloaded' },
+ { status: 'installing' },
+ { status: 'error', message: 'x' },
+ { status: 'auth-required' },
+ ];
+
+ for (const state of states) {
+ expect(present(state).indicatorLabel, state.status).not.toBe('');
+ }
+ });
+});
+
+describe('byte formatting', () => {
+ it('formats megabytes to one decimal', () => {
+ expect(formatMegabytes(0)).toBe('0.0 MB');
+ expect(formatMegabytes(1024 * 1024)).toBe('1.0 MB');
+ expect(formatMegabytes(71_000_000)).toBe('67.7 MB');
+ });
+
+ it('omits a rate when the updater reports zero', () => {
+ expect(formatTransferRate(0)).toBe('');
+ expect(formatTransferRate(-1)).toBe('');
+ expect(formatTransferRate(3_200_000)).toBe('3.1 MB/s');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/updates/update-presentation.ts b/dash/apps/switchdash-desktop/src/renderer/lib/updates/update-presentation.ts
new file mode 100644
index 000000000..a2e1c6726
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/updates/update-presentation.ts
@@ -0,0 +1,200 @@
+import type { UpdateState } from '@renderer/lib/stores/update-store';
+import { PRODUCT_NAME } from '@shared/app-identity';
+
+/**
+ * Single source of truth for how an update status reads to the user.
+ *
+ * The sidebar indicator, its panel, and the Settings card all render from this
+ * one mapping. They previously each derived their own copy from the raw status
+ * and drifted apart — the sidebar collapsed three statuses into one label while
+ * Settings distinguished them.
+ */
+
+export type UpdateTone = 'neutral' | 'info' | 'success' | 'warning';
+
+export type UpdateIndicatorIcon = 'none' | 'available' | 'downloading' | 'restart' | 'alert';
+
+export type UpdateActionKind = 'none' | 'download' | 'restart' | 'retry' | 'check';
+
+export interface UpdatePresentation {
+ tone: UpdateTone;
+ /** Compact text for the always-visible sidebar indicator. */
+ indicatorLabel: string;
+ indicatorIcon: UpdateIndicatorIcon;
+ /** True when the indicator represents something the user can act on. */
+ actionable: boolean;
+ /** Heading inside the panel and the Settings card. */
+ title: string;
+ /** Supporting line; null when the title says everything. */
+ detail: string | null;
+ actionKind: UpdateActionKind;
+ actionLabel: string | null;
+ /** True while work is in flight, so surfaces can show a spinner. */
+ busy: boolean;
+ /** 0-100 while downloading, else null. */
+ progressPercent: number | null;
+}
+
+const BYTES_PER_MB = 1024 * 1024;
+
+export function formatMegabytes(bytes: number): string {
+ return `${(bytes / BYTES_PER_MB).toFixed(1)} MB`;
+}
+
+export function formatTransferRate(bytesPerSecond: number): string {
+ if (bytesPerSecond <= 0) return '';
+ return `${(bytesPerSecond / BYTES_PER_MB).toFixed(1)} MB/s`;
+}
+
+/**
+ * Build the download detail line from whatever the progress event carried.
+ * electron-updater does not guarantee every field, so each part is optional and
+ * the line degrades to just a percentage rather than rendering "NaN MB".
+ */
+function describeDownload(progress: {
+ percent?: number;
+ transferred?: number;
+ total?: number;
+ bytesPerSecond?: number;
+}): string {
+ const parts: string[] = [];
+
+ if (typeof progress.transferred === 'number' && typeof progress.total === 'number') {
+ parts.push(`${formatMegabytes(progress.transferred)} of ${formatMegabytes(progress.total)}`);
+ }
+
+ if (typeof progress.bytesPerSecond === 'number') {
+ const rate = formatTransferRate(progress.bytesPerSecond);
+ if (rate) parts.push(rate);
+ }
+
+ if (parts.length === 0) {
+ return `${Math.round(progress.percent ?? 0)}% downloaded`;
+ }
+
+ return parts.join(' · ');
+}
+
+export function presentUpdate(state: UpdateState, currentVersion: string): UpdatePresentation {
+ const current = currentVersion ? `v${currentVersion}` : 'this version';
+
+ switch (state.status) {
+ case 'checking':
+ return {
+ tone: 'neutral',
+ indicatorLabel: currentVersion ? `v${currentVersion}` : '',
+ indicatorIcon: 'none',
+ actionable: false,
+ title: 'Checking for updates',
+ detail: null,
+ actionKind: 'none',
+ actionLabel: null,
+ busy: true,
+ progressPercent: null,
+ };
+
+ case 'available': {
+ const next = state.info?.version;
+ return {
+ tone: 'info',
+ indicatorLabel: next ? `v${next}` : 'Update',
+ indicatorIcon: 'available',
+ actionable: true,
+ title: 'Update available',
+ detail: next ? `${current} → v${next}` : 'A new version is available.',
+ actionKind: 'download',
+ actionLabel: 'Download update',
+ busy: false,
+ progressPercent: null,
+ };
+ }
+
+ case 'downloading': {
+ const percent = state.progress?.percent ?? 0;
+ return {
+ tone: 'info',
+ indicatorLabel: `${Math.round(percent)}%`,
+ indicatorIcon: 'downloading',
+ actionable: true,
+ title: 'Downloading update',
+ detail: describeDownload(state.progress ?? {}),
+ actionKind: 'none',
+ actionLabel: null,
+ busy: true,
+ progressPercent: percent,
+ };
+ }
+
+ case 'downloaded':
+ return {
+ tone: 'success',
+ indicatorLabel: 'Restart to update',
+ indicatorIcon: 'restart',
+ actionable: true,
+ title: 'Update ready to install',
+ detail: `Restart to finish installing, or ${PRODUCT_NAME} will apply it next time you quit.`,
+ actionKind: 'restart',
+ actionLabel: 'Restart now',
+ busy: false,
+ progressPercent: 100,
+ };
+
+ case 'installing':
+ return {
+ tone: 'success',
+ indicatorLabel: 'Installing',
+ indicatorIcon: 'restart',
+ actionable: false,
+ title: 'Installing update',
+ detail: `${PRODUCT_NAME} will close and restart automatically. This may take a few seconds.`,
+ actionKind: 'none',
+ actionLabel: null,
+ busy: true,
+ progressPercent: 100,
+ };
+
+ case 'error':
+ return {
+ tone: 'warning',
+ indicatorLabel: 'Update failed',
+ indicatorIcon: 'alert',
+ actionable: true,
+ title: 'Update failed',
+ // Surface the real reason. The generic line is only a fallback for an
+ // empty message — never a replacement for one we were given.
+ detail: state.message || 'The update could not be completed.',
+ actionKind: 'retry',
+ actionLabel: 'Try again',
+ busy: false,
+ progressPercent: null,
+ };
+
+ case 'auth-required':
+ return {
+ tone: 'warning',
+ indicatorLabel: 'Sign in for updates',
+ indicatorIcon: 'alert',
+ actionable: true,
+ title: 'Sign in to GitHub for updates',
+ detail: 'Run `gh auth login` in a terminal, then check again.',
+ actionKind: 'check',
+ actionLabel: 'Check again',
+ busy: false,
+ progressPercent: null,
+ };
+
+ default:
+ return {
+ tone: 'neutral',
+ indicatorLabel: currentVersion ? `v${currentVersion}` : '',
+ indicatorIcon: 'none',
+ actionable: false,
+ title: `${PRODUCT_NAME} is up to date`,
+ detail: currentVersion ? `You are on ${current}.` : null,
+ actionKind: 'check',
+ actionLabel: 'Check for updates',
+ busy: false,
+ progressPercent: null,
+ };
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/shared/urls.ts b/dash/apps/switchdash-desktop/src/shared/urls.ts
index b139f3b37..8e3a78e77 100644
--- a/dash/apps/switchdash-desktop/src/shared/urls.ts
+++ b/dash/apps/switchdash-desktop/src/shared/urls.ts
@@ -1,4 +1,14 @@
export const SWITCHDASH_RELEASES_URL = 'https://github.com/sandbox-quantum/switch/releases';
+
+/**
+ * Release page for one specific version. Falls back to the releases index when
+ * the version is unknown, so the link is never dead.
+ */
+export function switchdashReleaseUrl(version: string | undefined): string {
+ if (!version) return SWITCHDASH_RELEASES_URL;
+ const tag = version.startsWith('v') ? version : `v${version}`;
+ return `${SWITCHDASH_RELEASES_URL}/tag/${tag}`;
+}
export const SWITCHDASH_DOCS_URL = 'https://github.com/sandbox-quantum/switch';
export const SWITCHDASH_ISSUES_URL = 'https://github.com/sandbox-quantum/switch/issues';
export const SWITCHDASH_ISSUES_NEW_URL =