Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(download): publish complete resumable files without a request

Afloat761442a940b8
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index a81b9293..a147bc3e 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -232,6 +232,8 @@ for the idle timeout or moves on to another mirror.
Rebuilding the checksum of a saved resumable partial also uses the caller's
signal, so cancellation stops local reads before another request starts and
leaves the partial file intact for the next attempt.
+If that saved file already matches the trusted checksum, publish it without
+another network request; the usual cancellation and atomic-rename checks still apply.
Move a freshly downloaded or unpacked file or folder into place with
`renameRetrying` from `fs-retry.ts`: on Windows antivirus and indexing hold
diff --git a/packages/local-installation/src/download-complete-partial.test.ts b/packages/local-installation/src/download-complete-partial.test.ts
new file mode 100644
index 00000000..eacee2e1
--- /dev/null
+++ b/packages/local-installation/src/download-complete-partial.test.ts
@@ -0,0 +1,112 @@
+import { createHash } from "node:crypto";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { expect, it, vi } from "vitest";
+import { downloadVerified } from "./download.js";
+
+it.each(["sha256", "sha512"] as const)(
+ "publishes a complete saved download without a network request (%s)",
+ async (algorithm) => {
+ const root = await mkdtemp(path.join(tmpdir(), "download-complete-"));
+ const output = path.join(root, "runtime.tgz");
+ const bytes = Buffer.from("complete trusted runtime archive");
+ const options = {
+ url: "https://example.com/runtime.tgz",
+ output,
+ algorithm,
+ digest: createHash(algorithm).update(bytes).digest("hex"),
+ maxBytes: bytes.length,
+ resumable: true,
+ };
+ const timing = { attempts: 1, retryDelayMs: 0, idleTimeoutMs: 1_000 };
+ const cancelled = new AbortController();
+ const reason = new Error("Cancelled before publication.");
+ try {
+ await expect(
+ downloadVerified(
+ {
+ ...options,
+ signal: cancelled.signal,
+ onProgress(completed) {
+ if (completed === bytes.length) cancelled.abort(reason);
+ },
+ },
+ async () => new Response(bytes),
+ timing,
+ ),
+ ).rejects.toBe(reason);
+ expect(await readdir(root)).toEqual(["runtime.tgz.part"]);
+ expect(await readFile(`${output}.part`)).toEqual(bytes);
+
+ const offline = vi.fn<typeof fetch>(async () => {
+ throw new TypeError("Network unavailable.");
+ });
+ const progress = vi.fn();
+ await downloadVerified(
+ {
+ ...options,
+ signal: new AbortController().signal,
+ onProgress: progress,
+ },
+ offline,
+ timing,
+ );
+ expect(offline).not.toHaveBeenCalled();
+ expect(progress).toHaveBeenLastCalledWith(bytes.length, bytes.length);
+ expect(await readdir(root)).toEqual(["runtime.tgz"]);
+ expect(await readFile(output)).toEqual(bytes);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+);
+
+it.each(["incomplete", "damaged"])(
+ "still requests bytes when the saved download is %s",
+ async (kind) => {
+ const root = await mkdtemp(path.join(tmpdir(), "download-incomplete-"));
+ const output = path.join(root, "runtime.tgz");
+ const bytes = Buffer.from("trusted runtime archive");
+ const partial =
+ kind === "incomplete" ? bytes.subarray(0, 7) : Buffer.alloc(bytes.length);
+ try {
+ await writeFile(`${output}.part`, partial);
+ const fetcher = vi.fn<typeof fetch>(async (_url, init) => {
+ expect(new Headers(init?.headers).get("range")).toBe(
+ `bytes=${partial.length}-`,
+ );
+ if (kind === "damaged") return new Response(null, { status: 416 });
+ return new Response(bytes.subarray(partial.length), {
+ status: 206,
+ headers: {
+ "content-range": `bytes ${partial.length}-${bytes.length - 1}/${bytes.length}`,
+ },
+ });
+ });
+ const result = downloadVerified(
+ {
+ url: "https://example.com/runtime.tgz",
+ output,
+ algorithm: "sha256",
+ digest: createHash("sha256").update(bytes).digest("hex"),
+ maxBytes: bytes.length,
+ resumable: true,
+ signal: new AbortController().signal,
+ },
+ fetcher,
+ );
+ if (kind === "damaged") await expect(result).rejects.toThrow(/checksum/i);
+ else {
+ await result;
+ expect(await readFile(output)).toEqual(bytes);
+ }
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(await readdir(root)).toEqual(
+ kind === "damaged" ? [] : ["runtime.tgz"],
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/packages/local-installation/src/download-resume-cancel.test.ts b/packages/local-installation/src/download-resume-cancel.test.ts
index 0b588bd7..c9833b3a 100644
--- a/packages/local-installation/src/download-resume-cancel.test.ts
+++ b/packages/local-installation/src/download-resume-cancel.test.ts
@@ -78,7 +78,7 @@ it("stops reading a resumable partial when cancelled and keeps its bytes for ret
},
fetcher,
);
- expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(fetcher).not.toHaveBeenCalled();
expect(await readdir(root)).toEqual(["runtime.tgz"]);
expect((await readFile(output)).equals(bytes)).toBe(true);
} finally {
diff --git a/packages/local-installation/src/download.ts b/packages/local-installation/src/download.ts
index 32d163c1..38f8967a 100644
--- a/packages/local-installation/src/download.ts
+++ b/packages/local-installation/src/download.ts
@@ -68,7 +68,8 @@ function publicUrl(value: string) {
* Only a verified, bounded download may become an installation input. A
* failed, slow or interrupted transfer moves on to the next mirror and
* resumes there with an HTTP range request; the checksum still decides what
- * is published. Resolves to the URL that delivered the last bytes.
+ * is published. Resolves to the URL that delivered the last bytes, or the
+ * preferred URL when a complete saved file needs no request.
*/
export async function downloadVerified(
options: {
@@ -99,6 +100,7 @@ export async function downloadVerified(
: `${options.output}.${randomUUID()}.part`;
let hash: Hash = createHash(options.algorithm);
let completed = 0;
+ let completePartial = false;
if (options.resumable) {
const existing = await lstat(partial).catch(() => undefined);
if (existing?.isFile() && existing.size <= options.maxBytes) {
@@ -112,11 +114,12 @@ export async function downloadVerified(
throw error;
}
completed = existing.size;
+ completePartial = hash.copy().digest("hex") === options.digest;
} else await rm(partial, { recursive: true, force: true });
}
options.signal.throwIfAborted();
let handle = await open(partial, options.resumable ? "a" : "ax", 0o600);
- let size: number | undefined;
+ let size: number | undefined = completePartial ? completed : undefined;
let lastProgressAt = 0;
let failure = "no connection";
@@ -289,7 +292,7 @@ export async function downloadVerified(
let published = false;
let served = urls[0]!;
try {
- let result: AttemptOutcome["status"] = "next";
+ let result: AttemptOutcome["status"] = completePartial ? "done" : "next";
// Hosts that cannot serve the file leave the rotation.
let active = urls;
const slowAfterMs = timing.slowCheckAfterMs ?? 0;
@@ -298,6 +301,8 @@ export async function downloadVerified(
const slowEnabled = slowAfterMs > 0 && slowFloor > 0 && timing.attempts > 1;
let skipNextDelay = false;
rounds: for (let round = 0; round < timing.attempts; round += 1) {
+ // A cancelled publication can leave every verified byte on disk.
+ if (completePartial) break;
if (!active.length) break;
if (round > 0 && !skipNextDelay)
await delay(timing.retryDelayMs * 2 ** (round - 1), undefined, {