Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 93 additions & 16 deletions apps/mobile/src/adapters/device.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Directory, DownloadTask, File, Paths } from "expo-file-system";
import * as Network from "expo-network";
import { Linking, Platform } from "react-native";
import { AppState, Linking, Platform } from "react-native";
import { allowedCpuSet, cpuListText, initialPlan, threadPlan, threadsReload, withThreads, type HardwareFacts, type RuntimePlan, type ThreadPlan } from "@hermit/model";
import { HermitNotifications } from "../../modules/hermit-notifications";
import { pausesFor, readResumeRecord, resumableBytes, resumePlan, resumeRecordText, type ResumeRecord } from "../download-resume";
import { nightDeviceState, type NightDeviceState } from "../night-device";
import { byteCount, hardwareFactsFor, hardwarePlatform, thermalFromNative, type NativeThermal } from "../platform-facts";
import { observedTokensPerSecond } from "./qvac-engine";
Expand All @@ -15,6 +16,27 @@ export function onReconnect(listener: () => void): () => void {
return () => sub.remove();
}

/** The model download running now, so it can be paused to keep its iOS resume data. */
let active: DownloadTask | undefined;

/**
* iOS (#127): pauses the running model download when the app goes to the background or the connection drops, so
* NSURLSession's resume data is saved next to `.part` and the next attempt picks up from it. expo-file-system hands
* the resume data back only from a pause, never from a failure. Does nothing on Android, which keeps `.part` on disk.
* Returns unsubscribe.
*/
export function pauseDownloadWhenLeaving(): () => void {
const pause = (signal: { appState?: string; connected?: boolean }) => {
if (pausesFor(Platform.OS, signal) && active?.state === "active") void active.pauseAsync().catch(() => {});
};
const app = AppState.addEventListener("change", (appState) => pause({ appState }));
const net = Network.addNetworkStateListener((s) => pause({ connected: s.isConnected }));
return () => {
app.remove();
net.remove();
};
}

/** Android's storage page (EC-ONB-03), falling back to the app's own settings page. */
export async function openStorageSettings(): Promise<void> {
try {
Expand Down Expand Up @@ -52,15 +74,34 @@ export function verifiedSha256(name: string): string | undefined {
* A model in place without its verification record goes back to `.part` first, so it is hashed again
* before it can ever load; it is never trusted as is.
*/
export function partialBytes(name: string): number {
export function partialBytes(name: string, url: string): number {
const final = modelFile(name);
const part = modelFile(`${name}.part`);
const sidecar = modelFile(`${name}.sha256`);
if (final.exists && !sidecar.exists) {
if (part.exists) part.delete();
final.move(part);
}
return part.exists ? byteCount(part.size) : 0;
return resumableBytesOf(name, url);
}

/** iOS: NSURLSession's resume data for `<name>.part`, saved when the download paused (#127). */
const resumeFile = (name: string) => modelFile(`${name}.part.resume`);

/** The saved resume data for this URL, when it is there and well formed; never throws. */
function savedResume(name: string, url: string, size?: number): ResumeRecord | undefined {
try {
const f = resumeFile(name);
return f.exists ? readResumeRecord(f.textSync(), url, size) : undefined;
} catch {
return undefined;
}
}

/** Bytes a download of `<name>` can resume from: `.part` on disk, or on iOS the saved resume data. Moves nothing. */
export function resumableBytesOf(name: string, url: string): number {
const part = modelFile(`${name}.part`);
return resumableBytes(Platform.OS, part.exists ? byteCount(part.size) : 0, savedResume(name, url));
}

/**
Expand All @@ -72,32 +113,68 @@ export function partialBytes(name: string): number {
* starts clean (a retry after a failed check, US-ONB-07); more than 0 resumes from that byte with an
* HTTP Range request (lost connection, full disk, app killed). A failed attempt keeps `.part` so the
* next one can resume; only discard() (after a hash mismatch) deletes it.
*
* iOS (#127) writes `.part` only once the file is complete, and resumes from the resume data NSURLSession
* produced when the task paused, saved in `<name>.part.resume`; see download-resume.ts for which path runs.
*/
export async function phoneDownload(url: string, name: string, from: number, onProgress: (received: number) => void, expectedSize?: number) {
const final = modelFile(name);
const part = modelFile(`${name}.part`);
const sidecar = modelFile(`${name}.sha256`);
const saved = resumeFile(name);
// Whatever sits at the final name is not trusted by a new attempt: back to .part, record removed.
if (final.exists) {
if (part.exists) part.delete();
final.move(part);
}
if (sidecar.exists) sidecar.delete();
const offset = from > 0 && part.exists ? Math.min(from, byteCount(part.size)) : 0;
if (offset === 0 && part.exists) part.delete();
const onBytes = { onProgress: ({ bytesWritten }: { bytesWritten: number | bigint }) => onProgress(byteCount(bytesWritten)) };
const record = savedResume(name, url, expectedSize);
// Resume data is used once: a resumed task that pauses again saves a fresh record, so a stale one never lingers.
if (saved.exists) saved.delete();
const plan = resumePlan(Platform.OS, { from, partBytes: part.exists ? byteCount(part.size) : 0, expectedSize, record });
if (plan.kind === "clean" && part.exists) part.delete();
let received = 0;
const onBytes = {
onProgress: ({ bytesWritten }: { bytesWritten: number | bigint }) => {
received = byteCount(bytesWritten);
onProgress(received);
},
};
const restored = (resumeData: string) => DownloadTask.fromSavable({ url, fileUri: part.uri, isDirectory: false, resumeData }, onBytes);
let task: DownloadTask | undefined;
let file: File | null;
if (offset > 0 && offset === expectedSize) {
// Complete already: go straight to the check, which still runs.
onProgress(offset);
file = part;
} else if (offset > 0) {
// Android resume data is the byte offset; the native task truncates to it and appends (Range).
file = await DownloadTask.fromSavable({ url, fileUri: part.uri, isDirectory: false, resumeData: String(offset) }, onBytes).resumeAsync();
} else {
file = await File.createDownloadTask(url, part, onBytes).downloadAsync();
try {
if (plan.kind === "complete") {
// Complete already: go straight to the check, which still runs.
onProgress(byteCount(part.size));
file = part;
} else if (plan.kind === "range") {
// Android resume data is the byte offset; the native task truncates to it and appends (Range).
file = await (task = active = restored(String(plan.offset))).resumeAsync();
} else if (plan.kind === "resume_data") {
// iOS: NSURLSession's own resume data from the pause. If it is rejected (stale, or the system cleared the
// bytes it kept), one clean restart from zero instead, so a bad record never blocks the download.
received = plan.offset;
onProgress(plan.offset);
try {
file = await (task = active = restored(plan.resumeData)).resumeAsync();
} catch {
received = 0;
onProgress(0);
file = await (task = active = File.createDownloadTask(url, part, onBytes)).downloadAsync();
}
} else {
file = await (task = active = File.createDownloadTask(url, part, onBytes)).downloadAsync();
}
} finally {
if (active === task) active = undefined;
}
// iOS keeps nothing in .part until the end: a pause saves NSURLSession's resume data next to it instead.
if (!file && task?.state === "paused" && Platform.OS === "ios") {
const text = resumeRecordText(url, task.savable().resumeData, received);
if (text) saved.write(text);
}
if (!file) throw new Error("download paused"); // .part stays for the next resume
if (!file) throw new Error("download paused"); // .part (Android) or its resume data (iOS) stays for the next resume
return {
/** Native streamed SHA-256 (seconds, off the JS thread); the JS chunks() path stays for tests and fallback. */
sha256: () => HermitNotifications.sha256File(file.uri),
Expand Down
4 changes: 2 additions & 2 deletions apps/mobile/src/adapters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,10 @@ export function downloadModel(url: string, from: number, onProgress: (received:

/** Bytes of an unverified partial download on disk, for resuming after a kill or a drop (EC-ONB-04). */
export function partialModel(file: { url: string }): number {
return partialBytes(file.url.split("/").pop() ?? "model.gguf");
return partialBytes(file.url.split("/").pop() ?? "model.gguf", file.url);
}

export { onReconnect, openStorageSettings } from "./device";
export { onReconnect, openStorageSettings, pauseDownloadWhenLeaving } from "./device";

/** True only when the model in place was promoted with exactly the SHA-256 this build pins, or an update made one active. */
export function modelReady(file: { url: string; sha256: string }): boolean {
Expand Down
15 changes: 10 additions & 5 deletions apps/mobile/src/adapters/model-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
type UpdateStep,
} from "@hermit/model";
import { HermitNotifications } from "../../modules/hermit-notifications";
import { modelFile, phoneDownload, phoneFacts } from "./device";
import { modelFile, phoneDownload, phoneFacts, resumableBytesOf } from "./device";
import { countedFetch, countOutbound } from "./net";
import { byteCount } from "../platform-facts";

Expand Down Expand Up @@ -118,7 +118,7 @@ async function apply(e: UpdateEffect): Promise<UpdateEvent> {
await phoneDownload(e.url, e.fileName, e.from, () => {}, expected);
return { type: "downloaded" };
} catch {
return { type: "download_failed", received: modelFile(`${e.fileName}.part`).exists ? byteCount(modelFile(`${e.fileName}.part`).size) : 0 };
return { type: "download_failed", received: resumableBytesOf(e.fileName, e.url) };
}
}
case "verify": {
Expand Down Expand Up @@ -153,7 +153,7 @@ async function apply(e: UpdateEffect): Promise<UpdateEvent> {
return { type: "self_test", passed: smokePassed(reply) };
}
case "delete_file": {
for (const name of [e.fileName, `${e.fileName}.part`, `${e.fileName}.sha256`]) {
for (const name of [e.fileName, `${e.fileName}.part`, `${e.fileName}.part.resume`, `${e.fileName}.sha256`]) {
const f = modelFile(name);
if (f.exists) f.delete();
}
Expand Down Expand Up @@ -214,8 +214,13 @@ export function recoverModelUpdate(): Promise<void> {
state = journal;
return exclusive(async () => {
const pointer = readJson<InstalledModel>(POINTER);
const staged = journal.phase === "downloading" || journal.phase === "waiting" ? modelFile(`${stagedName(journal)}.part`) : undefined;
await run(recoverUpdate(journal, { pointerSha256: pointer?.sha256, stagedBytes: staged?.exists ? byteCount(staged.size) : undefined }));
let stagedBytes: number | undefined;
if (journal.phase === "downloading" || journal.phase === "waiting") {
const staged = modelFile(`${stagedName(journal)}.part`);
// iOS has no .part mid-download; its saved resume data says how far it got (#127).
stagedBytes = staged.exists ? byteCount(staged.size) : resumableBytesOf(stagedName(journal), journal.manifest.file.url) || undefined;
}
await run(recoverUpdate(journal, { pointerSha256: pointer?.sha256, stagedBytes }));
});
}

Expand Down
6 changes: 5 additions & 1 deletion apps/mobile/src/app/download.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { router, useLocalSearchParams } from "expo-router";
import { useCallback, useEffect, useReducer, useRef, useState } from "react";
import { AppState, View } from "react-native";
import { PROFILES, assertPinnedUrl, classifyInterruption, downloadView, floorCheck, percent, reduceDownload, resumesOnReturn, type DegradedReason, type DownloadAction, type DownloadEvent, type DownloadState } from "@hermit/model";
import { deviceFacts, downloadModel, floorFacts, modelReady, NotWiredError, onReconnect, openStorageSettings, partialModel } from "../adapters";
import { deviceFacts, downloadModel, floorFacts, modelReady, NotWiredError, onReconnect, openStorageSettings, partialModel, pauseDownloadWhenLeaving } from "../adapters";
import { currentLocale, t } from "../i18n";
import { Btn, Group, Row, T } from "../components/kit";
import { Onb } from "../components/Onboarding";
Expand Down Expand Up @@ -102,6 +102,10 @@ export default function Download() {
};
}, [run, allowMobile]);

// iOS (#127): leaving the app or losing the connection pauses the download so it keeps its place; the pause lands
// as an interrupted download above, and coming back or reconnecting resumes it. Nothing on Android.
useEffect(() => pauseDownloadWhenLeaving(), []);

const onAction = (id: DownloadAction) => {
switch (id) {
case "start":
Expand Down
79 changes: 79 additions & 0 deletions apps/mobile/src/download-resume.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/// <reference types="node" />
// How a stopped model download resumes on each platform (issue #127). Made-up URL, sizes and resume data.
import { test } from "node:test";
import assert from "node:assert/strict";
import { pausesFor, readResumeRecord, resumePlan, resumeRecordText, resumableBytes } from "./download-resume.ts";

const url = "https://example.com/models/made-up.gguf";
const size = 1_000_000;
// A stand-in for the base64 blob NSURLSession produces when a task pauses.
const blob = Buffer.from("<plist>made-up resume data</plist>").toString("base64");
const record = { url, resumeData: blob, bytes: 400_000 };

test("Android resumes from the byte offset of .part, as before", () => {
assert.deepEqual(resumePlan("android", { from: 400_000, partBytes: 400_000, expectedSize: size }), { kind: "range", offset: 400_000 });
// Never past what is on disk.
assert.deepEqual(resumePlan("android", { from: 500_000, partBytes: 400_000, expectedSize: size }), { kind: "range", offset: 400_000 });
assert.deepEqual(resumePlan("android", { from: size, partBytes: size, expectedSize: size }), { kind: "complete" });
assert.deepEqual(resumePlan("android", { from: 400_000, partBytes: 0, expectedSize: size }), { kind: "clean" });
// A stray iOS record never changes the Android path.
assert.deepEqual(resumePlan("android", { from: 400_000, partBytes: 400_000, expectedSize: size, record }), { kind: "range", offset: 400_000 });
});

test("iOS resumes from the saved NSURLSession resume data, never from a byte offset", () => {
assert.deepEqual(resumePlan("ios", { from: 400_000, partBytes: 0, expectedSize: size, record }), { kind: "resume_data", resumeData: blob, offset: 400_000 });
});

test("iOS starts clean when the resume data is missing, or when asked to start over", () => {
assert.deepEqual(resumePlan("ios", { from: 400_000, partBytes: 0, expectedSize: size }), { kind: "clean" });
assert.deepEqual(resumePlan("ios", { from: 0, partBytes: 0, expectedSize: size, record }), { kind: "clean" });
assert.deepEqual(resumePlan("android", { from: 0, partBytes: 400_000, expectedSize: size }), { kind: "clean" });
});

test("iOS goes straight to the check when the whole file already sits in .part", () => {
assert.deepEqual(resumePlan("ios", { from: size, partBytes: size, expectedSize: size }), { kind: "complete" });
// A .part of the wrong length on iOS is not a byte offset to resume from.
assert.deepEqual(resumePlan("ios", { from: 400_000, partBytes: 300_000, expectedSize: size }), { kind: "clean" });
});

test("what is stored next to .part: the URL, the resume data and how far it got", () => {
const text = resumeRecordText(url, blob, 400_000);
assert.ok(text);
assert.deepEqual(JSON.parse(text), { v: 1, url, resumeData: blob, bytes: 400_000 });
assert.deepEqual(readResumeRecord(text, url, size), record);
});

test("nothing is stored when the pause produced no resume data or no bytes", () => {
assert.equal(resumeRecordText(url, undefined, 400_000), undefined);
assert.equal(resumeRecordText(url, "", 400_000), undefined);
assert.equal(resumeRecordText(url, blob, 0), undefined);
});

test("a stale or broken record is ignored, so the download starts clean", () => {
const good = resumeRecordText(url, blob, 400_000)!;
assert.equal(readResumeRecord(undefined, url, size), undefined);
assert.equal(readResumeRecord("not json", url, size), undefined);
assert.equal(readResumeRecord(good, "https://example.com/models/other.gguf", size), undefined, "another file's record");
assert.equal(readResumeRecord(resumeRecordText(url, blob, size + 1)!, url, size), undefined, "more bytes than the model has");
assert.equal(readResumeRecord(resumeRecordText(url, "40000", 400_000)!, url, size), undefined, "Android's offset is not iOS resume data");
assert.equal(readResumeRecord(JSON.stringify({ v: 2, url, resumeData: blob, bytes: 400_000 }), url, size), undefined, "unknown version");
assert.equal(readResumeRecord(JSON.stringify({ v: 1, url, resumeData: blob, bytes: "400000" }), url, size), undefined);
});

test("the bytes reported as kept: .part on Android, the saved record on iOS", () => {
assert.equal(resumableBytes("android", 400_000, record), 400_000);
assert.equal(resumableBytes("android", 0, record), 0);
assert.equal(resumableBytes("ios", 0, record), 400_000);
assert.equal(resumableBytes("ios", 0, undefined), 0);
assert.equal(resumableBytes("ios", size, record), size, "a finished file waiting for its check");
});

test("only iOS pauses the download to keep its resume data, when the app leaves or the connection drops", () => {
assert.equal(pausesFor("ios", { appState: "background" }), true);
assert.equal(pausesFor("ios", { appState: "inactive" }), false, "Control Center or a notification is not leaving");
assert.equal(pausesFor("ios", { appState: "active" }), false);
assert.equal(pausesFor("ios", { connected: false }), true);
assert.equal(pausesFor("ios", { connected: true }), false);
assert.equal(pausesFor("android", { appState: "background" }), false);
assert.equal(pausesFor("android", { connected: false }), false);
});
Loading
Loading