Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(desktop): probe update download source (#509)

Laodouuu304d519c5480
diff --git a/packages/desktop/src/update-source.ts b/packages/desktop/src/update-source.ts
new file mode 100644
index 00000000..14c8a29c
--- /dev/null
+++ b/packages/desktop/src/update-source.ts
@@ -0,0 +1,364 @@
+/**
+ * Update-source selection for the desktop auto-updater.
+ *
+ * This module owns the same source-neutral speed-probe contract the release installers
+ * and download page use: fix the target tag first, read that tag's
+ * release-download-manifest.tsv, prove both sources can serve the shared probe file, and
+ * then compare the large probe using the current installer rule. GitHub is the free
+ * source: it wins outright at or above the minimum speed, and the OSS mirror takes over
+ * only when GitHub misses that minimum and OSS is clearly faster.
+ *
+ * The desktop default feed is still the GitHub Releases feed electron-builder publishes.
+ * An inconclusive test never blocks updates; the caller keeps that default.
+ */
+import { createHash } from "node:crypto";
+
+export const OSS_ORIGIN = "https://penguin-harness-releases.oss-cn-beijing.aliyuncs.com";
+export const OSS_RELEASE_ROOT = `${OSS_ORIGIN}/releases`;
+export const GITHUB_RELEASE_ROOT =
+ "https://github.com/Prism-Shadow/penguin-harness/releases/download";
+export const OSS_LATEST_JSON_URL = `${OSS_ORIGIN}/latest.json`;
+
+/** Same contract as the release installers (install.sh / install.ps1). */
+export const SPEED_PROBE_MANIFEST_TIMEOUT_SECONDS = 5;
+export const SPEED_PROBE_SMALL_TIMEOUT_SECONDS = 5;
+export const SPEED_PROBE_LARGE_TIMEOUT_SECONDS = 8;
+export const SPEED_PROBE_TOTAL_TIMEOUT_SECONDS = 26;
+export const SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND = 262144;
+export const SPEED_PROBE_OSS_SWITCH_RATIO = 1.5;
+
+/** Minimal structural slice of fetch so callers can inject Electron's net.fetch or a fake. */
+export interface ProbeFetchInit {
+ headers: Record<string, string>;
+ signal: AbortSignal;
+}
+
+export interface ProbeResponse {
+ ok: boolean;
+ status: number;
+ headers: { get(name: string): string | null };
+ arrayBuffer(): Promise<ArrayBuffer>;
+}
+
+export type FetchFn = (url: string, init: ProbeFetchInit) => Promise<ProbeResponse>;
+
+export interface ReleaseProbe {
+ name: string;
+ size: number;
+ sha256: string;
+}
+
+export interface ReleaseDownloadManifest {
+ smallProbe: ReleaseProbe;
+ largeProbe: ReleaseProbe;
+ /** Integrity check that the manifest belongs to a release carrying this update asset. */
+ assetSize: number;
+}
+
+/** The update asset electron-updater replaces on this platform (dmg is manual-only). */
+export function desktopUpdateAssetName(platform: NodeJS.Platform, arch: string): string | null {
+ if (platform === "darwin") {
+ return arch === "arm64" || arch === "x64" ? `penguin-desktop-darwin-${arch}.zip` : null;
+ }
+ if (platform === "win32") {
+ return arch === "x64" ? "penguin-desktop-win32-x64.exe" : null;
+ }
+ if (platform === "linux") {
+ return arch === "x64" ? "penguin-desktop-linux-x86_64.AppImage" : null;
+ }
+ return null;
+}
+
+/** Generic-provider feed base for the OSS mirror's immutable tag directory. */
+export function ossFeedUrl(tag: string): string {
+ return `${OSS_RELEASE_ROOT}/${tag}/`;
+}
+
+/** Generic-provider feed base for the same tag on GitHub Releases. */
+export function githubFeedUrl(tag: string): string {
+ return `${GITHUB_RELEASE_ROOT}/${tag}/`;
+}
+
+export type FeedLabel = "OSS mirror" | "GitHub" | "configured mirror";
+
+export function feedLabel(url: string): FeedLabel {
+ try {
+ const host = new URL(url).host;
+ if (host.endsWith(".aliyuncs.com")) return "OSS mirror";
+ if (host === "github.com") return "GitHub";
+ } catch {
+ // fall through: an unparseable feed keeps the neutral label
+ }
+ return "configured mirror";
+}
+
+/**
+ * Resolves the OSS mirror's latest immutable tag, validated exactly like the installers
+ * and the download page validate latest.json: schema 1, a safe v-tag, and a
+ * releaseBaseUrl that names the expected bucket path (metadata cannot redirect the feed
+ * to an arbitrary host).
+ */
+export async function resolveOssLatestTag(fetchFn: FetchFn): Promise<string | null> {
+ let response: ProbeResponse;
+ try {
+ response = await fetchFn(OSS_LATEST_JSON_URL, {
+ headers: {},
+ signal: AbortSignal.timeout(8_000),
+ });
+ } catch {
+ return null;
+ }
+ if (!response.ok) return null;
+ try {
+ const body: unknown = JSON.parse(new TextDecoder().decode(await response.arrayBuffer()));
+ if (typeof body !== "object" || body === null) return null;
+ const { schemaVersion, tag, releaseBaseUrl } = body as {
+ schemaVersion?: unknown;
+ tag?: unknown;
+ releaseBaseUrl?: unknown;
+ };
+ if (schemaVersion !== 1 || typeof tag !== "string") return null;
+ if (!/^v[0-9A-Za-z][0-9A-Za-z._-]*$/.test(tag)) return null;
+ if (releaseBaseUrl !== `${OSS_RELEASE_ROOT}/${tag}`) return null;
+ return tag;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Fetches and strictly validates the release-download-manifest.tsv for the fixed tag
+ * (OSS first, then GitHub, each capped by the shared budget). Only the probe rows and the
+ * current platform's desktop_asset size are needed — the updater still trusts Electron's
+ * latest*.yml feeds for the update itself.
+ */
+export async function loadReleaseDownloadManifest(opts: {
+ fetchFn: FetchFn;
+ tag: string;
+ assetName: string;
+ deadlineMs: number;
+}): Promise<ReleaseDownloadManifest | null> {
+ const { fetchFn, tag, assetName, deadlineMs } = opts;
+ const timeoutMs = remainingTimeout(deadlineMs, SPEED_PROBE_MANIFEST_TIMEOUT_SECONDS);
+ if (timeoutMs <= 0) return null;
+
+ let text: string | null = null;
+ for (const base of [`${OSS_RELEASE_ROOT}/${tag}`, `${GITHUB_RELEASE_ROOT}/${tag}`]) {
+ try {
+ const response = await fetchFn(`${base}/release-download-manifest.tsv`, {
+ headers: {},
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (response.ok) text = new TextDecoder().decode(await response.arrayBuffer());
+ } catch {
+ // try the other source
+ }
+ if (text !== null) break;
+ }
+ if (text === null) return null;
+
+ const lines = text.split(/\r?\n/);
+ if (lines.at(-1) === "") lines.pop();
+ if (lines.length < 4) return null;
+ if (lines[0] !== `penguin-release-download-manifest\t1\t${tag}`) return null;
+
+ let smallProbe: ReleaseProbe | null = null;
+ let largeProbe: ReleaseProbe | null = null;
+ let assetSize: number | null = null;
+ for (const line of lines.slice(1)) {
+ const parts = line.split("\t");
+ if (parts[0] === "probe" && parts.length === 5) {
+ const probe = parseProbeRow(parts[1]!, parts[2]!, parts[3]!, parts[4]!);
+ if (probe === null) return null;
+ if (parts[1] === "small") smallProbe = probe;
+ if (parts[1] === "large") largeProbe = probe;
+ } else if (parts[0] === "desktop_asset" && parts.length === 4 && parts[1] === assetName) {
+ const size = parsePositiveSize(parts[2]!);
+ if (size === null) return null;
+ assetSize = size;
+ }
+ }
+ if (smallProbe === null || largeProbe === null || assetSize === null) return null;
+ return { smallProbe, largeProbe, assetSize };
+}
+
+function parseProbeRow(
+ label: string,
+ name: string,
+ size: string,
+ hash: string,
+): ReleaseProbe | null {
+ if (label !== "small" && label !== "large") return null;
+ if (!/^[A-Za-z0-9._+-]+$/.test(name) || name.includes("..")) return null;
+ const parsedSize = parsePositiveSize(size);
+ if (parsedSize === null) return null;
+ if (!/^[0-9a-f]{64}$/.test(hash)) return null;
+ return { name, size: parsedSize, sha256: hash };
+}
+
+function parsePositiveSize(raw: string): number | null {
+ if (!/^[1-9][0-9]*$/.test(raw)) return null;
+ const value = Number(raw);
+ return Number.isSafeInteger(value) ? value : null;
+}
+
+export interface ProbeResult {
+ ok: boolean;
+ /** Whole-body throughput in bytes/second; only computed when wantSpeed is set. */
+ speedBps?: number;
+}
+
+function probeSpeed(result: ProbeResult): number {
+ return result.ok && result.speedBps !== undefined ? result.speedBps : 0;
+}
+
+export function selectMeasuredSource(githubBps: number, ossBps: number): "github" | "oss" {
+ if (githubBps >= SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND) return "github";
+ return ossBps > githubBps * SPEED_PROBE_OSS_SWITCH_RATIO ? "oss" : "github";
+}
+
+/**
+ * Downloads one probe within the shared budget. Success requires a 2xx status, no
+ * non-identity content encoding, an exact byte count and a matching sha256 — the same
+ * success criteria the installers use.
+ */
+export async function probeSource(opts: {
+ fetchFn: FetchFn;
+ base: string;
+ probe: ReleaseProbe;
+ deadlineMs: number;
+ maxTimeoutSeconds: number;
+ wantSpeed: boolean;
+}): Promise<ProbeResult> {
+ const timeoutMs = remainingTimeout(opts.deadlineMs, opts.maxTimeoutSeconds);
+ if (timeoutMs <= 0) return { ok: false };
+ const startedAt = Date.now();
+ try {
+ const response = await opts.fetchFn(`${opts.base}/${opts.probe.name}`, {
+ headers: { "accept-encoding": "identity" },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!response.ok) return { ok: false };
+ const encoding = response.headers.get("content-encoding");
+ if (encoding !== null && encoding.toLowerCase() !== "identity") return { ok: false };
+ const body = new Uint8Array(await response.arrayBuffer());
+ if (body.byteLength !== opts.probe.size) return { ok: false };
+ if (createHash("sha256").update(body).digest("hex") !== opts.probe.sha256) {
+ return { ok: false };
+ }
+ if (!opts.wantSpeed) return { ok: true };
+ const seconds = Math.max((Date.now() - startedAt) / 1000, 0.001);
+ return { ok: true, speedBps: Math.floor(body.byteLength / seconds) };
+ } catch {
+ return { ok: false };
+ }
+}
+
+function remainingTimeout(deadlineMs: number, maxSeconds: number): number {
+ const remaining = deadlineMs - Date.now();
+ if (remaining <= 0) return 0;
+ return Math.min(maxSeconds * 1000, remaining);
+}
+
+export type FeedDecision =
+ /** Keep electron-updater's default GitHub Releases feed (no setFeedURL). */
+ | { kind: "keep-github"; reason: string }
+ /** Pin generic feeds: primary now, same-tag fallback on a failed check. */
+ | { kind: "pinned"; primaryUrl: string; fallbackUrl: string };
+
+export interface SelectAutoUpdateFeedOptions {
+ fetchFn: FetchFn;
+ platform: NodeJS.Platform;
+ arch: string;
+ log: (line: string) => void;
+ /** Total probe budget as a duration in ms; tests can stretch or exhaust it. */
+ budgetMs?: number;
+}
+
+/**
+ * The auto-mode selection tree. It mirrors the installers' current rule while keeping
+ * the desktop's default GitHub feed on inconclusive input.
+ */
+export async function selectAutoUpdateFeed(
+ opts: SelectAutoUpdateFeedOptions,
+): Promise<FeedDecision> {
+ const { fetchFn, platform, arch, log } = opts;
+ const deadlineMs = Date.now() + (opts.budgetMs ?? SPEED_PROBE_TOTAL_TIMEOUT_SECONDS * 1000);
+
+ const inconclusive = (): FeedDecision => {
+ log("Download source test was inconclusive; keeping GitHub update feed.");
+ return { kind: "keep-github", reason: "inconclusive" };
+ };
+
+ const assetName = desktopUpdateAssetName(platform, arch);
+ if (assetName === null) return inconclusive();
+
+ const tag = await resolveOssLatestTag(fetchFn);
+ if (tag === null) return inconclusive();
+
+ const manifest = await loadReleaseDownloadManifest({ fetchFn, tag, assetName, deadlineMs });
+ if (manifest === null) return inconclusive();
+
+ log("Testing OSS mirror and GitHub download sources ...");
+ const ossBase = `${OSS_RELEASE_ROOT}/${tag}`;
+ const githubBase = `${GITHUB_RELEASE_ROOT}/${tag}`;
+
+ const [ossSmall, githubSmall] = await Promise.all([
+ probeSource({
+ fetchFn,
+ base: ossBase,
+ probe: manifest.smallProbe,
+ deadlineMs,
+ maxTimeoutSeconds: SPEED_PROBE_SMALL_TIMEOUT_SECONDS,
+ wantSpeed: false,
+ }),
+ probeSource({
+ fetchFn,
+ base: githubBase,
+ probe: manifest.smallProbe,
+ deadlineMs,
+ maxTimeoutSeconds: SPEED_PROBE_SMALL_TIMEOUT_SECONDS,
+ wantSpeed: false,
+ }),
+ ]);
+
+ if (!ossSmall.ok && githubSmall.ok) {
+ log("Selected GitHub (OSS mirror probe unavailable).");
+ return { kind: "pinned", primaryUrl: githubFeedUrl(tag), fallbackUrl: ossFeedUrl(tag) };
+ }
+ if (ossSmall.ok && !githubSmall.ok) {
+ log("Selected OSS mirror (GitHub probe unavailable).");
+ return { kind: "pinned", primaryUrl: ossFeedUrl(tag), fallbackUrl: githubFeedUrl(tag) };
+ }
+ if (!ossSmall.ok && !githubSmall.ok) return inconclusive();
+
+ const githubLarge = await probeSource({
+ fetchFn,
+ base: githubBase,
+ probe: manifest.largeProbe,
+ deadlineMs,
+ maxTimeoutSeconds: SPEED_PROBE_LARGE_TIMEOUT_SECONDS,
+ wantSpeed: true,
+ });
+ const githubSpeed = probeSpeed(githubLarge);
+ if (githubSpeed >= SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND) {
+ log("Selected GitHub (meets minimum download speed).");
+ return { kind: "pinned", primaryUrl: githubFeedUrl(tag), fallbackUrl: ossFeedUrl(tag) };
+ }
+
+ const ossLarge = await probeSource({
+ fetchFn,
+ base: ossBase,
+ probe: manifest.largeProbe,
+ deadlineMs,
+ maxTimeoutSeconds: SPEED_PROBE_LARGE_TIMEOUT_SECONDS,
+ wantSpeed: true,
+ });
+ const ossSpeed = probeSpeed(ossLarge);
+ if (selectMeasuredSource(githubSpeed, ossSpeed) === "oss") {
+ log("Selected OSS mirror (clearly faster than GitHub here).");
+ return { kind: "pinned", primaryUrl: ossFeedUrl(tag), fallbackUrl: githubFeedUrl(tag) };
+ }
+ log("Selected GitHub (the OSS mirror was not enough faster to be worth switching).");
+ return { kind: "pinned", primaryUrl: githubFeedUrl(tag), fallbackUrl: ossFeedUrl(tag) };
+}
diff --git a/packages/desktop/src/update-support.ts b/packages/desktop/src/update-support.ts
index a5276959..f2bd0266 100644
--- a/packages/desktop/src/update-support.ts
+++ b/packages/desktop/src/update-support.ts
@@ -26,10 +26,10 @@ export function updateSupport(opts: {
}
/**
- * Optional feed override (`PENGUIN_UPDATE_FEED_URL`), the seed of the documented
- * auto | oss | github source switch and what makes an end-to-end update test possible
- * against a local server. Returns null when unset or unparseable — an unusable override
- * must not silently redirect updates, so the caller keeps the default GitHub feed.
+ * Optional feed override (`PENGUIN_UPDATE_FEED_URL`), what makes an end-to-end update
+ * test possible against a local server. Returns null when unset or unparseable — an
+ * unusable override must not silently redirect updates, so the caller keeps the default
+ * GitHub feed.
*/
export function feedUrlOverride(env: NodeJS.ProcessEnv): string | null {
const raw = env.PENGUIN_UPDATE_FEED_URL?.trim();
@@ -42,3 +42,46 @@ export function feedUrlOverride(env: NodeJS.ProcessEnv): string | null {
return null;
}
}
+
+export type UpdateSource = "auto" | "oss" | "github";
+
+/**
+ * Desktop update source switches. The names are deliberately separate from the installer's
+ * PENGUIN_DOWNLOAD_* variables so a CLI-install setting never leaks into the app's
+ * background updater.
+ */
+export interface UpdateSourceConfig {
+ source: UpdateSource;
+ probe: boolean;
+ /** PENGUIN_UPDATE_SOURCE was set but not one of auto | oss | github. */
+ invalidSource: boolean;
+ /** PENGUIN_UPDATE_SPEED_PROBE was set but not 0 or 1. */
+ invalidProbe: boolean;
+}
+
+export function updateSourceConfig(env: NodeJS.ProcessEnv): UpdateSourceConfig {
+ const rawSource = env.PENGUIN_UPDATE_SOURCE?.trim() ?? "";
+ let source: UpdateSource = "auto";
+ let invalidSource = false;
+ if (rawSource !== "") {
+ if (rawSource === "auto" || rawSource === "oss" || rawSource === "github") {
+ source = rawSource;
+ } else {
+ invalidSource = true;
+ }
+ }
+
+ const rawProbe = env.PENGUIN_UPDATE_SPEED_PROBE?.trim() ?? "";
+ let probe = true;
+ let invalidProbe = false;
+ if (rawProbe !== "") {
+ if (rawProbe === "0") {
+ probe = false;
+ } else if (rawProbe === "1") {
+ probe = true;
+ } else {
+ invalidProbe = true;
+ }
+ }
+ return { source, probe, invalidSource, invalidProbe };
+}
diff --git a/packages/desktop/src/updater.ts b/packages/desktop/src/updater.ts
index 79f84de6..be601d4e 100644
--- a/packages/desktop/src/updater.ts
+++ b/packages/desktop/src/updater.ts
@@ -19,11 +19,18 @@
* gates only apply to signed release builds. Linux AppImage continues without
* code-signing for now.
*/
-import { app, dialog, shell } from "electron";
+import { app, dialog, net, shell } from "electron";
import type { BrowserWindow } from "electron";
import electronUpdater from "electron-updater";
import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";
-import { feedUrlOverride, updateSupport } from "./update-support.js";
+import { feedUrlOverride, updateSourceConfig, updateSupport } from "./update-support.js";
+import {
+ feedLabel,
+ ossFeedUrl,
+ resolveOssLatestTag,
+ selectAutoUpdateFeed,
+} from "./update-source.js";
+import type { FetchFn } from "./update-source.js";
import { initialUpdateStatus, nextUpdateStatus } from "./updater-status.js";
import type { UpdaterEvent } from "./updater-status.js";
@@ -35,6 +42,11 @@ const FIRST_CHECK_DELAY_MS = 20_000;
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
const RELEASES_URL = "https://github.com/Prism-Shadow/penguin-harness/releases";
+const GITHUB_FEED = {
+ provider: "github" as const,
+ owner: "Prism-Shadow",
+ repo: "penguin-harness",
+};
function log(line: string): void {
process.stdout.write(`[updater] ${line}\n`);
@@ -42,6 +54,110 @@ function log(line: string): void {
let manualCheckInFlight = false;
let downloadedVersion: string | null = null;
+let downloadInFlight = false;
+
+type FeedState =
+ { phase: "pending" } | { phase: "unavailable" } | { phase: "ready"; fallbackUrl: string | null };
+let feedState: FeedState = { phase: "pending" };
+type FeedRefreshMode = "static" | "github" | "oss" | "auto-probe";
+let feedRefreshMode: FeedRefreshMode = "github";
+let feedRefreshInFlight: Promise<void> | null = null;
+/** The generic URL electron-updater currently points at (null = default GitHub feed). */
+let activeGenericUrl: string | null = null;
+/** The other pinned feed: retrying switches to it, and the pair swaps roles. */
+let otherGenericUrl: string | null = null;
+
+/** fetch for update-source.ts: Electron's proxy-aware network stack, same as updater downloads. */
+const fetchForUpdateSource: FetchFn = (url, init) =>
+ net.fetch(url, { headers: init.headers, signal: init.signal });
+
+function setGenericFeed(url: string, fallbackUrl: string | null): void {
+ activeGenericUrl = url;
+ otherGenericUrl = fallbackUrl;
+ feedState = { phase: "ready", fallbackUrl };
+ autoUpdater.setFeedURL({ provider: "generic", url });
+}
+
+function setGitHubFeed(): void {
+ activeGenericUrl = null;
+ otherGenericUrl = null;
+ feedState = { phase: "ready", fallbackUrl: null };
+ autoUpdater.setFeedURL(GITHUB_FEED);
+}
+
+function switchToFallbackFeed(reason: string): boolean {
+ if (downloadedVersion !== null || feedState.phase !== "ready" || feedState.fallbackUrl === null) {
+ return false;
+ }
+ const previous = activeGenericUrl;
+ const next = feedState.fallbackUrl;
+ activeGenericUrl = next;
+ otherGenericUrl = previous;
+ feedState = { phase: "ready", fallbackUrl: null };
+ autoUpdater.setFeedURL({ provider: "generic", url: next });
+ log(`${feedLabel(previous ?? next)} update ${reason}; retrying ${feedLabel(next)}`);
+ return true;
+}
+
+function refreshUpdateFeed(): Promise<void> {
+ if (feedRefreshInFlight !== null) return feedRefreshInFlight;
+ feedRefreshInFlight = refreshUpdateFeedOnce().finally(() => {
+ feedRefreshInFlight = null;
+ });
+ return feedRefreshInFlight;
+}
+
+async function refreshUpdateFeedOnce(): Promise<void> {
+ if (feedRefreshMode === "static") return;
+ if (feedRefreshMode === "github") {
+ setGitHubFeed();
+ return;
+ }
+
+ feedState = { phase: "pending" };
+ if (feedRefreshMode === "oss") {
+ try {
+ const tag = await resolveOssLatestTag(fetchForUpdateSource);
+ if (tag === null) {
+ feedState = { phase: "unavailable" };
+ log(
+ "PENGUIN_UPDATE_SOURCE=oss but the OSS mirror latest.json is unavailable or invalid; updates are disabled for this check.",
+ );
+ return;
+ }
+ setGenericFeed(ossFeedUrl(tag), null);
+ log(`selected OSS update feed (${tag})`);
+ } catch {
+ feedState = { phase: "unavailable" };
+ log("OSS update source selection failed; updates are disabled for this check.");
+ }
+ return;
+ }
+
+ try {
+ const decision = await selectAutoUpdateFeed({
+ fetchFn: fetchForUpdateSource,
+ platform: process.platform,
+ arch: process.arch,
+ log,
+ });
+ if (decision.kind === "pinned") {
+ setGenericFeed(decision.primaryUrl, decision.fallbackUrl);
+ log(`selected ${feedLabel(decision.primaryUrl)} update feed`);
+ } else {
+ setGitHubFeed();
+ log("selected GitHub update feed");
+ }
+ } catch (err) {
+ setGitHubFeed();
+ log(`update source selection failed: ${(err as Error).message}; keeping GitHub update feed.`);
+ }
+}
+
+function scheduleChecks(): void {
+ setTimeout(() => void check(), FIRST_CHECK_DELAY_MS).unref();
+ setInterval(() => void check(), CHECK_INTERVAL_MS).unref();
+}
// --- status relay (the account-menu row's data source) -----------------------
@@ -65,6 +181,25 @@ function reannounceStatus(): void {
for (const listener of statusListeners) listener(status);
}
+function reportUpdaterError(err: Error): void {
+ emitStatus({ kind: "error", message: err.message });
+ if (manualCheckInFlight) {
+ manualCheckInFlight = false;
+ void dialog
+ .showMessageBox({
+ type: "error",
+ message: "Could not check for updates.",
+ detail: `${err.message}\n\nYou can always download the latest release manually.`,
+ buttons: ["Open Releases", "OK"],
+ defaultId: 1,
+ cancelId: 1,
+ })
+ .then((r) => {
+ if (r.response === 0) void shell.openExternal(RELEASES_URL);
+ });
+ }
+}
+
/** Current snapshot, for the initial push after a server (re)start. */
export function getUpdaterStatus(): DesktopUpdateStatus {
return status;
@@ -102,6 +237,10 @@ export function handleUpdaterCommand(action: "check" | "install"): void {
reannounceStatus();
return;
}
+ if (feedState.phase === "pending") {
+ reannounceStatus();
+ return;
+ }
void check();
return;
}
@@ -137,21 +276,13 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
return;
}
- // Background downloads, explicit install: the user decides when to restart. Quitting
- // normally must NOT swap the app underneath a running server, so install happens only
- // through the dialog's own path.
- autoUpdater.autoDownload = true;
+ // Background downloads, explicit install: the user decides when to restart. The
+ // download is still started immediately after update-available; keeping the trigger
+ // here lets a failed package download retry the same tag on the fallback feed.
+ autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
autoUpdater.logger = null;
- const override = feedUrlOverride(process.env);
- if (override) {
- // Generic provider: also the shape the documented auto | oss | github source switch
- // will use for the OSS mirror.
- autoUpdater.setFeedURL({ provider: "generic", url: override });
- log(`feed override: ${override}`);
- }
-
autoUpdater.on("checking-for-update", () => {
log("checking");
emitStatus({ kind: "checking" });
@@ -172,6 +303,7 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
autoUpdater.on("update-available", (info: { version: string }) => {
log(`update available: ${info.version} (downloading)`);
emitStatus({ kind: "available", version: info.version });
+ void downloadUpdateWithFallback();
if (manualCheckInFlight) {
manualCheckInFlight = false;
void dialog.showMessageBox({
@@ -195,35 +327,81 @@ export function initUpdater(getWindow: () => BrowserWindow | null): void {
});
autoUpdater.on("error", (err: Error) => {
log(`error: ${err.message}`);
- emitStatus({ kind: "error", message: err.message });
- if (manualCheckInFlight) {
- manualCheckInFlight = false;
- void dialog
- .showMessageBox({
- type: "error",
- message: "Could not check for updates.",
- detail: `${err.message}\n\nYou can always download the latest release manually.`,
- buttons: ["Open Releases", "OK"],
- defaultId: 1,
- cancelId: 1,
- })
- .then((r) => {
- if (r.response === 0) void shell.openExternal(RELEASES_URL);
- });
+ if (downloadInFlight) {
+ return;
+ }
+ if (switchToFallbackFeed("feed unavailable")) {
+ void autoUpdater.checkForUpdates().catch((retryErr: Error) => {
+ log(`check failed: ${retryErr.message}`);
+ });
+ return;
}
+ reportUpdaterError(err);
});
- setTimeout(() => void check(), FIRST_CHECK_DELAY_MS).unref();
- setInterval(() => void check(), CHECK_INTERVAL_MS).unref();
+ const override = feedUrlOverride(process.env);
+ if (override) {
+ feedRefreshMode = "static";
+ setGenericFeed(override, null);
+ log(`feed override: ${override}`);
+ scheduleChecks();
+ return;
+ }
+
+ const config = updateSourceConfig(process.env);
+ if (config.invalidSource) {
+ log("PENGUIN_UPDATE_SOURCE has an unsupported value; treated as auto.");
+ }
+ if (config.invalidProbe) {
+ log("PENGUIN_UPDATE_SPEED_PROBE has an unsupported value; treated as 1.");
+ }
+
+ if (config.source === "github") {
+ feedRefreshMode = "github";
+ setGitHubFeed();
+ log("selected GitHub update feed");
+ scheduleChecks();
+ return;
+ }
+
+ if (config.source === "oss") {
+ feedRefreshMode = "oss";
+ void refreshUpdateFeed().finally(scheduleChecks);
+ return;
+ }
+
+ if (!config.probe) {
+ feedRefreshMode = "github";
+ setGitHubFeed();
+ log("selected GitHub update feed");
+ scheduleChecks();
+ return;
+ }
+
+ feedRefreshMode = "auto-probe";
+ void refreshUpdateFeed().finally(scheduleChecks);
}
async function check(): Promise<void> {
- // A waiting build ends the checking: a re-check with autoDownload on would start
- // fetching any newer release and invalidate the downloaded package on disk while
- // the UI still points its install action at it. The user installs what they were
- // offered; the next launch checks again. A running download likewise finishes
- // undisturbed.
+ // A waiting build ends the checking: a re-check that finds a newer release would
+ // start fetching it and invalidate the downloaded package on disk while the UI still
+ // points its install action at it. The user installs what they were offered; the next
+ // launch checks again. A running download likewise finishes undisturbed.
if (downloadedVersion !== null || status.state === "downloading") return;
+ await refreshUpdateFeed();
+ if (feedState.phase !== "ready") {
+ const message =
+ feedState.phase === "pending"
+ ? "Update source selection is still in progress."
+ : "The configured update source is unavailable.";
+ log(
+ `check skipped (${feedState.phase === "pending" ? "update source selection pending" : "update source unavailable"})`,
+ );
+ emitStatus({ kind: "error", message });
+ return;
+ }
+ // Each fresh cycle gets its one-shot switch back (the retry path bypasses check()).
+ feedState = { phase: "ready", fallbackUrl: otherGenericUrl };
try {
await autoUpdater.checkForUpdates();
} catch (err) {
@@ -233,6 +411,36 @@ async function check(): Promise<void> {
}
}
+async function downloadUpdateWithFallback(): Promise<void> {
+ if (downloadedVersion !== null || downloadInFlight) return;
+ downloadInFlight = true;
+ let delegatedToRetryCheck = false;
+ try {
+ await autoUpdater.downloadUpdate();
+ } catch (err) {
+ const error = err as Error;
+ if (downloadedVersion !== null) return;
+ downloadInFlight = false;
+ if (switchToFallbackFeed("download failed")) {
+ delegatedToRetryCheck = true;
+ try {
+ const retryResult = await autoUpdater.checkForUpdates();
+ if (retryResult === null || !retryResult.isUpdateAvailable) {
+ const message = "The fallback update source did not offer a downloadable update.";
+ log(message);
+ emitStatus({ kind: "error", message });
+ }
+ } catch (retryErr) {
+ log(`check failed: ${(retryErr as Error).message}`);
+ }
+ return;
+ }
+ reportUpdaterError(error);
+ } finally {
+ if (!delegatedToRetryCheck) downloadInFlight = false;
+ }
+}
+
/** Menu action: same check, but every outcome is reported. */
export async function checkForUpdatesManually(): Promise<void> {
if (!updatesAvailableInThisForm()) {
@@ -254,6 +462,15 @@ export async function checkForUpdatesManually(): Promise<void> {
await promptRestart(downloadedVersion, null);
return;
}
+ if (feedState.phase === "pending") {
+ await dialog.showMessageBox({
+ type: "info",
+ message: "Updates are unavailable.",
+ detail: "Update source selection is still in progress; try again in a moment.",
+ buttons: ["OK"],
+ });
+ return;
+ }
if (status.state === "downloading") {
// check() would decline anyway; a manual action still answers (the silence rule).
await dialog.showMessageBox({
@@ -265,6 +482,15 @@ export async function checkForUpdatesManually(): Promise<void> {
}
manualCheckInFlight = true;
await check();
+ if (manualCheckInFlight && feedState.phase === "unavailable") {
+ manualCheckInFlight = false;
+ await dialog.showMessageBox({
+ type: "error",
+ message: "Could not check for updates.",
+ detail: "The configured update source is unavailable. See the updater log for details.",
+ buttons: ["OK"],
+ });
+ }
}
/** "Ready to install" prompt; restarting is the only path that swaps the app. */
diff --git a/packages/desktop/test/update-source.test.ts b/packages/desktop/test/update-source.test.ts
new file mode 100644
index 00000000..fa4254cc
--- /dev/null
+++ b/packages/desktop/test/update-source.test.ts
@@ -0,0 +1,612 @@
+/**
+ * Tests for the desktop update-source selection (no Electron runtime). A fake fetch stands
+ * in for the release endpoints so the whole probe contract — latest.json validation,
+ * manifest parsing, probe verification, the 256 KiB/s minimum-speed gate, the 1.5x OSS
+ * switch threshold and the inconclusive fallbacks — runs against controlled responses,
+ * mirroring the decision vectors the release installers test.
+ */
+import { createHash } from "node:crypto";
+import { describe, expect, it, vi } from "vitest";
+import {
+ GITHUB_RELEASE_ROOT,
+ OSS_LATEST_JSON_URL,
+ OSS_RELEASE_ROOT,
+ desktopUpdateAssetName,
+ feedLabel,
+ githubFeedUrl,
+ loadReleaseDownloadManifest,
+ ossFeedUrl,
+ probeSource,
+ resolveOssLatestTag,
+ selectAutoUpdateFeed,
+ selectMeasuredSource,
+ type FetchFn,
+ type ProbeResponse,
+} from "../src/update-source.js";
+
+const TAG = "v0.2.2";
+const OSS_BASE = `${OSS_RELEASE_ROOT}/${TAG}`;
+const GH_BASE = `${GITHUB_RELEASE_ROOT}/${TAG}`;
+const WIN_ASSET = "penguin-desktop-win32-x64.exe";
+const MAC_ASSET = "penguin-desktop-darwin-arm64.zip";
+
+function probeBody(size: number): Uint8Array {
+ return new Uint8Array(size).fill(0x2a);
+}
+
+function sha256Hex(bytes: Uint8Array): string {
+ return createHash("sha256").update(bytes).digest("hex");
+}
+
+const SMALL = {
+ name: "probe-64k.bin",
+ size: 64 * 1024,
+ sha256: sha256Hex(probeBody(64 * 1024)),
+};
+const LARGE = {
+ name: "probe-1m.bin",
+ size: 1024 * 1024,
+ sha256: sha256Hex(probeBody(1024 * 1024)),
+};
+const LARGE_BYTES = probeBody(1024 * 1024);
+
+function manifestText(assetName: string, assetSize: number): string {
+ return [
+ `penguin-release-download-manifest\t1\t${TAG}`,
+ `probe\tsmall\t${SMALL.name}\t${SMALL.size}\t${SMALL.sha256}`,
+ `probe\tlarge\t${LARGE.name}\t${LARGE.size}\t${LARGE.sha256}`,
+ `desktop_asset\t${assetName}\t${assetSize}\t${"0".repeat(64)}`,
+ "",
+ ].join("\n");
+}
+
+interface FakeRoute {
+ status?: number;
+ body?: Uint8Array | string;
+ /** Advances the mocked clock without slowing the test process. */
+ advanceMs?: number;
+ networkError?: boolean;
+ encoding?: string | null;
+}
+
+interface FakeCall {
+ url: string;
+ acceptEncoding: string | undefined;
+}
+
+interface FakeClock {
+ now: number;
+}
+
+function fakeResponse(status: number, body: Uint8Array, encoding: string | null): ProbeResponse {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: (name) => (name === "content-encoding" ? encoding : null) },
+ arrayBuffer: async () => body.slice().buffer,
+ };
+}
+
+function fakeFetch(
+ routes: Record<string, FakeRoute>,
+ calls: FakeCall[] = [],
+ clock?: FakeClock,
+): FetchFn {
+ return async (url, init) => {
+ calls.push({ url, acceptEncoding: init.headers["accept-encoding"] });
+ const route = routes[url];
+ if (route === undefined) return fakeResponse(404, new Uint8Array(0), null);
+ if (route.advanceMs !== undefined && route.advanceMs > 0 && clock) clock.now += route.advanceMs;
+ if (route.networkError) throw new Error("simulated network failure");
+ const body =
+ typeof route.body === "string"
+ ? new TextEncoder().encode(route.body)
+ : (route.body ?? new Uint8Array(0));
+ return fakeResponse(route.status ?? 200, body, route.encoding ?? null);
+ };
+}
+
+/** latest.json + both manifests + both small probes + GitHub large probe all healthy. */
+function happyRoutes(
+ opts: {
+ assetName?: string;
+ assetSize?: number;
+ githubLargeMs?: number;
+ ossLargeMs?: number;
+ largeFail?: boolean;
+ } = {},
+): Record<string, FakeRoute> {
+ const assetName = opts.assetName ?? WIN_ASSET;
+ return {
+ [OSS_LATEST_JSON_URL]: {
+ body: JSON.stringify({
+ schemaVersion: 1,
+ tag: TAG,
+ releaseBaseUrl: `${OSS_RELEASE_ROOT}/${TAG}`,
+ }),
+ },
+ [`${OSS_BASE}/release-download-manifest.tsv`]: {
+ body: manifestText(assetName, opts.assetSize ?? 120 * 1024 * 1024),
+ },
+ [`${OSS_BASE}/${SMALL.name}`]: { body: probeBody(SMALL.size) },
+ [`${GH_BASE}/${SMALL.name}`]: { body: probeBody(SMALL.size) },
+ [`${OSS_BASE}/${LARGE.name}`]: {
+ body: LARGE_BYTES,
+ advanceMs: opts.ossLargeMs ?? 1000,
+ },
+ [`${GH_BASE}/${LARGE.name}`]: opts.largeFail
+ ? { status: 500 }
+ : { body: LARGE_BYTES, advanceMs: opts.githubLargeMs ?? 1000 },
+ };
+}
+
+function runSelection(
+ routes: Record<string, FakeRoute>,
+ calls: FakeCall[] = [],
+ platform: NodeJS.Platform = "win32",
+ arch = "x64",
+ budgetMs = 60_000,
+): { decision: ReturnType<typeof selectAutoUpdateFeed>; logs: string[] } {
+ const logs: string[] = [];
+ const clock = { now: 1_000_000 };
+ const now = vi.spyOn(Date, "now").mockImplementation(() => clock.now);
+ const decision = selectAutoUpdateFeed({
+ fetchFn: fakeFetch(routes, calls, clock),
+ platform,
+ arch,
+ log: (line) => logs.push(line),
+ budgetMs,
+ }).finally(() => {
+ now.mockRestore();
+ });
+ return {
+ decision,
+ logs,
+ };
+}
+
+describe("desktopUpdateAssetName", () => {
+ it("maps the update asset per platform and arch (zip for macOS, never the dmg)", () => {
+ expect(desktopUpdateAssetName("darwin", "arm64")).toBe("penguin-desktop-darwin-arm64.zip");
+ expect(desktopUpdateAssetName("darwin", "x64")).toBe("penguin-desktop-darwin-x64.zip");
+ expect(desktopUpdateAssetName("win32", "x64")).toBe(WIN_ASSET);
+ expect(desktopUpdateAssetName("linux", "x64")).toBe("penguin-desktop-linux-x86_64.AppImage");
+ });
+
+ it("yields nothing for forms the updater never downloads", () => {
+ expect(desktopUpdateAssetName("win32", "arm64")).toBeNull();
+ expect(desktopUpdateAssetName("linux", "arm64")).toBeNull();
+ expect(desktopUpdateAssetName("darwin", "ia32")).toBeNull();
+ });
+});
+
+describe("feedLabel", () => {
+ it("names the known sources and stays neutral for anything else", () => {
+ expect(feedLabel("https://x.oss-cn-beijing.aliyuncs.com/releases/v1/")).toBe("OSS mirror");
+ expect(feedLabel("https://github.com/Prism-Shadow/penguin-harness/releases/download/v1/")).toBe(
+ "GitHub",
+ );
+ expect(feedLabel("https://mirror.example.com/updates/")).toBe("configured mirror");
+ expect(feedLabel("not a url")).toBe("configured mirror");
+ });
+});
+
+describe("resolveOssLatestTag", () => {
+ it("returns the tag of a valid latest.json", async () => {
+ const fetchFn = fakeFetch({
+ [OSS_LATEST_JSON_URL]: {
+ body: JSON.stringify({
+ schemaVersion: 1,
+ tag: TAG,
+ releaseBaseUrl: `${OSS_RELEASE_ROOT}/${TAG}`,
+ }),
+ },
+ });
+ await expect(resolveOssLatestTag(fetchFn)).resolves.toBe(TAG);
+ });
+
+ it("rejects non-200, network failures and invalid JSON", async () => {
+ await expect(
+ resolveOssLatestTag(fakeFetch({ [OSS_LATEST_JSON_URL]: { status: 503 } })),
+ ).resolves.toBeNull();
+ await expect(
+ resolveOssLatestTag(fakeFetch({ [OSS_LATEST_JSON_URL]: { networkError: true } })),
+ ).resolves.toBeNull();
+ await expect(
+ resolveOssLatestTag(fakeFetch({ [OSS_LATEST_JSON_URL]: { body: "{not json" } })),
+ ).resolves.toBeNull();
+ });
+
+ it("rejects wrong schema, unsafe tags and mismatched base URLs", async () => {
+ await expect(
+ resolveOssLatestTag(
+ fakeFetch({
+ [OSS_LATEST_JSON_URL]: {
+ body: JSON.stringify({ schemaVersion: 2, tag: TAG, releaseBaseUrl: `${OSS_BASE}` }),
+ },
+ }),
+ ),
+ ).resolves.toBeNull();
+ await expect(
+ resolveOssLatestTag(
+ fakeFetch({
+ [OSS_LATEST_JSON_URL]: {
+ body: JSON.stringify({
+ schemaVersion: 1,
+ tag: "../v0.2.2",
+ releaseBaseUrl: `${OSS_BASE}`,
+ }),
+ },
+ }),
+ ),
+ ).resolves.toBeNull();
+ await expect(
+ resolveOssLatestTag(
+ fakeFetch({
+ [OSS_LATEST_JSON_URL]: {
+ body: JSON.stringify({
+ schemaVersion: 1,
+ tag: TAG,
+ releaseBaseUrl: "https://evil.example/releases/v0.2.2",
+ }),
+ },
+ }),
+ ),
+ ).resolves.toBeNull();
+ });
+});
+
+describe("loadReleaseDownloadManifest", () => {
+ const deadlineMs = Date.now() + 60_000;
+
+ it("parses a valid manifest and falls back to GitHub when the OSS copy is missing", async () => {
+ const parsed = await loadReleaseDownloadManifest({
+ fetchFn: fakeFetch({
+ [`${GH_BASE}/release-download-manifest.tsv`]: {
+ body: manifestText(WIN_ASSET, 120 * 1024 * 1024),
+ },
+ }),
+ tag: TAG,
+ assetName: WIN_ASSET,
+ deadlineMs,
+ });
+ expect(parsed).toEqual({ smallProbe: SMALL, largeProbe: LARGE, assetSize: 120 * 1024 * 1024 });
+ });
+
+ it("rejects a missing manifest, a wrong header and an exhausted budget", async () => {
+ await expect(
+ loadReleaseDownloadManifest({
+ fetchFn: fakeFetch({}),
+ tag: TAG,
+ assetName: WIN_ASSET,
+ deadlineMs,
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ loadReleaseDownloadManifest({
+ fetchFn: fakeFetch({
+ [`${OSS_BASE}/release-download-manifest.tsv`]: {
+ body: manifestText(WIN_ASSET, 120 * 1024 * 1024).replace(TAG, "v9.9.9"),
+ },
+ }),
+ tag: TAG,
+ assetName: WIN_ASSET,
+ deadlineMs,
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ loadReleaseDownloadManifest({
+ fetchFn: fakeFetch({
+ [`${OSS_BASE}/release-download-manifest.tsv`]: {
+ body: manifestText(WIN_ASSET, 120 * 1024 * 1024),
+ },
+ }),
+ tag: TAG,
+ assetName: WIN_ASSET,
+ deadlineMs: Date.now() - 1,
+ }),
+ ).resolves.toBeNull();
+ });
+
+ it("rejects manifests missing probes or the platform asset row", async () => {
+ const withoutLarge = manifestText(WIN_ASSET, 120 * 1024 * 1024)
+ .split("\n")
+ .filter((line) => !line.startsWith("probe\tlarge"))
+ .join("\n");
+ await expect(
+ loadReleaseDownloadManifest({
+ fetchFn: fakeFetch({
+ [`${OSS_BASE}/release-download-manifest.tsv`]: { body: withoutLarge },
+ }),
+ tag: TAG,
+ assetName: WIN_ASSET,
+ deadlineMs,
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ loadReleaseDownloadManifest({
+ fetchFn: fakeFetch({
+ [`${OSS_BASE}/release-download-manifest.tsv`]: {
+ body: manifestText(MAC_ASSET, 120 * 1024 * 1024),
+ },
+ }),
+ tag: TAG,
+ assetName: WIN_ASSET,
+ deadlineMs,
+ }),
+ ).resolves.toBeNull();
+ });
+});
+
+describe("probeSource", () => {
+ const deadlineMs = Date.now() + 60_000;
+
+ it("accepts an exact verified probe and reports throughput", async () => {
+ const result = await probeSource({
+ fetchFn: fakeFetch({ [`${OSS_BASE}/${LARGE.name}`]: { body: LARGE_BYTES } }),
+ base: OSS_BASE,
+ probe: LARGE,
+ deadlineMs,
+ maxTimeoutSeconds: 5,
+ wantSpeed: true,
+ });
+ expect(result.ok).toBe(true);
+ expect(result.speedBps).toBeGreaterThan(0);
+ });
+
+ it("rejects wrong sizes, wrong hashes, non-2xx, compression and network failures", async () => {
+ const routes = (route: FakeRoute) => ({
+ [`${OSS_BASE}/${SMALL.name}`]: route,
+ });
+ expect(
+ (
+ await probeSource({
+ fetchFn: fakeFetch(routes({ body: new Uint8Array(100) })),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ })
+ ).ok,
+ ).toBe(false);
+ expect(
+ (
+ await probeSource({
+ fetchFn: fakeFetch(routes({ body: probeBody(SMALL.size).fill(0x01) })),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ })
+ ).ok,
+ ).toBe(false);
+ expect(
+ (
+ await probeSource({
+ fetchFn: fakeFetch(routes({ status: 500 })),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ })
+ ).ok,
+ ).toBe(false);
+ expect(
+ (
+ await probeSource({
+ fetchFn: fakeFetch(routes({ body: probeBody(SMALL.size), encoding: "gzip" })),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ })
+ ).ok,
+ ).toBe(false);
+ expect(
+ (
+ await probeSource({
+ fetchFn: fakeFetch(routes({ networkError: true })),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ })
+ ).ok,
+ ).toBe(false);
+ });
+
+ it("requests identity encoding and refuses to start past the budget", async () => {
+ const calls: FakeCall[] = [];
+ await probeSource({
+ fetchFn: fakeFetch({ [`${OSS_BASE}/${SMALL.name}`]: { body: probeBody(SMALL.size) } }, calls),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ });
+ expect(calls[0]?.acceptEncoding).toBe("identity");
+ expect(
+ (
+ await probeSource({
+ fetchFn: fakeFetch({}),
+ base: OSS_BASE,
+ probe: SMALL,
+ deadlineMs: Date.now() - 1,
+ maxTimeoutSeconds: 2,
+ wantSpeed: false,
+ })
+ ).ok,
+ ).toBe(false);
+ });
+});
+
+describe("selectMeasuredSource", () => {
+ it("keeps GitHub above the minimum speed and on ties below it", () => {
+ expect(selectMeasuredSource(262144, 10_000_000)).toBe("github");
+ expect(selectMeasuredSource(200_000, 299_999)).toBe("github");
+ });
+
+ it("switches to OSS only when GitHub missed the minimum and OSS is more than 1.5x faster", () => {
+ expect(selectMeasuredSource(200_000, 300_001)).toBe("oss");
+ });
+});
+
+describe("selectAutoUpdateFeed", () => {
+ it("keeps GitHub when the GitHub large probe meets the 256 KiB/s gate", async () => {
+ const { decision, logs } = await runSelection(happyRoutes());
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: githubFeedUrl(TAG),
+ fallbackUrl: ossFeedUrl(TAG),
+ });
+ expect(logs).toContain("Selected GitHub (meets minimum download speed).");
+ });
+
+ it("promotes the OSS mirror when GitHub misses the minimum and OSS is clearly faster", async () => {
+ const { decision, logs } = await runSelection(
+ happyRoutes({ githubLargeMs: 5_000, ossLargeMs: 1_000 }),
+ );
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: ossFeedUrl(TAG),
+ fallbackUrl: githubFeedUrl(TAG),
+ });
+ expect(logs).toContain("Selected OSS mirror (clearly faster than GitHub here).");
+ });
+
+ it("keeps GitHub when both sources miss the minimum and OSS is not enough faster", async () => {
+ const { decision, logs } = await runSelection(
+ happyRoutes({ githubLargeMs: 5_000, ossLargeMs: 4_500 }),
+ );
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: githubFeedUrl(TAG),
+ fallbackUrl: ossFeedUrl(TAG),
+ });
+ expect(logs).toContain(
+ "Selected GitHub (the OSS mirror was not enough faster to be worth switching).",
+ );
+ });
+
+ it("uses the OSS mirror when the GitHub large probe fails and OSS can be measured", async () => {
+ const { decision, logs } = await runSelection(
+ happyRoutes({ largeFail: true, ossLargeMs: 1_000 }),
+ );
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: ossFeedUrl(TAG),
+ fallbackUrl: githubFeedUrl(TAG),
+ });
+ expect(logs).toContain("Selected OSS mirror (clearly faster than GitHub here).");
+ });
+
+ it("keeps GitHub when only the OSS small probe fails, without measuring throughput", async () => {
+ const routes = happyRoutes();
+ delete routes[`${OSS_BASE}/${SMALL.name}`];
+ const calls: FakeCall[] = [];
+ const { decision, logs } = await runSelection(routes, calls);
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: githubFeedUrl(TAG),
+ fallbackUrl: ossFeedUrl(TAG),
+ });
+ expect(logs).toContain("Selected GitHub (OSS mirror probe unavailable).");
+ expect(calls.some((c) => c.url.endsWith(LARGE.name))).toBe(false);
+ });
+
+ it("selects the OSS mirror when only the GitHub small probe fails", async () => {
+ const routes = happyRoutes();
+ delete routes[`${GH_BASE}/${SMALL.name}`];
+ const calls: FakeCall[] = [];
+ const { decision, logs } = await runSelection(routes, calls);
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: ossFeedUrl(TAG),
+ fallbackUrl: githubFeedUrl(TAG),
+ });
+ expect(logs).toContain("Selected OSS mirror (GitHub probe unavailable).");
+ expect(calls.some((c) => c.url.endsWith(LARGE.name))).toBe(false);
+ });
+
+ it("keeps GitHub when both small probes fail", async () => {
+ const routes = happyRoutes();
+ delete routes[`${OSS_BASE}/${SMALL.name}`];
+ delete routes[`${GH_BASE}/${SMALL.name}`];
+ const calls: FakeCall[] = [];
+ const { decision, logs } = await runSelection(routes, calls);
+ expect(await decision).toEqual({ kind: "keep-github", reason: "inconclusive" });
+ expect(logs).toContain("Download source test was inconclusive; keeping GitHub update feed.");
+ expect(calls.some((c) => c.url.endsWith(LARGE.name))).toBe(false);
+ });
+
+ it("keeps GitHub without any probes when latest.json is invalid or the manifest is unusable", async () => {
+ const noLatest = await runSelection({ [OSS_LATEST_JSON_URL]: { status: 503 } });
+ expect(await noLatest.decision).toEqual({ kind: "keep-github", reason: "inconclusive" });
+
+ const routes = happyRoutes();
+ delete routes[`${OSS_BASE}/release-download-manifest.tsv`];
+ const noManifest = await runSelection(routes);
+ expect(await noManifest.decision).toEqual({ kind: "keep-github", reason: "inconclusive" });
+
+ const badHeader = happyRoutes();
+ badHeader[`${OSS_BASE}/release-download-manifest.tsv`] = {
+ body: manifestText(WIN_ASSET, 120 * 1024 * 1024).replace(TAG, "v9.9.9"),
+ };
+ const mismatched = await runSelection(badHeader);
+ expect(await mismatched.decision).toEqual({ kind: "keep-github", reason: "inconclusive" });
+ });
+
+ it("selects the OSS mirror when the GitHub small probe is corrupted (wrong bytes or compressed)", async () => {
+ const wrongBytes = happyRoutes();
+ wrongBytes[`${GH_BASE}/${SMALL.name}`] = { body: new Uint8Array(100) };
+ const corrupted = await runSelection(wrongBytes);
+ expect(await corrupted.decision).toEqual({
+ kind: "pinned",
+ primaryUrl: ossFeedUrl(TAG),
+ fallbackUrl: githubFeedUrl(TAG),
+ });
+
+ const compressed = happyRoutes();
+ compressed[`${GH_BASE}/${SMALL.name}`] = {
+ body: probeBody(SMALL.size),
+ encoding: "gzip",
+ };
+ const gzipped = await runSelection(compressed);
+ expect(await gzipped.decision).toEqual({
+ kind: "pinned",
+ primaryUrl: ossFeedUrl(TAG),
+ fallbackUrl: githubFeedUrl(TAG),
+ });
+ });
+
+ it("keeps GitHub when the probe budget is already exhausted", async () => {
+ const routes = happyRoutes();
+ const calls: FakeCall[] = [];
+ const { decision, logs } = await runSelection(routes, calls, "win32", "x64", 0);
+ expect(await decision).toEqual({ kind: "keep-github", reason: "inconclusive" });
+ expect(logs).toContain("Download source test was inconclusive; keeping GitHub update feed.");
+ });
+
+ it("keeps GitHub for forms without a desktop update asset, without any network access", async () => {
+ const calls: FakeCall[] = [];
+ const { decision } = await runSelection(happyRoutes(), calls, "win32", "arm64");
+ expect(await decision).toEqual({ kind: "keep-github", reason: "inconclusive" });
+ expect(calls).toEqual([]);
+ });
+
+ it("uses the platform-specific desktop asset row (macOS zip)", async () => {
+ const routes = happyRoutes({ assetName: MAC_ASSET });
+ const { decision } = await runSelection(routes, [], "darwin", "arm64");
+ expect(await decision).toEqual({
+ kind: "pinned",
+ primaryUrl: githubFeedUrl(TAG),
+ fallbackUrl: ossFeedUrl(TAG),
+ });
+ });
+});
diff --git a/packages/desktop/test/update-support.test.ts b/packages/desktop/test/update-support.test.ts
index c101794b..fe337c9e 100644
--- a/packages/desktop/test/update-support.test.ts
+++ b/packages/desktop/test/update-support.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { feedUrlOverride, updateSupport } from "../src/update-support.js";
+import { feedUrlOverride, updateSourceConfig, updateSupport } from "../src/update-support.js";
describe("updateSupport", () => {
it("supports packaged macOS and Windows builds", () => {
@@ -44,3 +44,43 @@ describe("feedUrlOverride", () => {
expect(feedUrlOverride({ PENGUIN_UPDATE_FEED_URL: "not a url" })).toBeNull();
});
});
+
+describe("updateSourceConfig", () => {
+ it("defaults to auto with the speed probe on", () => {
+ expect(updateSourceConfig({})).toEqual({
+ source: "auto",
+ probe: true,
+ invalidSource: false,
+ invalidProbe: false,
+ });
+ });
+
+ it("accepts every source and the probe switch, trimming whitespace", () => {
+ expect(updateSourceConfig({ PENGUIN_UPDATE_SOURCE: " oss " })).toMatchObject({
+ source: "oss",
+ invalidSource: false,
+ });
+ expect(updateSourceConfig({ PENGUIN_UPDATE_SOURCE: "github" })).toMatchObject({
+ source: "github",
+ invalidSource: false,
+ });
+ expect(updateSourceConfig({ PENGUIN_UPDATE_SOURCE: "auto" })).toMatchObject({
+ source: "auto",
+ invalidSource: false,
+ });
+ expect(updateSourceConfig({ PENGUIN_UPDATE_SPEED_PROBE: "1" })).toMatchObject({
+ probe: true,
+ invalidProbe: false,
+ });
+ expect(updateSourceConfig({ PENGUIN_UPDATE_SPEED_PROBE: " 0 " })).toMatchObject({
+ probe: false,
+ invalidProbe: false,
+ });
+ });
+
+ it("treats unsupported values as defaults and flags them", () => {
+ expect(
+ updateSourceConfig({ PENGUIN_UPDATE_SOURCE: "mirror", PENGUIN_UPDATE_SPEED_PROBE: "2" }),
+ ).toEqual({ source: "auto", probe: true, invalidSource: true, invalidProbe: true });
+ });
+});