A local-first multi-agent app development platform, built on PenguinHarness
Make the download page wait for the speed probe instead of guessing GitHub (#406)
Yaowei Zhengcc362d951ca3
diff --git a/changelog/unreleased/2026-08-23-download-source-rule.md b/changelog/unreleased/2026-08-23-download-source-rule.mdnew file mode 100644index 00000000..d3853a24--- /dev/null+++ b/changelog/unreleased/2026-08-23-download-source-rule.md@@ -0,0 +1,35 @@+# One download-source rule for the installers and the download page++- **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)++[中文版](2026-08-23-download-source-rule.zh.md)++`install.sh`, `install.ps1` and the desktop download page each chose between GitHub and the OSS+mirror their own way. They now apply one rule, measured rather than assumed: time the release's+large probe file on GitHub, keep GitHub whenever it reaches 256 KB/s, and only below that measure+the mirror and switch to it when it is more than 1.5x faster. GitHub is the free source, so it+keeps every tie and every comparison that cannot be measured, and the mirror's bandwidth is never+spent on a probe that could not change the answer. `penguin update` inherits the rule through+`install.sh`.++## Installers++- Auto mode no longer hands a bundle under 32 MiB straight to the mirror without measuring anything; every auto install is decided by the same measurement.+- A GitHub below the minimum no longer means the mirror by default. The mirror is measured too, and has to beat GitHub by the switch ratio to take over.+- The probe budget covers the manifest, the reachability pair and up to two throughput probes, and is the sum of their caps, so the second throughput probe always gets its full window.+- Progress output names which of the two conditions decided it.++## 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.++## Docs++- The CLI install pages describe the measured selection and `PENGUIN_DOWNLOAD_SPEED_PROBE=0`, in both languages.diff --git a/changelog/unreleased/2026-08-23-download-source-rule.zh.md b/changelog/unreleased/2026-08-23-download-source-rule.zh.mdnew file mode 100644index 00000000..6959127b--- /dev/null+++ b/changelog/unreleased/2026-08-23-download-source-rule.zh.md@@ -0,0 +1,33 @@+# 安装脚本与下载页共用同一套下载源规则++- **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)++[English](2026-08-23-download-source-rule.md)++`install.sh`、`install.ps1` 与桌面端下载页此前各自决定在 GitHub 与 OSS 镜像之间怎么选。现在三者+共用同一套规则,且由实测决定而非预设:对 GitHub 上该 Release 的大测速文件计时,达到 256 KB/s 即+保持 GitHub;只有低于该值时才测量镜像,且仅当镜像快出 1.5 倍以上才切换。GitHub 是免费的源,因此+所有持平与无法测出的比较都留在 GitHub,镜像的带宽也不会花在无法改变结论的探测上。`penguin update`+经由 `install.sh` 继承同一规则。++## 安装脚本++- 自动模式不再把小于 32 MiB 的安装包直接交给镜像而不做任何测量;每一次自动安装都由同一次测量决定。+- GitHub 低于达标线不再等同于选择镜像:镜像同样会被测量,且必须以切换系数胜出才会接管。+- 测速预算涵盖 manifest、连通性探测对以及至多两次吞吐探测,其值取各段上限之和,因此第二次吞吐探测总能拿到完整的窗口。+- 进度输出会写明是两种情形中的哪一种决定了结果。++## 下载页++- 测速期间按钮以加载态等待结论,而不是先指向 GitHub,因此连不上 GitHub 的访客不会拿到一个点了也不会开始的链接。无论测速结论如何,来源仍可手动切换。+- 每个请求都受自身上限与整段 9 秒预算的双重约束;响应头与传输体各有上限,因此始终不响应的源会被判定为不可达,而不必等满传输上限。+- GitHub 不可达时,结论取决于镜像是否响应,用 64 KiB 探测文件询问;GitHub 可达但低于达标线时,则是吞吐问题,用大测速文件测量。+- 结论在浏览器会话内缓存,因此每个标签页至多测量一次。+- 吞吐量读自 Resource Timing 记录而非响应体,因为 GitHub 的 Release 资源拒绝跨源读取。++## 文档++- CLI 安装文档以两种语言说明这套实测选源,以及 `PENGUIN_DOWNLOAD_SPEED_PROBE=0`。diff --git a/packages/landing/src/components/icons.tsx b/packages/landing/src/components/icons.tsxindex 526a5f5f..1ec9979c 100644--- a/packages/landing/src/components/icons.tsx+++ b/packages/landing/src/components/icons.tsx@@ -157,6 +157,15 @@ export function RefreshIcon(props: IconProps) {);}+/** Pair it with `animate-spin`: the gap in the ring is what makes the rotation readable. */+export function SpinnerIcon(props: IconProps) {+ return (+ <Icon {...props}>+ <path d="M21 12a9 9 0 1 1-6.22-8.56" />+ </Icon>+ );+}+export function CpuIcon(props: IconProps) {return (<Icon {...props}>diff --git a/packages/landing/src/lib/download-source.ts b/packages/landing/src/lib/download-source.tsindex 98a28433..25a24c93 100644--- a/packages/landing/src/lib/download-source.ts+++ b/packages/landing/src/lib/download-source.ts@@ -20,15 +20,50 @@* two numbers are comparable — the alternative, reading OSS through CORS, would time the JS-side* buffering on one side only. GitHub's duration additionally covers the two redirect hops its* release URLs take, which can only make it read slower than it is, never faster.+ *+ * Unlike the installers, this runs with someone watching a page, so every wait is bounded twice:+ * each request has its own cap, and PROBE_BUDGET_MS caps the whole sequence. A visitor who cannot+ * reach GitHub at all is the one this matters most for, and they are also the one whose GitHub+ * request will never come back — so the answer has to be reached on a clock, not on completion.*/+import { GITHUB_LATEST_DOWNLOAD, OSS_LATEST_JSON_URL, OSS_ORIGIN } from "./links";+export const SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND = 262144;/** How much faster the mirror has to be before its paid bandwidth beats a free GitHub download. */export const SPEED_PROBE_OSS_SWITCH_RATIO = 1.5;-/** The installers' large-probe cap: a source that cannot deliver the probe in this long loses. */-export const SPEED_PROBE_TIMEOUT_MS = 8000;+/**+ * 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.+ */+export const PROBE_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;++/** A source that has not sent response headers by here is treated as unreachable, not as slow. */+const CONNECT_TIMEOUT_MS = 2500;++/**+ * 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+ * is only there to absorb GitHub's redirect hops rather than to refine a number.+ *+ * The installers allow 8s here, and that difference is deliberate. A source slower than 1 MiB per+ * cap reads as unmeasured rather than as a number, so this cap sets the floor under which the+ * tie-break rule stops seeing a speed at all: ~210 KB/s here against ~131 KB/s there. Between those+ * two figures a slow GitHub the installers would have kept goes to the mirror instead — a bandwidth+ * cost on a connection that is slow whichever source it uses, traded for a page that answers in+ * seconds. Widening it to match would put the worst case past PROBE_BUDGET_MS, with someone sitting+ * in front of it.+ */+const TRANSFER_TIMEOUT_MS = 5000;++/** Cap for the small probe, which is only ever asked whether a source answers at all. */+const REACHABILITY_TIMEOUT_MS = 2500;export type DownloadSource = "github" | "oss";@@ -39,6 +74,13 @@ export interface ReleaseProbe {size: number;}+export interface ReleaseProbes {+ /** 64 KiB: cheap enough to ask "does this source answer" without paying for a megabyte. */+ small: ReleaseProbe;+ /** 1 MiB: long enough that a throughput reading is not swallowed by connection setup. */+ large: ReleaseProbe;+}+/*** The shared rule, in one place: GitHub clears the minimum and wins outright, otherwise the mirror* has to beat it by the switch ratio to take over.@@ -51,37 +93,61 @@ export function selectDownloadSource(return ossBytesPerSecond > githubBytesPerSecond * SPEED_PROBE_OSS_SWITCH_RATIO ? "oss" : "github";}+/** A shrinking budget shared by every phase, the browser's form of the installers' total timeout. */+export interface ProbeDeadline {+ /** This phase's cap, clamped to what is left; 0 means the budget is spent. */+ slice(capMs: number): number;+}++export function createDeadline(budgetMs: number = PROBE_BUDGET_MS): ProbeDeadline {+ const endsAt = Date.now() + budgetMs;+ return { slice: (capMs) => Math.max(0, Math.min(capMs, endsAt - Date.now())) };+}+const SAFE_ASSET_NAME = /^[A-Za-z0-9._+-]+$/;+function parseProbeRow(fields: string[]): ReleaseProbe | null {+ if (fields.length !== 5) return null;+ const file = fields[2] ?? "";+ const size = Number(fields[3]);+ if (!SAFE_ASSET_NAME.test(file) || file.includes("..")) return null;+ if (!Number.isSafeInteger(size) || size <= 0) return null;+ return { file, size };+}+/**- * The large probe row of a release's download manifest, validated the way the installers validate- * it: the header has to name this exact tag, and the file name has to be a plain asset name so a- * tampered manifest cannot point the probe at another path.+ * The probe rows of a release's download manifest, validated the way the installers validate them:+ * the header has to name this exact tag, and a file name has to be a plain asset name so a tampered+ * manifest cannot point a request at another path.*/-export function parseLargeProbe(manifest: string, tag: string): ReleaseProbe | null {+export function parseProbes(manifest: string, tag: string): ReleaseProbes | null {const lines = manifest.split("\n");if (lines[0] !== `penguin-release-download-manifest\t1\t${tag}`) return null;+ let small: ReleaseProbe | null = null;+ let large: ReleaseProbe | null = null;for (const line of lines.slice(1)) {const fields = line.split("\t");- if (fields[0] !== "probe" || fields[1] !== "large") continue;- if (fields.length !== 5) return null;- const file = fields[2] ?? "";- const size = Number(fields[3]);- if (!SAFE_ASSET_NAME.test(file) || file.includes("..")) return null;- if (!Number.isSafeInteger(size) || size <= 0) return null;- return { file, size };+ if (fields[0] !== "probe") continue;+ const probe = parseProbeRow(fields);+ if (!probe) return null;+ if (fields[1] === "small") small = probe;+ if (fields[1] === "large") large = probe;}- return null;+ return small && large ? { small, large } : null;}/**- * A fresh query string per probe: a cached hit would time the disk rather than the network, and it- * keeps every measurement on a resource timing entry name of its own.+ * A fresh query string per request: a cached hit would time the disk rather than the network, and+ * it keeps every measurement on a resource timing entry name of its own.*/function probeUrl(base: string, file: string): string {return `${base}/${file}?probe=${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;}+function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}+/** The entry's duration in ms, or null when none is recorded before the deadline. */function awaitResourceTiming(url: string, timeoutMs: number): Promise<number | null> {if (typeof PerformanceObserver === "undefined") return Promise.resolve(null);@@ -107,30 +173,80 @@ function awaitResourceTiming(url: string, timeoutMs: number): Promise<number | n});}-/** Bytes per second for one probe download; 0 when it did not complete inside the deadline. */-export async function measureBytesPerSecond(+/**+ * Starts an opaque request and resolves once its headers land, or null if they do not land inside+ * `connectMs`. The returned `settled` promise is the transfer itself; the caller decides how long+ * to wait for the body and keeps `abort` armed until then, so a stalled body is cut off rather than+ * measured. Opaque is the only option for GitHub, whose release assets refuse cross-origin reads.+ */+function startProbeRequest(url: string,- sizeBytes: number,- timeoutMs: number = SPEED_PROBE_TIMEOUT_MS,- signal?: AbortSignal,-): Promise<number> {+ connectMs: number,+): { reachable: Promise<boolean>; abort: () => void } {const controller = new AbortController();- const deadline = setTimeout(() => controller.abort(), timeoutMs);- signal?.addEventListener("abort", () => controller.abort(), { once: true });- if (signal?.aborted) controller.abort();- const timing = awaitResourceTiming(url, timeoutMs);+ if (connectMs <= 0) {+ controller.abort();+ return { reachable: Promise.resolve(false), abort: () => controller.abort() };+ }+ const headers = fetch(url, {+ mode: "no-cors",+ cache: "no-store",+ signal: controller.signal,+ }).then(+ () => true,+ () => false,+ );+ const reachable = Promise.race([headers, delay(connectMs).then(() => false)]).then((ok) => {+ if (!ok) controller.abort();+ return ok;+ });+ return { reachable, abort: () => controller.abort() };+}++/** Whether a source answers at all, asked with the cheap 64 KiB probe. */+export async function probeReachable(url: string, deadline: ProbeDeadline): Promise<boolean> {+ const { reachable, abort } = startProbeRequest(url, deadline.slice(REACHABILITY_TIMEOUT_MS));+ const ok = await reachable;+ abort();+ return ok;+}++/**+ * What one probe learned about a source. The two fields answer two different questions, and the+ * installers keep them apart too: their small-probe pair settles reachability before any throughput+ * probe runs. A source that never answered loses to one that did, full stop; a source that answered+ * but could not finish the probe is merely unmeasured, and the rule's tie-break decides it.+ */+export interface Measurement {+ /** Response headers landed inside the connect cap. */+ reachable: boolean;+ /** Throughput, or 0 when the transfer did not finish inside the transfer cap. */+ bytesPerSecond: number;+}++const UNREACHABLE: Measurement = { reachable: false, bytesPerSecond: 0 };++/** Measures one probe download under both caps. */+export async function measureSource(+ url: string,+ sizeBytes: number,+ deadline: ProbeDeadline,+): Promise<Measurement> {+ const { reachable, abort } = startProbeRequest(url, deadline.slice(CONNECT_TIMEOUT_MS));try {- // An opaque fetch settles once the headers land, not once the body does. The timing entry is- // what waits for the transfer to finish; the abort above is what bounds it, and stays armed- // until then so a stalled body is cut off rather than measured.- await fetch(url, { mode: "no-cors", cache: "no-store", signal: controller.signal });- const durationMs = await timing;- if (controller.signal.aborted || durationMs === null || durationMs <= 0) return 0;- return Math.round((sizeBytes * 1000) / durationMs);+ if (!(await reachable)) return UNREACHABLE;+ const transferMs = deadline.slice(TRANSFER_TIMEOUT_MS);+ if (transferMs <= 0) return { reachable: true, bytesPerSecond: 0 };+ const durationMs = await awaitResourceTiming(url, transferMs);+ const measured = durationMs !== null && durationMs > 0;+ return {+ reachable: true,+ bytesPerSecond: measured ? Math.round((sizeBytes * 1000) / durationMs) : 0,+ };} catch {- return 0;+ return UNREACHABLE;} finally {- clearTimeout(deadline);+ abort();}}@@ -140,41 +256,92 @@ export interface ProbeSources {}/**- * Applies the rule to one release. OSS is measured only once GitHub has failed the minimum: above- * it GitHub has already won, and the mirror's bandwidth is not spent on a probe that could not- * change the answer. The two run one after the other on purpose — concurrent transfers share the- * link and would each read as half as fast, which an absolute threshold cannot tolerate.+ * 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.+ */+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.+ *+ * 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.+ *+ * 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.*/-export async function probeDownloadSource(+export async function decideDownloadSource(+ sources: ProbeSources,+ probes: ReleaseProbes,+ io: SourceProbes,+): 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";+ }+ const oss = await io.measure(sources.ossBase, probes.large);+ return selectDownloadSource(github.bytesPerSecond, oss.bytesPerSecond);+}++/** The decision above, wired to real requests under the shared budget. */+export function probeDownloadSource(sources: ProbeSources,- probe: ReleaseProbe,- signal?: AbortSignal,+ probes: ReleaseProbes,+ deadline: ProbeDeadline,): Promise<DownloadSource> {- const measure = (base: string) =>- measureBytesPerSecond(probeUrl(base, probe.file), probe.size, SPEED_PROBE_TIMEOUT_MS, signal);- const github = await measure(sources.githubBase);- if (github >= SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND) return "github";- return selectDownloadSource(github, await measure(sources.ossBase));+ return decideDownloadSource(sources, probes, {+ measure: (base, probe) => measureSource(probeUrl(base, probe.file), probe.size, deadline),+ answers: (base, probe) => probeReachable(probeUrl(base, probe.file), deadline),+ });+}++/** Reads a small JSON/TSV lookup under the shared budget; null on any failure. */+async function fetchMetadata(url: string, deadline: ProbeDeadline): Promise<Response | null> {+ const timeoutMs = deadline.slice(METADATA_TIMEOUT_MS);+ if (timeoutMs <= 0) return null;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const res = await fetch(url, { cache: "no-store", signal: controller.signal });+ return res.ok ? res : null;+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }}/**- * The release's large probe row, read from the mirror — the one origin of the two that answers a+ * The release's probe rows, read from the mirror — the one origin of the two that answers a* cross-origin read at all, and the same file the installers parse.*/-export async function fetchLargeProbe(+export async function fetchProbes(ossBase: string,tag: string,- signal?: AbortSignal,-): Promise<ReleaseProbe | null> {- try {- const res = await fetch(`${ossBase}/release-download-manifest.tsv`, {- signal,- cache: "no-store",- });- return res.ok ? parseLargeProbe(await res.text(), tag) : null;- } catch {- return null;- }+ deadline: ProbeDeadline,+): Promise<ReleaseProbes | null> {+ const res = await fetchMetadata(`${ossBase}/release-download-manifest.tsv`, deadline);+ return res ? parseProbes(await res.text(), tag) : null;+}++/** Reads the mirror pointer under the shared budget. */+export async function fetchMirrorPointer(+ url: string,+ deadline: ProbeDeadline,+): Promise<unknown | null> {+ const res = await fetchMetadata(url, deadline);+ return res ? await res.json() : null;}/** Data Saver is a request not to spend a megabyte on measuring; the unprobed default stands. */@@ -183,3 +350,92 @@ export function probingAllowed(): boolean {const connection = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;return connection?.saveData !== true;}++/** The OSS mirror the buttons would use: an immutable per-tag directory in the release bucket. */+export interface Mirror {+ tag: string;+ 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._-]*$/;++/**+ * The only shape a mirror is ever allowed to take: a safe release tag, and the exact bucket path+ * that tag implies. Every way a mirror can enter the page goes through here — the live pointer and+ * the session cache alike — so neither metadata nor stored state can aim a download at some other+ * host. Keep it that way: a second definition is a second thing to get wrong.+ */+export function toMirror(tag: unknown, base: unknown): Mirror | null {+ if (typeof tag !== "string" || !RELEASE_TAG.test(tag)) return null;+ if (base !== `${OSS_ORIGIN}/releases/${tag}`) return null;+ return { tag, base };+}++/** latest.json validated like the installer forwarders validate it: schema 1, then the shape above. */+export function parseMirror(value: unknown): Mirror | null {+ if (typeof value !== "object" || value === null) return null;+ const manifest = value as { schemaVersion?: unknown; tag?: unknown; releaseBaseUrl?: unknown };+ if (manifest.schemaVersion !== 1) return null;+ return toMirror(manifest.tag, manifest.releaseBaseUrl);+}++/**+ * 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.+ */+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 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.+ }+}++/**+ * 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.+ */+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 };+ const probes = await fetchProbes(mirror.base, mirror.tag, deadline);+ if (!probes) return { source: "github", mirror };+ const source = await 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.tsindex 7b2951ab..c6709376 100644--- a/packages/landing/src/lib/strings-en.ts+++ b/packages/landing/src/lib/strings-en.ts@@ -103,6 +103,7 @@ 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 …",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.tsindex 94b26abe..fee5b397 100644--- a/packages/landing/src/lib/strings.ts+++ b/packages/landing/src/lib/strings.ts@@ -105,6 +105,7 @@ export const zh = {windows: { name: "Windows", require: "Windows 10 及以上(x64),NSIS 安装程序" },linux: { name: "Linux", require: "x64,AppImage 免安装运行,或 deb 交给包管理器" },},+ statusProbing: "正在为你测试下载源,选出更快的那个……",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.tsxindex 7f85942b..7465a110 100644--- a/packages/landing/src/pages/download.tsx+++ b/packages/landing/src/pages/download.tsx@@ -1,16 +1,24 @@/**- * Desktop download page. The buttons are static GitHub `releases/latest/download/<name>`- * links by default — always valid because installer names are version-less — and swap to- * the OSS mirror's immutable per-tag URLs only when the mirror earns them: the bucket's- * `latest.json` pointer has to resolve (validated the same way the installers validate- * it), 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 — silently keeps the free GitHub links. Plain-anchor downloads are never CORS-gated;- * only the version lookup and the probe are. Whatever the probe decides, the visitor can- * still switch sources by hand below the cards. Below that, 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.+ * 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.+ *+ * 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.+ *+ * Plain-anchor downloads are never CORS-gated; only the version lookup and the probe 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 { Link } from "react-router";@@ -22,25 +30,22 @@ import {GITHUB_LATEST_DOWNLOAD,LINUX_APPIMAGE_CHMOD_CMD,MAC_UNQUARANTINE_CMD,- OSS_LATEST_JSON_URL,- OSS_ORIGIN,RELEASES_URL,} from "../lib/links";import { detectPlatform } from "../lib/platform";import type { Platform } from "../lib/platform";-import { fetchLargeProbe, probeDownloadSource, probingAllowed } from "../lib/download-source";-import type { DownloadSource } from "../lib/download-source";+import {+ cacheResolution,+ readCachedResolution,+ resolveDownloadSource,+} from "../lib/download-source";+import type { DownloadSource, Resolution } from "../lib/download-source";import { Section } from "../components/section";import { CodeCard } from "../components/code-card";-import { ChevronDownIcon, DownloadIcon, ExternalLinkIcon } from "../components/icons";+import { ChevronDownIcon, DownloadIcon, ExternalLinkIcon, SpinnerIcon } from "../components/icons";const PLATFORMS: Platform[] = ["mac", "windows", "linux"];-interface Mirror {- tag: string;- base: string;-}-/*** One collapsible item of the first-launch FAQ. `defaultOpen` pre-expands the visitor's* own platform on mount; after that the element owns its open state (React only writes@@ -71,58 +76,31 @@ function FaqItem({);}-/** latest.json validated like the installer forwarders validate it: schema 1, safe v-tag, fixed bucket base. */-function parseMirror(value: unknown): Mirror | null {- if (typeof value !== "object" || value === null) return null;- const manifest = value as { schemaVersion?: unknown; tag?: unknown; releaseBaseUrl?: unknown };- if (manifest.schemaVersion !== 1 || typeof manifest.tag !== "string") return null;- if (!/^v[0-9A-Za-z][0-9A-Za-z._-]*$/.test(manifest.tag)) return null;- if (manifest.releaseBaseUrl !== `${OSS_ORIGIN}/releases/${manifest.tag}`) return null;- return { tag: manifest.tag, base: manifest.releaseBaseUrl };-}-export function DownloadPage() {- const [mirror, setMirror] = useState<Mirror | null>(null);- /** What the probe settled on; null while it is still running or never ran. */- const [probed, setProbed] = useState<DownloadSource | null>(null);+ /** 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 [override, setOverride] = useState<DownloadSource | null>(null);useEffect(() => {- const controller = new AbortController();- const lookupTimer = setTimeout(() => controller.abort(), 5000);+ // The session cache already answered, so there is nothing to measure and no spinner to show.+ if (resolution) return;let cancelled = false;- // Resolve the mirror, then measure. Every failure lands on GitHub, which the buttons already- // point at — nothing here can leave the page without a working download.- void (async () => {- let found: Mirror | null = null;- try {- const res = await fetch(OSS_LATEST_JSON_URL, { signal: controller.signal });- found = res.ok ? parseMirror(await res.json()) : null;- } catch {- found = null;- }- clearTimeout(lookupTimer);- if (cancelled || !found) return;- setMirror(found);- if (!probingAllowed()) return;- const probe = await fetchLargeProbe(found.base, found.tag, controller.signal);- if (cancelled || !probe) return;- const source = await probeDownloadSource(- { githubBase: GITHUB_LATEST_DOWNLOAD, ossBase: found.base },- probe,- controller.signal,- );- if (!cancelled) setProbed(source);- })();+ void resolveDownloadSource().then((resolved) => {+ cacheResolution(resolved);+ if (!cancelled) setResolution(resolved);+ });return () => {cancelled = true;- clearTimeout(lookupTimer);- controller.abort();};+ // 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 selected: DownloadSource = override ?? probed ?? "github";+ const probing = resolution === null;+ const mirror = resolution?.mirror ?? null;+ const selected: DownloadSource = override ?? resolution?.source ?? "github";const viaMirror = mirror !== null && selected === "oss";const hrefFor = (file: string) =>viaMirror ? `${mirror.base}/${file}` : `${GITHUB_LATEST_DOWNLOAD}/${file}`;@@ -159,10 +137,22 @@ export function DownloadPage() {{DESKTOP_INSTALLERS[platform].map(({ file, variant }) => (<akey={file}- href={hrefFor(file)}- className="inline-flex items-center justify-center gap-1.5 rounded-md bg-gray-900 px-3.5 py-2 text-sm font-medium text-white transition-colors hover:bg-gray-700 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-300"+ // No href while probing: an anchor without one is not a link, which is exactly+ // the state this is in — the source is not decided yet. The label and the box+ // keep their size, so nothing shifts under the pointer when it resolves.+ href={probing ? undefined : hrefFor(file)}+ aria-disabled={probing || undefined}+ className={`inline-flex items-center justify-center gap-1.5 rounded-md px-3.5 py-2 text-sm font-medium transition-colors ${+ probing+ ? "cursor-progress bg-gray-200 text-gray-500 dark:bg-gray-800 dark:text-gray-500"+ : "bg-gray-900 text-white hover:bg-gray-700 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-300"+ }`}>- <DownloadIcon className="h-4 w-4" />+ {probing ? (+ <SpinnerIcon className="h-4 w-4 animate-spin" />+ ) : (+ <DownloadIcon className="h-4 w-4" />+ )}{variant}</a>))}@@ -172,16 +162,25 @@ export function DownloadPage() {</div><div className="mx-auto mt-8 max-w-4xl text-center text-sm text-gray-600 dark:text-gray-400">- <p>- {viaMirror ? S.download.statusOss(mirror.tag) : S.download.statusGithub}{" "}- {mirror !== null && (- <button- type="button"- className={textLink}- onClick={() => setOverride(viaMirror ? "github" : "oss")}- >- {viaMirror ? S.download.altGithub : S.download.altOss}- </button>+ <p aria-live="polite">+ {probing ? (+ <span className="inline-flex items-center gap-1.5">+ <SpinnerIcon className="h-3.5 w-3.5 animate-spin" />+ {S.download.statusProbing}+ </span>+ ) : (+ <>+ {viaMirror ? S.download.statusOss(mirror.tag) : S.download.statusGithub}{" "}+ {mirror !== null && (+ <button+ type="button"+ className={textLink}+ onClick={() => setOverride(viaMirror ? "github" : "oss")}+ >+ {viaMirror ? S.download.altGithub : S.download.altOss}+ </button>+ )}+ </>)}</p><p className="mt-2">diff --git a/packages/landing/test/download-source.test.ts b/packages/landing/test/download-source.test.tsindex 07016684..3c97d988 100644--- a/packages/landing/test/download-source.test.ts+++ b/packages/landing/test/download-source.test.ts@@ -4,11 +4,20 @@* 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 { describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it } from "vitest";+import { OSS_ORIGIN } from "../src/lib/links";+import type { Measurement } from "../src/lib/download-source";import {+ PROBE_BUDGET_MS,SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND,- parseLargeProbe,+ cacheResolution,+ createDeadline,+ decideDownloadSource,+ parseMirror,+ parseProbes,+ readCachedResolution,selectDownloadSource,+ toMirror,} from "../src/lib/download-source";const MIN = SPEED_PROBE_GITHUB_MIN_BYTES_PER_SECOND;@@ -44,27 +53,230 @@ const MANIFEST = ["",].join("\n");-describe("parseLargeProbe", () => {- it("reads the large probe row of a manifest for this exact tag", () => {- expect(parseLargeProbe(MANIFEST, TAG)).toEqual({ file: "probe-1m.bin", size: 1048576 });+describe("parseProbes", () => {+ it("reads both probe rows of a manifest for this exact tag", () => {+ expect(parseProbes(MANIFEST, TAG)).toEqual({+ small: { file: "probe-64k.bin", size: 65536 },+ large: { file: "probe-1m.bin", size: 1048576 },+ });});it("refuses a manifest published for another tag", () => {- expect(parseLargeProbe(MANIFEST, "v9.9.9")).toBeNull();+ expect(parseProbes(MANIFEST, "v9.9.9")).toBeNull();});it("refuses a probe name that is not a plain asset name", () => {const escaped = MANIFEST.replace("probe-1m.bin", "../../etc/passwd");- expect(parseLargeProbe(escaped, TAG)).toBeNull();+ expect(parseProbes(escaped, TAG)).toBeNull();});it("refuses a size that is not a positive integer", () => {- expect(parseLargeProbe(MANIFEST.replace("\t1048576\t", "\t0\t"), TAG)).toBeNull();- expect(parseLargeProbe(MANIFEST.replace("\t1048576\t", "\tlots\t"), TAG)).toBeNull();+ expect(parseProbes(MANIFEST.replace("\t1048576\t", "\t0\t"), TAG)).toBeNull();+ expect(parseProbes(MANIFEST.replace("\t1048576\t", "\tlots\t"), TAG)).toBeNull();});- it("returns null when the release carries no large probe at all", () => {- const rows = MANIFEST.split("\n").filter((line) => !line.startsWith("probe\tlarge"));- expect(parseLargeProbe(rows.join("\n"), TAG)).toBeNull();+ it("returns null unless the release carries both probes", () => {+ for (const dropped of ["probe\tlarge", "probe\tsmall"]) {+ const rows = MANIFEST.split("\n").filter((line) => !line.startsWith(dropped));+ expect(parseProbes(rows.join("\n"), TAG)).toBeNull();+ }+ });+});++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);+ });++ it("clamps a phase to what is left rather than letting it overrun the budget", () => {+ const deadline = createDeadline(1200);+ expect(deadline.slice(5000)).toBeLessThanOrEqual(1200);+ expect(deadline.slice(5000)).toBeGreaterThan(0);+ });++ it("hands out zero once the budget is spent, so the phase fails instead of waiting", () => {+ expect(createDeadline(0).slice(5000)).toBe(0);+ expect(createDeadline(-1).slice(5000)).toBe(0);+ });+});++const MIRROR = { tag: TAG, base: `${OSS_ORIGIN}/releases/${TAG}` };++describe("toMirror", () => {+ it("accepts a safe tag paired with the bucket path that tag implies", () => {+ expect(toMirror(MIRROR.tag, MIRROR.base)).toEqual(MIRROR);+ });++ it("refuses a base that does not belong to the tag, or to the bucket at all", () => {+ expect(toMirror(TAG, `${OSS_ORIGIN}/releases/v9.9.9`)).toBeNull();+ expect(toMirror(TAG, `https://example.invalid/releases/${TAG}`)).toBeNull();+ expect(toMirror(TAG, `${OSS_ORIGIN}/releases/${TAG}/..`)).toBeNull();+ });++ it("refuses a tag that is not a plain release tag", () => {+ expect(toMirror("../invalid", `${OSS_ORIGIN}/releases/../invalid`)).toBeNull();+ expect(toMirror(1, MIRROR.base)).toBeNull();+ });+});++describe("parseMirror", () => {+ it("reads a schema-1 pointer", () => {+ const pointer = { schemaVersion: 1, tag: TAG, releaseBaseUrl: MIRROR.base };+ expect(parseMirror(pointer)).toEqual(MIRROR);+ });++ it("refuses anything that is not a schema-1 object", () => {+ expect(parseMirror({ schemaVersion: 2, tag: TAG, releaseBaseUrl: MIRROR.base })).toBeNull();+ expect(parseMirror(null)).toBeNull();+ expect(parseMirror("v1.2.3")).toBeNull();+ });+});++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}`,+};+const PROBES = {+ small: { file: "probe-64k.bin", size: 65536 },+ large: { file: "probe-1m.bin", size: 1048576 },+};++/** Records which questions were asked of which source, so "never touched" is testable. */+function fakeProbes(github: Measurement, oss: Measurement, ossAnswers = oss.reachable) {+ const asked: string[] = [];+ return {+ asked,+ io: {+ measure: async (base: string) => {+ 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;+ },+ },+ };+}++const reachable = (bytesPerSecond: number): Measurement => ({ reachable: true, bytesPerSecond });+const unreachable: Measurement = { reachable: false, bytesPerSecond: 0 };++describe("decideDownloadSource", () => {+ it("keeps GitHub at the minimum without spending a byte of the mirror's bandwidth", async () => {+ const { asked, io } = fakeProbes(reachable(MIN), reachable(MIN * 10));+ await expect(decideDownloadSource(SOURCES, PROBES, io)).resolves.toBe("github");+ expect(asked).toEqual(["measure:github"]);+ });++ it("settles an unreachable GitHub on whether the mirror answers, not on its speed", async () => {+ 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"]);+ });++ // The divergence this branch split exists to prevent: a GitHub that answered but came in under+ // the minimum is a throughput question, and the mirror has to win it by the switch ratio. Reading+ // it as "unreachable" would hand the download to a mirror only 1.2x faster.+ it("makes a slow-but-reachable GitHub a throughput question, ratio and all", async () => {+ const slow = reachable(MIN / 2);+ for (const [ossSpeed, expected] of [+ [MIN / 2 + 1, "github"],+ [(MIN / 2) * 1.5, "github"],+ [(MIN / 2) * 1.51, "oss"],+ ] as const) {+ const { asked, io } = fakeProbes(slow, reachable(ossSpeed));+ await expect(decideDownloadSource(SOURCES, PROBES, io)).resolves.toBe(expected);+ expect(asked).toEqual(["measure:github", "measure:oss"]);+ }+ });++ it("lets any measured mirror beat a GitHub that answered but finished nothing", async () => {+ const { asked, io } = fakeProbes(reachable(0), reachable(1));+ await expect(decideDownloadSource(SOURCES, PROBES, io)).resolves.toBe("oss");+ expect(asked).toEqual(["measure:github", "measure:oss"]);});});