From c8485fc5c5fcbec39ff9c477066843af6f8a0387 Mon Sep 17 00:00:00 2001 From: Daniel Bejarano <58019353+dbejarano820@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:27:55 -0600 Subject: [PATCH] iOS: a stopped model download resumes from NSURLSession's resume data (#127) On iOS, expo-file-system resumes only from the base64 resume data NSURLSession produces on a pause, and .part does not exist until the file is complete, so every stopped download started again from zero. - download-resume.ts (pure, tested): which path each platform takes, the record kept next to .part, and when to fall back to a clean restart. - The download screen pauses the running download on iOS when the app goes to the background or the connection drops; the pause saves the resume data in .part.resume, and the next attempt resumes from it. A missing, stale or rejected record means one clean restart. - partialModel and the model update read the saved bytes on iOS. - Android keeps its byte offset path. The SHA-256 check is unchanged. Signed-off-by: Daniel Bejarano --- apps/mobile/src/adapters/device.ts | 109 +++++++++++++++++++---- apps/mobile/src/adapters/index.ts | 4 +- apps/mobile/src/adapters/model-update.ts | 15 ++-- apps/mobile/src/app/download.tsx | 6 +- apps/mobile/src/download-resume.test.ts | 79 ++++++++++++++++ apps/mobile/src/download-resume.ts | 83 +++++++++++++++++ 6 files changed, 272 insertions(+), 24 deletions(-) create mode 100644 apps/mobile/src/download-resume.test.ts create mode 100644 apps/mobile/src/download-resume.ts diff --git a/apps/mobile/src/adapters/device.ts b/apps/mobile/src/adapters/device.ts index 5be9f62..da7960b 100644 --- a/apps/mobile/src/adapters/device.ts +++ b/apps/mobile/src/adapters/device.ts @@ -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"; @@ -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 { try { @@ -52,7 +74,7 @@ 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`); @@ -60,7 +82,26 @@ export function partialBytes(name: string): number { 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 `.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 `` 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)); } /** @@ -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 `.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), diff --git a/apps/mobile/src/adapters/index.ts b/apps/mobile/src/adapters/index.ts index 603f658..be56af8 100644 --- a/apps/mobile/src/adapters/index.ts +++ b/apps/mobile/src/adapters/index.ts @@ -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 { diff --git a/apps/mobile/src/adapters/model-update.ts b/apps/mobile/src/adapters/model-update.ts index 4782b9d..f607a87 100644 --- a/apps/mobile/src/adapters/model-update.ts +++ b/apps/mobile/src/adapters/model-update.ts @@ -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"; @@ -118,7 +118,7 @@ async function apply(e: UpdateEffect): Promise { 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": { @@ -153,7 +153,7 @@ async function apply(e: UpdateEffect): Promise { 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(); } @@ -214,8 +214,13 @@ export function recoverModelUpdate(): Promise { state = journal; return exclusive(async () => { const pointer = readJson(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 })); }); } diff --git a/apps/mobile/src/app/download.tsx b/apps/mobile/src/app/download.tsx index 115d705..1401387 100644 --- a/apps/mobile/src/app/download.tsx +++ b/apps/mobile/src/app/download.tsx @@ -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"; @@ -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": diff --git a/apps/mobile/src/download-resume.test.ts b/apps/mobile/src/download-resume.test.ts new file mode 100644 index 0000000..5209d73 --- /dev/null +++ b/apps/mobile/src/download-resume.test.ts @@ -0,0 +1,79 @@ +/// +// 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("made-up resume data").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); +}); diff --git a/apps/mobile/src/download-resume.ts b/apps/mobile/src/download-resume.ts new file mode 100644 index 0000000..8c0ba75 --- /dev/null +++ b/apps/mobile/src/download-resume.ts @@ -0,0 +1,83 @@ +// How a stopped model download resumes on each platform (issue #127). Pure: tested under Node with node --test +// (download-resume.test.ts); the adapter in adapters/device.ts does the file and network work. +// +// Android (expo-file-system) resumes from a byte offset: the native task truncates `.part` to it and appends with an +// HTTP Range request. iOS never writes `.part` until the file is complete; NSURLSession keeps the bytes itself and +// resumes only from the opaque base64 blob it produced when the task was paused, so that blob is what is kept, in a +// small record next to `.part`. A missing, stale or rejected record means a clean restart. The SHA-256 check on the +// finished file runs the same on both paths. + +const isIos = (os: string) => os === "ios"; + +/** What is saved next to `.part` on iOS when a download pauses. */ +export interface ResumeRecord { + url: string; + /** NSURLSession's resume data, base64, as expo-file-system returns it from a pause. */ + resumeData: string; + /** How many bytes had arrived when it paused, for the progress bar and the state machine. */ + bytes: number; +} + +export type ResumePlan = + | { kind: "clean" } + | { kind: "complete" } + | { kind: "range"; offset: number } + | { kind: "resume_data"; resumeData: string; offset: number }; + +const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/; +const isBase64 = (s: string) => s.length % 4 === 0 && BASE64.test(s); +const isBytes = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n > 0; + +/** The record's text, or undefined when the pause left nothing to resume from (no resume data, or no bytes yet). */ +export function resumeRecordText(url: string, resumeData: string | null | undefined, bytes: number): string | undefined { + if (!resumeData || !isBytes(bytes)) return undefined; + return JSON.stringify({ v: 1, url, resumeData, bytes }); +} + +/** The saved record, only when it is for this URL, well formed and no longer than the model; else undefined. */ +export function readResumeRecord(text: string | undefined, url: string, size?: number): ResumeRecord | undefined { + if (!text) return undefined; + let r: unknown; + try { + r = JSON.parse(text); + } catch { + return undefined; + } + if (typeof r !== "object" || r === null) return undefined; + const o = r as Record; + if (o.v !== 1 || o.url !== url || typeof o.resumeData !== "string" || !isBase64(o.resumeData) || !isBytes(o.bytes)) return undefined; + if (size !== undefined && o.bytes > size) return undefined; + return { url, resumeData: o.resumeData, bytes: o.bytes }; +} + +/** + * Which path a download attempt takes. `from` is the state machine's `downloading.from` (0 means start clean), + * `partBytes` the length of `.part` on disk, `record` the saved iOS resume data, already read and checked. + */ +export function resumePlan(os: string, x: { from: number; partBytes: number; expectedSize?: number; record?: ResumeRecord }): ResumePlan { + if (x.from <= 0) return { kind: "clean" }; + if (isIos(os)) { + // A finished file waiting for its check (the app stopped before hashing): straight to the check, which still runs. + if (x.partBytes > 0 && x.partBytes === x.expectedSize) return { kind: "complete" }; + return x.record ? { kind: "resume_data", resumeData: x.record.resumeData, offset: x.record.bytes } : { kind: "clean" }; + } + const offset = Math.min(x.from, x.partBytes); + if (offset <= 0) return { kind: "clean" }; + return offset === x.expectedSize ? { kind: "complete" } : { kind: "range", offset }; +} + +/** The bytes a download can resume from: `.part` on disk, or on iOS before it exists, the saved record. */ +export function resumableBytes(os: string, partBytes: number, record: ResumeRecord | undefined): number { + if (partBytes > 0) return partBytes; + return isIos(os) && record ? record.bytes : 0; +} + +/** + * Whether to pause the running download now so its resume data is kept. Only iOS: expo-file-system hands back the + * resume data from a pause, never from a failure, and an app closed while in the background loses it. Android keeps + * `.part` on disk and needs nothing. + */ +export function pausesFor(os: string, signal: { appState?: string; connected?: boolean }): boolean { + if (!isIos(os)) return false; + return signal.appState === "background" || signal.connected === false; +}