Skip to content

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

Decide the download source in under a second, and re-decide on every visit (#420)

Yaowei Zheng29f432f889b0
diff --git a/changelog/unreleased/2026-08-23-download-source-rule.md b/changelog/unreleased/2026-08-23-download-source-rule.md
index d3853a24..0e59c222 100644
--- a/changelog/unreleased/2026-08-23-download-source-rule.md
+++ b/changelog/unreleased/2026-08-23-download-source-rule.md
@@ -3,7 +3,7 @@
- **Date:** 2026-08-23
- **Type:** feature
- **Scope:** `tooling`, `landing`, `docs`
-- **PR:** [#403](https://github.com/Prism-Shadow/penguin-harness/pull/403), [#406](https://github.com/Prism-Shadow/penguin-harness/pull/406)
+- **PR:** [#403](https://github.com/Prism-Shadow/penguin-harness/pull/403), [#406](https://github.com/Prism-Shadow/penguin-harness/pull/406), [#420](https://github.com/Prism-Shadow/penguin-harness/pull/420)
[中文版](2026-08-23-download-source-rule.zh.md)
@@ -24,11 +24,29 @@ spent on a probe that could not change the answer. `penguin update` inherits the
## Download page
-- The buttons wait for the answer behind a spinner instead of pointing at GitHub while the probe runs, so a visitor who cannot reach GitHub is never handed a link that will not start. Whatever the probe decides, the source can still be switched by hand.
-- Every request is bounded by its own cap and by a 9s budget over the whole sequence. Response headers and transfer body have separate caps, so a source that never answers is settled as unreachable without waiting out the transfer.
-- An unreachable GitHub is settled on whether the mirror answers, asked with the 64 KiB probe; a reachable one below the minimum is settled on throughput, measured on the large probe.
-- The result is cached for the browser session, so the measurement happens at most once per tab.
-- Throughput is read from the Resource Timing entry rather than the response body, because GitHub's release assets refuse cross-origin reads.
+Two passes decide, because the two questions have incompatible clocks. Whether a source answers is
+a round trip; how fast it is cannot be judged in under a second at any probe size, since the
+minimum is 256 KB/s against a 1 MiB probe and the boundary case is therefore a four-second
+transfer.
+
+- The buttons wait only on the first pass — capped at about a second, a target rather than a
+ guarantee — and go live knowing nobody
+ has been handed a link that will never start. Until then they render without an `href`, dimmed,
+ `aria-disabled`, with a spinner in place of the download icon.
+- That pass asks GitHub one question over a version-less URL that needs no manifest and no tag: does
+ it answer. GitHub is the free source and keeps the download whenever it does, so that path does
+ not wait for the mirror pointer at all. The pointer runs on a longer clock of its own, and a late
+ arrival still reaches the page rather than being discarded.
+- The throughput comparison then runs behind the live page and upgrades the links when the mirror
+ turns out to be worth switching to, saying so in the status line while it runs. It also runs when
+ GitHub missed the sub-second window, so a distant-but-working GitHub is handed the download back
+ rather than written off.
+- Nothing is cached. Network conditions change between visits, so every page load measures again.
+- Requests are bounded by their own caps as well as by their pass. Response headers and transfer
+ body have separate caps, so a source that never answers is settled as unreachable without waiting
+ out the transfer.
+- Throughput is read from the Resource Timing entry rather than the response body, because GitHub's
+ release assets refuse cross-origin reads.
## Docs
diff --git a/changelog/unreleased/2026-08-23-download-source-rule.zh.md b/changelog/unreleased/2026-08-23-download-source-rule.zh.md
index 6959127b..75348415 100644
--- a/changelog/unreleased/2026-08-23-download-source-rule.zh.md
+++ b/changelog/unreleased/2026-08-23-download-source-rule.zh.md
@@ -3,7 +3,7 @@
- **Date:** 2026-08-23
- **Type:** feature
- **Scope:** `tooling`, `landing`, `docs`
-- **PR:** [#403](https://github.com/Prism-Shadow/penguin-harness/pull/403), [#406](https://github.com/Prism-Shadow/penguin-harness/pull/406)
+- **PR:** [#403](https://github.com/Prism-Shadow/penguin-harness/pull/403), [#406](https://github.com/Prism-Shadow/penguin-harness/pull/406), [#420](https://github.com/Prism-Shadow/penguin-harness/pull/420)
[English](2026-08-23-download-source-rule.md)
@@ -22,10 +22,20 @@
## 下载页
-- 测速期间按钮以加载态等待结论,而不是先指向 GitHub,因此连不上 GitHub 的访客不会拿到一个点了也不会开始的链接。无论测速结论如何,来源仍可手动切换。
-- 每个请求都受自身上限与整段 9 秒预算的双重约束;响应头与传输体各有上限,因此始终不响应的源会被判定为不可达,而不必等满传输上限。
-- GitHub 不可达时,结论取决于镜像是否响应,用 64 KiB 探测文件询问;GitHub 可达但低于达标线时,则是吞吐问题,用大测速文件测量。
-- 结论在浏览器会话内缓存,因此每个标签页至多测量一次。
+判定分两趟,因为两个问题的时间尺度并不相容:一个源是否响应只需一次往返;而它有多快,无论探测文件取
+多大都无法在一秒内判定——达标线是 256 KB/s、大测速文件是 1 MiB,临界情形本身就是一次四秒的传输。
+
+- 按钮只等待第一趟,其上限约为一秒——这是目标而非保证;等待结束时即可确信没有人拿到一个永远不会开始的链接。在此之前
+ 按钮不带 `href`、置灰、标记 `aria-disabled`,并以加载图标替代下载图标。
+- 这一趟只问 GitHub 一个问题:它是否响应;所用 URL 不带版本号,既不需要 manifest 也不需要 tag。
+ GitHub 是免费的源,只要它响应就保留下载,因此该路径完全不等待镜像指针。指针有自己更长的时限,
+ 迟到的结果也仍会送达页面,而不是被丢弃。
+- 随后速度比较在页面已可用的情况下于后台进行,若镜像值得切换则更新链接,并在状态行说明正在进行。
+ GitHub 未能在一秒窗口内响应时同样会跑这一趟,使得「距离远但可用」的 GitHub 能被交还下载,而不是
+ 被就此判出局。
+- 不再有任何缓存。访客的网络状况会变化,因此每次加载都重新测量。
+- 请求同时受自身上限与所属趟次的约束;响应头与传输体各有上限,因此始终不响应的源会被判定为不可达,
+ 而不必等满传输上限。
- 吞吐量读自 Resource Timing 记录而非响应体,因为 GitHub 的 Release 资源拒绝跨源读取。
## 文档
diff --git a/packages/landing/src/lib/download-source.ts b/packages/landing/src/lib/download-source.ts
index 25a24c93..e7e01bc0 100644
--- a/packages/landing/src/lib/download-source.ts
+++ b/packages/landing/src/lib/download-source.ts
@@ -35,11 +35,39 @@ export const SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND = 262144;
export const SPEED_PROBE_OSS_SWITCH_RATIO = 1.5;
/**
- * The whole sequence — mirror pointer, manifest, and up to two probes — from its first request.
- * Every phase below clamps to what is left of it, so the buttons cannot stay behind a spinner
- * longer than this no matter which request is the one hanging.
+ * Two passes, because the two questions have incompatible clocks.
+ *
+ * Whether a source answers at all is a round trip, and it is the question that decides whether
+ * someone is handed a link that never starts — so it gates the buttons and gets one second.
+ *
+ * How fast a source is cannot be answered in one second at any probe size. The minimum is
+ * 256 KB/s and the large probe is 1 MiB, so the boundary case *is* a four-second transfer, on top
+ * of roughly half a second of DNS, TLS and GitHub's two redirect hops; shrink the probe and that
+ * fixed half-second swamps the reading instead. So throughput runs afterwards, gates nothing, and
+ * silently upgrades the links if the mirror turns out to be worth switching to. The worst it can
+ * cost is a download that was slower than necessary — never one that does not start.
*/
-export const PROBE_BUDGET_MS = 9000;
+/**
+ * Three clocks, because the gate and the mirror pointer must not share one. The gate hinges on
+ * GitHub — a GitHub that answers keeps the download whatever the mirror is doing — so GitHub gets
+ * its own window, and the gate as a whole is capped at roughly a second.
+ *
+ * That one second is a target, not a guarantee, and the caps are set accordingly. A cap only ever
+ * bites a source that is slow or silent: a healthy GitHub answers in a few hundred milliseconds and
+ * never notices it. So the cost of a generous cap falls entirely on the blocked case, which is
+ * already waiting, while the cost of a tight one falls on a distant-but-working GitHub that gets
+ * written off and has its download handed to the mirror we pay for. Prefer the generous side.
+ *
+ * The pointer's clock is longer than the gate's on purpose. It used to share the gate's, which
+ * meant a pointer that arrived late was discarded, and a visitor who could not reach GitHub was
+ * left on GitHub links with no mirror to switch to for the rest of the visit. It now outlives the
+ * gate: the gate takes it only if it is there in time, and a late arrival still reaches the page,
+ * where it enables the manual switch and lets the throughput pass correct the answer.
+ */
+export const GITHUB_REACHABILITY_MS = 800;
+export const GATE_BUDGET_MS = 1000;
+export const MIRROR_POINTER_MS = 2500;
+export const THROUGHPUT_BUDGET_MS = 9000;
/** Cap for the two small JSON/TSV lookups, which are a round trip and a few hundred bytes. */
const METADATA_TIMEOUT_MS = 2500;
@@ -47,6 +75,13 @@ const METADATA_TIMEOUT_MS = 2500;
/** A source that has not sent response headers by here is treated as unreachable, not as slow. */
const CONNECT_TIMEOUT_MS = 2500;
+/**
+ * The file the reachability pass asks GitHub for. Which file hardly matters — a 404 answers the
+ * question as well as a 200 does, and an opaque response cannot tell them apart anyway — so a
+ * version-less URL that needs no manifest and no tag is exactly right here.
+ */
+const GITHUB_REACHABILITY_PROBE = "probe-64k.bin";
+
/**
* Cap for a probe's body. The large probe is 1 MiB, which is exactly the minimum's worth of bytes
* in 4s, so anything still running at this point is already below the minimum and the extra second
@@ -99,7 +134,7 @@ export interface ProbeDeadline {
slice(capMs: number): number;
}
-export function createDeadline(budgetMs: number = PROBE_BUDGET_MS): ProbeDeadline {
+export function createDeadline(budgetMs: number): ProbeDeadline {
const endsAt = Date.now() + budgetMs;
return { slice: (capMs) => Math.max(0, Math.min(capMs, endsAt - Date.now())) };
}
@@ -255,27 +290,19 @@ export interface ProbeSources {
ossBase: string;
}
-/**
- * The two questions the decision below can ask of a source, injected so the branch structure can be
- * tested without a network: `measure` runs the large probe, `answers` runs the cheap 64 KiB one.
- */
+/** The one question the throughput pass asks of a source, injected so the branches are testable. */
export interface SourceProbes {
measure(base: string, probe: ReleaseProbe): Promise<Measurement>;
- answers(base: string, probe: ReleaseProbe): Promise<boolean>;
}
/**
- * Applies the rule to one release, in the same order the installers apply it.
+ * The throughput half of the rule, in the order the installers apply it. It runs once the
+ * reachability pass has found a mirror, which is why an unreachable GitHub here needs no second
+ * question: that pass already proved the mirror replies, so it wins by default.
*
* GitHub is measured first. At or above the minimum it wins outright and the mirror is never
- * touched — no paid bandwidth spent on a probe that could not change the answer.
- *
- * A GitHub that never answered is a different finding from one that answered slowly, and the two
- * take different branches, exactly as they do in install.sh. Unreachable is settled on reachability
- * alone: the mirror wins if it answers, which the 64 KiB probe establishes in a fraction of the
- * time a second megabyte would. Reachable-but-unmeasured is a throughput question, so the mirror is
- * measured on the same large probe and the tie-break rule decides — collapsing the two would hand
- * the mirror downloads the rule says GitHub should keep.
+ * touched — no paid bandwidth spent on a probe that could not change the answer. Below it, the
+ * mirror is measured on the same probe and has to win by the switch ratio.
*
* The measurements run one after another on purpose: concurrent transfers share the link and would
* each read as half as fast, which an absolute threshold cannot tolerate.
@@ -287,9 +314,7 @@ export async function decideDownloadSource(
): Promise<DownloadSource> {
const github = await io.measure(sources.githubBase, probes.large);
if (github.bytesPerSecond >= SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND) return "github";
- if (!github.reachable) {
- return (await io.answers(sources.ossBase, probes.small)) ? "oss" : "github";
- }
+ if (!github.reachable) return "oss";
const oss = await io.measure(sources.ossBase, probes.large);
return selectDownloadSource(github.bytesPerSecond, oss.bytesPerSecond);
}
@@ -302,7 +327,6 @@ export function probeDownloadSource(
): Promise<DownloadSource> {
return decideDownloadSource(sources, probes, {
measure: (base, probe) => measureSource(probeUrl(base, probe.file), probe.size, deadline),
- answers: (base, probe) => probeReachable(probeUrl(base, probe.file), deadline),
});
}
@@ -357,12 +381,6 @@ export interface Mirror {
base: string;
}
-/** What the probe settled on, plus the mirror it would use. Never partially applied. */
-export interface Resolution {
- source: DownloadSource;
- mirror: Mirror | null;
-}
-
const RELEASE_TAG = /^v[0-9A-Za-z][0-9A-Za-z._-]*$/;
/**
@@ -385,57 +403,62 @@ export function parseMirror(value: unknown): Mirror | null {
return toMirror(manifest.tag, manifest.releaseBaseUrl);
}
+/** Resolves and validates the mirror pointer; null when it does not arrive in time or is invalid. */
+export function fetchMirror(deadline: ProbeDeadline): Promise<Mirror | null> {
+ return fetchMirrorPointer(OSS_LATEST_JSON_URL, deadline).then(parseMirror);
+}
+
/**
- * The result survives the rest of the browser session, so coming back to the page — or bouncing off
- * it to a release page and returning — spends neither another megabyte nor another spinner. It is
- * per-tab and short-lived on purpose: network conditions change, and a stale answer is only ever one
- * reload away from being re-measured. What comes back out is validated exactly like a live pointer,
- * so a tampered entry cannot aim a download anywhere the live lookup could not.
+ * The gating pass, and the only thing the buttons wait on. It asks one question — does GitHub
+ * answer — because that is the question whose wrong answer hands someone a link that never starts,
+ * and it is answerable in a round trip.
+ *
+ * GitHub is the free source and keeps the download whenever it answers, so that path does not wait
+ * for the mirror at all; the pointer is only needed to offer the mirror, and it is passed in as a
+ * promise so it can still be in flight. Only when GitHub stays silent does the answer depend on
+ * having a mirror to hand the download to.
*/
-const CACHE_KEY = "penguin.downloadSource.v1";
-
-export function readCachedResolution(): Resolution | null {
- try {
- const raw = sessionStorage.getItem(CACHE_KEY);
- if (!raw) return null;
- const parsed: unknown = JSON.parse(raw);
- if (typeof parsed !== "object" || parsed === null) return null;
- const { source, mirror } = parsed as { source?: unknown; mirror?: unknown };
- if (source !== "github" && source !== "oss") return null;
- if (mirror === null) return { source, mirror: null };
- if (typeof mirror !== "object") return null;
- const { tag, base } = mirror as { tag?: unknown; base?: unknown };
- const validated = toMirror(tag, base);
- return validated ? { source, mirror: validated } : null;
- } catch {
- // Private mode, blocked site data and a corrupt entry all land here; the page measures again.
- return null;
- }
+export async function gateDownloadSource(
+ mirror: Promise<Mirror | null>,
+ deadline: ProbeDeadline,
+): Promise<DownloadSource> {
+ const githubReachable = await probeReachable(
+ `${GITHUB_LATEST_DOWNLOAD}/${GITHUB_REACHABILITY_PROBE}`,
+ createDeadline(GITHUB_REACHABILITY_MS),
+ );
+ if (githubReachable) return "github";
+ // GitHub stayed silent, so the answer now needs a mirror — but only for as long as the gate has
+ // left. A pointer that misses this race is not lost; it reaches the page on its own clock.
+ const remainingMs = deadline.slice(GATE_BUDGET_MS);
+ const resolved =
+ remainingMs > 0 ? await Promise.race([mirror, delay(remainingMs).then(() => null)]) : null;
+ return resolved ? "oss" : "github";
}
-export function cacheResolution(resolution: Resolution): void {
- try {
- sessionStorage.setItem(CACHE_KEY, JSON.stringify(resolution));
- } catch {
- // Storage being unavailable costs a re-measure next visit, nothing more.
- }
+/**
+ * Whether measuring throughput could still change the gate's answer — which is whenever there is a
+ * mirror to compare against. It runs even when GitHub missed its window: that window is under a
+ * second, and a distant-but-working GitHub can spend that long on DNS, TLS and two redirect hops
+ * alone. The throughput pass gives it a far more generous one and hands the download back if it was
+ * wrongly written off.
+ */
+export function worthRefining(mirror: Mirror | null): boolean {
+ return mirror !== null && probingAllowed();
}
/**
- * Resolves the mirror pointer, then measures. Every failure lands on GitHub, the free source that
- * always has a valid version-less URL, so no path here can leave the page without a download.
+ * The unhurried pass. It gates nothing, so it can afford the manifest lookup and a megabyte of
+ * probe; its result replaces the gate's answer when it lands.
*/
-export async function resolveDownloadSource(): Promise<Resolution> {
- const deadline = createDeadline();
- const mirror = parseMirror(await fetchMirrorPointer(OSS_LATEST_JSON_URL, deadline));
- if (!mirror) return { source: "github", mirror: null };
- if (!probingAllowed()) return { source: "github", mirror };
+export async function refineDownloadSource(
+ mirror: Mirror,
+ deadline: ProbeDeadline,
+): Promise<DownloadSource> {
const probes = await fetchProbes(mirror.base, mirror.tag, deadline);
- if (!probes) return { source: "github", mirror };
- const source = await probeDownloadSource(
+ if (!probes) return "github";
+ return probeDownloadSource(
{ githubBase: GITHUB_LATEST_DOWNLOAD, ossBase: mirror.base },
probes,
deadline,
);
- return { source, mirror };
}
diff --git a/packages/landing/src/lib/strings-en.ts b/packages/landing/src/lib/strings-en.ts
index c6709376..77f2a03e 100644
--- a/packages/landing/src/lib/strings-en.ts
+++ b/packages/landing/src/lib/strings-en.ts
@@ -103,7 +103,8 @@ export const en: Strings = {
require: "x64 — AppImage runs in place, deb goes to your package manager",
},
},
- statusProbing: "Testing the download sources to pick the faster one …",
+ statusProbing: "Finding a download source that answers …",
+ statusRefining: "Still comparing the two sources — the faster one takes over on its own.",
statusOss: (version: string) =>
`Connected to the OSS mirror (${version}) — downloads are served from the mirror.`,
statusGithub: "Downloads point at the latest GitHub Release.",
diff --git a/packages/landing/src/lib/strings.ts b/packages/landing/src/lib/strings.ts
index fee5b397..038d88d5 100644
--- a/packages/landing/src/lib/strings.ts
+++ b/packages/landing/src/lib/strings.ts
@@ -105,7 +105,8 @@ export const zh = {
windows: { name: "Windows", require: "Windows 10 及以上(x64),NSIS 安装程序" },
linux: { name: "Linux", require: "x64,AppImage 免安装运行,或 deb 交给包管理器" },
},
- statusProbing: "正在为你测试下载源,选出更快的那个……",
+ statusProbing: "正在为你确认可用的下载源……",
+ statusRefining: "仍在比较两个源的速度,更快的一个会自动生效。",
statusOss: (version: string) => `已连接 OSS 国内镜像(${version}),点击即从镜像高速下载。`,
statusGithub: "下载指向 GitHub Releases 的最新版本。",
altGithub: "改从 GitHub 下载",
diff --git a/packages/landing/src/pages/download.tsx b/packages/landing/src/pages/download.tsx
index 7465a110..ba5d3ecd 100644
--- a/packages/landing/src/pages/download.tsx
+++ b/packages/landing/src/pages/download.tsx
@@ -1,26 +1,22 @@
/**
* Desktop download page. The buttons resolve to one of two sources: GitHub's static
* `releases/latest/download/<name>` links — always valid because installer names are
- * version-less — or the OSS mirror's immutable per-tag URLs, which it gets only when it
- * earns them. The bucket's `latest.json` pointer has to resolve, and the speed probe in
- * lib/download-source.ts has to find the mirror clearly faster than GitHub here, by the
- * same rule install.sh and install.ps1 apply. Any failure along the way — CORS not
- * configured on the bucket, the mirror unreachable, Data Saver on — lands on the free
- * GitHub links.
+ * version-less — or the OSS mirror's immutable per-tag URLs.
*
- * The buttons wait for that answer rather than advertising a guess, because the visitor
- * this matters most for is the one who cannot reach GitHub at all: showing them GitHub
- * links while the probe runs would hand them a download that never starts. Waiting is
- * safe only because the probe is on a clock — PROBE_BUDGET_MS bounds the whole sequence —
- * and the result is cached for the session, so the wait happens at most once. Whatever
- * the probe decides, the visitor can still switch sources by hand below the cards.
+ * Two passes decide, for the reason spelled out in lib/download-source.ts: whether a
+ * source answers is a round trip, while how fast it is cannot be judged in under a
+ * second at any probe size. So the buttons wait only on the first — one second at the
+ * outside — and go live knowing nobody has been handed a link that will never start.
+ * The throughput comparison then runs behind the live page and upgrades the links to the
+ * mirror if it turns out to be worth switching to, which can cost a slower download but
+ * never a broken one. Nothing is cached: conditions change between visits, so every load
+ * measures again. Whatever the passes decide, the visitor can still switch by hand.
*
- * Plain-anchor downloads are never CORS-gated; only the version lookup and the probe are.
+ * Plain-anchor downloads are never CORS-gated; only the lookups and the probes are.
* Below the cards, a first-launch FAQ covers the unsigned builds — one collapsible item
* per platform (macOS quarantine removal, SmartScreen, AppImage execute bit), with the
* visitor's own platform pre-expanded.
- */
-import { useEffect, useState } from "react";
+ */ import { useEffect, useState } from "react";
import { Link } from "react-router";
import type { ReactNode } from "react";
import { S } from "../lib/strings";
@@ -35,11 +31,16 @@ import {
import { detectPlatform } from "../lib/platform";
import type { Platform } from "../lib/platform";
import {
- cacheResolution,
- readCachedResolution,
- resolveDownloadSource,
+ GATE_BUDGET_MS,
+ MIRROR_POINTER_MS,
+ THROUGHPUT_BUDGET_MS,
+ createDeadline,
+ fetchMirror,
+ gateDownloadSource,
+ refineDownloadSource,
+ worthRefining,
} from "../lib/download-source";
-import type { DownloadSource, Resolution } from "../lib/download-source";
+import type { DownloadSource, Mirror } from "../lib/download-source";
import { Section } from "../components/section";
import { CodeCard } from "../components/code-card";
import { ChevronDownIcon, DownloadIcon, ExternalLinkIcon, SpinnerIcon } from "../components/icons";
@@ -77,30 +78,41 @@ function FaqItem({
}
export function DownloadPage() {
- /** null while the probe is still running: the buttons wait rather than advertise a guess. */
- const [resolution, setResolution] = useState<Resolution | null>(readCachedResolution);
- /** The visitor's own choice, which outranks the probe for the rest of the visit. */
+ const [mirror, setMirror] = useState<Mirror | null>(null);
+ /** null until the reachability pass ends — the only thing the buttons wait on. */
+ const [source, setSource] = useState<DownloadSource | null>(null);
+ /** True while the throughput pass is still running behind the live buttons. */
+ const [refining, setRefining] = useState(false);
+ /** The visitor's own choice, which outranks both passes for the rest of the visit. */
const [override, setOverride] = useState<DownloadSource | null>(null);
useEffect(() => {
- // The session cache already answered, so there is nothing to measure and no spinner to show.
- if (resolution) return;
let cancelled = false;
- void resolveDownloadSource().then((resolved) => {
- cacheResolution(resolved);
- if (!cancelled) setResolution(resolved);
+ // The pointer starts now and is handed to the gate still in flight: the gate only needs it on
+ // the path where GitHub stayed silent, and the buttons should not wait on it otherwise.
+ const mirrorPromise = fetchMirror(createDeadline(MIRROR_POINTER_MS));
+ void mirrorPromise.then((resolved) => {
+ if (!cancelled) setMirror(resolved);
});
+ void (async () => {
+ const gated = await gateDownloadSource(mirrorPromise, createDeadline(GATE_BUDGET_MS));
+ if (cancelled) return;
+ setSource(gated);
+ const resolved = await mirrorPromise;
+ if (cancelled || !worthRefining(resolved) || !resolved) return;
+ setRefining(true);
+ const refined = await refineDownloadSource(resolved, createDeadline(THROUGHPUT_BUDGET_MS));
+ if (cancelled) return;
+ setSource(refined);
+ setRefining(false);
+ })();
return () => {
cancelled = true;
};
- // Deliberately once per mount: `resolution` is read above only to skip a redundant re-run, and
- // listing it would restart the probe the moment its own result arrives.
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const detected = detectPlatform();
- const probing = resolution === null;
- const mirror = resolution?.mirror ?? null;
- const selected: DownloadSource = override ?? resolution?.source ?? "github";
+ const probing = source === null;
+ const selected: DownloadSource = override ?? source ?? "github";
const viaMirror = mirror !== null && selected === "oss";
const hrefFor = (file: string) =>
viaMirror ? `${mirror.base}/${file}` : `${GITHUB_LATEST_DOWNLOAD}/${file}`;
@@ -171,6 +183,14 @@ export function DownloadPage() {
) : (
<>
{viaMirror ? S.download.statusOss(mirror.tag) : S.download.statusGithub}{" "}
+ {refining && (
+ <>
+ <span className="inline-flex items-center gap-1.5 text-gray-500 dark:text-gray-500">
+ <SpinnerIcon className="h-3.5 w-3.5 animate-spin" />
+ {S.download.statusRefining}
+ </span>{" "}
+ </>
+ )}
{mirror !== null && (
<button
type="button"
diff --git a/packages/landing/test/download-source.test.ts b/packages/landing/test/download-source.test.ts
index 3c97d988..1d62ac99 100644
--- a/packages/landing/test/download-source.test.ts
+++ b/packages/landing/test/download-source.test.ts
@@ -4,20 +4,19 @@
* pinned here is the decision the measurements feed and the manifest parsing that names the probe.
* The installers run the same table against their own implementations in scripts/test-installer.sh.
*/
-import { beforeEach, describe, expect, it } from "vitest";
+import { describe, expect, it } from "vitest";
import { OSS_ORIGIN } from "../src/lib/links";
import type { Measurement } from "../src/lib/download-source";
import {
- PROBE_BUDGET_MS,
+ MIRROR_POINTER_MS,
SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND,
- cacheResolution,
createDeadline,
decideDownloadSource,
parseMirror,
parseProbes,
- readCachedResolution,
selectDownloadSource,
toMirror,
+ worthRefining,
} from "../src/lib/download-source";
const MIN = SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND;
@@ -85,8 +84,8 @@ describe("parseProbes", () => {
describe("createDeadline", () => {
it("hands each phase its cap while the budget is wide open", () => {
- const deadline = createDeadline(PROBE_BUDGET_MS);
- expect(deadline.slice(2500)).toBe(2500);
+ const deadline = createDeadline(MIRROR_POINTER_MS);
+ expect(deadline.slice(500)).toBe(500);
});
it("clamps a phase to what is left rather than letting it overrun the budget", () => {
@@ -133,81 +132,6 @@ describe("parseMirror", () => {
});
});
-class MemoryStorage {
- private store = new Map<string, string>();
- get length(): number {
- return this.store.size;
- }
- key(index: number): string | null {
- return [...this.store.keys()][index] ?? null;
- }
- getItem(key: string): string | null {
- return this.store.get(key) ?? null;
- }
- setItem(key: string, value: string): void {
- this.store.set(key, value);
- }
- removeItem(key: string): void {
- this.store.delete(key);
- }
- clear(): void {
- this.store.clear();
- }
-}
-
-function stubStorage(storage: Partial<Storage>): void {
- Object.defineProperty(globalThis, "sessionStorage", { value: storage, configurable: true });
-}
-
-describe("session cache", () => {
- beforeEach(() => stubStorage(new MemoryStorage()));
-
- // The writer and the reader agreeing on the stored shape is the whole point: when they drifted,
- // every read failed validation and the page silently re-measured on every single visit.
- it("round-trips what it wrote, mirror and all", () => {
- for (const resolution of [
- { source: "oss" as const, mirror: MIRROR },
- { source: "github" as const, mirror: MIRROR },
- { source: "github" as const, mirror: null },
- ]) {
- cacheResolution(resolution);
- expect(readCachedResolution()).toEqual(resolution);
- }
- });
-
- it("returns null when nothing was ever written", () => {
- expect(readCachedResolution()).toBeNull();
- });
-
- it("refuses a stored mirror the live lookup would have refused", () => {
- sessionStorage.setItem(
- "penguin.downloadSource.v1",
- JSON.stringify({ source: "oss", mirror: { tag: TAG, base: "https://example.invalid/x" } }),
- );
- expect(readCachedResolution()).toBeNull();
- });
-
- it("refuses a stored source that is not one of the two, and unparsable entries", () => {
- for (const raw of ['{"source":"elsewhere","mirror":null}', "not json", "[]", '"github"']) {
- sessionStorage.setItem("penguin.downloadSource.v1", raw);
- expect(readCachedResolution()).toBeNull();
- }
- });
-
- it("survives storage that throws, which is what a locked-down browser does", () => {
- stubStorage({
- getItem: () => {
- throw new Error("blocked");
- },
- setItem: () => {
- throw new Error("blocked");
- },
- });
- expect(() => cacheResolution({ source: "oss", mirror: MIRROR })).not.toThrow();
- expect(readCachedResolution()).toBeNull();
- });
-});
-
const SOURCES = {
githubBase: "https://github.test/latest",
ossBase: `${OSS_ORIGIN}/releases/${TAG}`,
@@ -218,7 +142,7 @@ const PROBES = {
};
/** Records which questions were asked of which source, so "never touched" is testable. */
-function fakeProbes(github: Measurement, oss: Measurement, ossAnswers = oss.reachable) {
+function fakeProbes(github: Measurement, oss: Measurement) {
const asked: string[] = [];
return {
asked,
@@ -227,10 +151,6 @@ function fakeProbes(github: Measurement, oss: Measurement, ossAnswers = oss.reac
asked.push(`measure:${base === SOURCES.githubBase ? "github" : "oss"}`);
return base === SOURCES.githubBase ? github : oss;
},
- answers: async (base: string) => {
- asked.push(`answers:${base === SOURCES.githubBase ? "github" : "oss"}`);
- return ossAnswers;
- },
},
};
}
@@ -245,17 +165,11 @@ describe("decideDownloadSource", () => {
expect(asked).toEqual(["measure:github"]);
});
- it("settles an unreachable GitHub on whether the mirror answers, not on its speed", async () => {
+ it("hands a GitHub that stopped answering to the mirror without a second probe", async () => {
+ // The reachability pass already proved the mirror replies, so nothing more need be asked.
const { asked, io } = fakeProbes(unreachable, reachable(1));
await expect(decideDownloadSource(SOURCES, PROBES, io)).resolves.toBe("oss");
- // The cheap question, not a second megabyte: this is the branch someone waits through.
- expect(asked).toEqual(["measure:github", "answers:oss"]);
- });
-
- it("keeps GitHub when neither source answers", async () => {
- const { asked, io } = fakeProbes(unreachable, unreachable, false);
- await expect(decideDownloadSource(SOURCES, PROBES, io)).resolves.toBe("github");
- expect(asked).toEqual(["measure:github", "answers:oss"]);
+ expect(asked).toEqual(["measure:github"]);
});
// The divergence this branch split exists to prevent: a GitHub that answered but came in under
@@ -280,3 +194,13 @@ describe("decideDownloadSource", () => {
expect(asked).toEqual(["measure:github", "measure:oss"]);
});
});
+
+describe("worthRefining", () => {
+ it("measures throughput whenever there is a mirror to compare against", () => {
+ expect(worthRefining(MIRROR)).toBe(true);
+ });
+
+ it("skips the megabyte when there is no mirror to compare against", () => {
+ expect(worthRefining(null)).toBe(false);
+ });
+});