diff --git a/apps/mobile/src/adapters/device-lab.ts b/apps/mobile/src/adapters/device-lab.ts index af1d179..cd69cfc 100644 --- a/apps/mobile/src/adapters/device-lab.ts +++ b/apps/mobile/src/adapters/device-lab.ts @@ -128,7 +128,7 @@ export async function shareReport(text: string, subject: string): Promise await Share.share({ message: text, title: subject }); } -/** Opens the GitHub form in the browser. Nothing is filed until the person submits it there. */ +/** Opens the GitHub form with the system's default handler: the GitHub app when installed, else the browser. Nothing is filed until the person submits it there. */ export function openReportForm(url: string): Promise { return Linking.openURL(url); } 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/device-lab.tsx b/apps/mobile/src/app/device-lab.tsx index e856b7b..3bed51e 100644 --- a/apps/mobile/src/app/device-lab.tsx +++ b/apps/mobile/src/app/device-lab.tsx @@ -13,7 +13,7 @@ import { modelReady, releaseModel } from "../adapters"; import { appVersion, batterySaverOn, copyReport, keepScreenOn, labPorts, labSetup, openReportForm, shareReport } from "../adapters/device-lab"; import { inTurn } from "../adapters/model-update"; import { Btn, Card, Failed, Field, Label, Meter, Note, Notice, Page, T } from "../components/kit"; -import { clockText, issueLink, REPORT_FORM_ADDRESS, reportGroups, reportText } from "../device-lab-view"; +import { clockText, fileReport, REPORT_FORM_ADDRESS, type FileNotice, reportGroups, reportText } from "../device-lab-view"; import { currentLocale, t } from "../i18n"; import { s } from "../theme"; import { usePalette } from "../use-palette"; @@ -27,7 +27,7 @@ type State = | { kind: "failed"; reason: Failure } | { kind: "done"; report: DeviceReport }; -type Shared = "copied" | "copyFailed" | "longCopied" | "openFailed"; +type Shared = "copied" | FileNotice; export default function DeviceLab() { usePalette(); @@ -190,22 +190,8 @@ function Report({ report, onAgain }: { report: DeviceReport; onAgain(): void }) } }; const file = async () => { - const link = issueLink(report); - if (!link.prefilled) { - try { - await copyReport(text); - setShared("longCopied"); - } catch { - return setShared("copyFailed"); - } - } else { - setShared(undefined); - } - try { - await openReportForm(link.url); - } catch { - setShared("openFailed"); - } + setShared(undefined); + setShared(await fileReport(report, { copy: copyReport, open: openReportForm })); }; const share = async () => { try { @@ -251,7 +237,7 @@ function Report({ report, onAgain }: { report: DeviceReport; onAgain(): void }) void copy()} /> void share()} /> - {notice ? : null} + {notice ? : null} 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/device-lab-view.test.ts b/apps/mobile/src/device-lab-view.test.ts index 8b1d2e5..920645b 100644 --- a/apps/mobile/src/device-lab-view.test.ts +++ b/apps/mobile/src/device-lab-view.test.ts @@ -4,7 +4,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { createTranslator, type Dictionary } from "@hermit/copy"; -import { clockText, issueLink, MAX_FORM_URL, REPORT_FORM_URL, reportGroups, reportText } from "./device-lab-view.ts"; +import { clockText, fileReport, issueLink, MAX_FORM_URL, REPORT_FORM_URL, reportGroups, reportText } from "./device-lab-view.ts"; const locale = (name: string) => JSON.parse(readFileSync(new URL(`../../../packages/copy/locales/${name}.json`, import.meta.url), "utf8")) as Dictionary; const fixture = (name: string) => JSON.parse(readFileSync(new URL(`../../../scripts/devices/fixtures/${name}`, import.meta.url), "utf8")); @@ -91,6 +91,75 @@ test("a report too long for a link opens the empty form instead", () => { assert.equal(new URL(link.url).searchParams.get("template"), "device_report.yml"); }); +/** A made-up phone for File it on GitHub: what it copied and opened, in order, and which of the two fail. */ +const phoneFor = (fail: { copy?: boolean; open?: boolean } = {}) => { + const calls: string[][] = []; + return { + calls, + io: { + copy: async (text: string) => { + calls.push(["copy", text]); + if (fail.copy) throw new Error("no clipboard"); + }, + open: async (url: string) => { + calls.push(["open", url]); + if (fail.open) throw new Error("no handler"); + }, + }, + }; +}; + +const tooLong = () => { + const long = JSON.parse(JSON.stringify(report)); + long.device.model = "M".repeat(40); + long.speed.sweep = Array.from({ length: 200 }, (_, i) => ({ threads: i + 1, tokensPerSecond: 1, loadMs: 1 })); + return long; +}; + +test("File it on GitHub copies the exact report first, then opens the filled-in form, on every phone", async () => { + for (const r of [report, iphone]) { + const phone = phoneFor(); + const notice = await fileReport(r, phone.io); + assert.deepEqual(phone.calls, [["copy", reportText(r)], ["open", issueLink(r).url]]); + assert.equal(issueLink(r).prefilled, true); + assert.equal(notice, "fileCopied"); + } +}); + +test("a report too long for a link is copied the same way, and the empty form opens", async () => { + const long = tooLong(); + const phone = phoneFor(); + assert.equal(await fileReport(long, phone.io), "longCopied"); + assert.deepEqual(phone.calls, [["copy", reportText(long)], ["open", issueLink(long).url]]); + assert.equal(new URL(phone.calls[1]![1]!).searchParams.get("report"), null); +}); + +test("when the copy fails, a filled-in form still opens, but an empty one doesn't", async () => { + const filled = phoneFor({ copy: true }); + assert.equal(await fileReport(report, filled.io), undefined); + assert.deepEqual(filled.calls.map((c) => c[0]), ["copy", "open"]); + const empty = phoneFor({ copy: true }); + assert.equal(await fileReport(tooLong(), empty.io), "copyFailed"); + assert.deepEqual(empty.calls.map((c) => c[0]), ["copy"]); +}); + +test("when nothing can open the link, the screen says so", async () => { + assert.equal(await fileReport(report, phoneFor({ open: true }).io), "openFailed"); + assert.equal(await fileReport(tooLong(), phoneFor({ open: true }).io), "openFailed"); +}); + +test("what File it on GitHub says: the report is copied, paste it into Report if the form opens empty, or pick Device report", () => { + for (const name of ["en", "es-419"]) { + const d = locale(name); + for (const key of ["HM-SET-10.fileCopied", "HM-SET-10.longCopied"]) { + assert.ok(d[key], `${name}: ${key} is missing`); + assert.ok(d[key]!.includes("Report") && d[key]!.includes("Device report"), `${name}: ${key}`); + assert.ok(!/[\u2013\u2014]/.test(d[key]!), `${name}: ${key} has a dash`); + } + assert.ok(!/Android/.test(d["HM-SET-10.fileCopied"]!), `${name}: fileCopied says Android`); + } +}); + test("the exact text is the report's JSON, and nothing else", () => { assert.deepEqual(JSON.parse(reportText(report)), report); assert.equal(reportText(report), JSON.stringify(report, null, 2)); diff --git a/apps/mobile/src/device-lab-view.ts b/apps/mobile/src/device-lab-view.ts index 74054c3..f2af53c 100644 --- a/apps/mobile/src/device-lab-view.ts +++ b/apps/mobile/src/device-lab-view.ts @@ -36,6 +36,32 @@ export function issueLink(r: DeviceReport): { url: string; prefilled: boolean } return { url: base, prefilled: false }; } +/** What the screen says after File it on GitHub. */ +export type FileNotice = "fileCopied" | "longCopied" | "copyFailed" | "openFailed"; + +/** + * File it on GitHub: the exact report goes to the clipboard first, every time, then the system opens the link with + * whatever handles github.com (the GitHub app when installed, else the browser). The app may drop the link's query, so + * the copy is what lets the report reach the form either way. When the copy fails, a filled-in form still opens; an + * empty one doesn't, since the person would have nothing to paste. + */ +export async function fileReport(r: DeviceReport, io: { copy(text: string): Promise; open(url: string): Promise }): Promise { + const link = issueLink(r); + let copied = true; + try { + await io.copy(reportText(r)); + } catch { + copied = false; + if (!link.prefilled) return "copyFailed"; + } + try { + await io.open(link.url); + } catch { + return "openFailed"; + } + return !copied ? undefined : link.prefilled ? "fileCopied" : "longCopied"; +} + /** Minutes and seconds, for the time so far ("1:05"). */ export function clockText(ms: number): string { const total = Math.max(0, Math.floor(ms / 1000)); 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; +} diff --git a/packages/copy/locales/en.json b/packages/copy/locales/en.json index c81b0a2..155fa13 100644 --- a/packages/copy/locales/en.json +++ b/packages/copy/locales/en.json @@ -2229,13 +2229,14 @@ "HM-SET-10.hideExact": "Hide the exact text", "HM-SET-10.exactNote": "This is exactly the text that Copy, Share and File it on GitHub use.", "HM-SET-10.shareTitle": "Share it, if you like", - "HM-SET-10.shareBody": "Reports from many phones help tune Hermit's speed and accuracy for each one. File it on GitHub opens the Hermit project's report form in your browser with the report filled in. Nothing is filed until you press Submit there, and you need a GitHub account.", + "HM-SET-10.shareBody": "Reports from many phones help tune Hermit's speed and accuracy for each one. File it on GitHub copies the report, then opens the Hermit project's report form in the GitHub app or your browser, with the report filled in. Nothing is filed until you press Submit there, and you need a GitHub account.", "HM-SET-10.file": "File it on GitHub", "HM-SET-10.copy": "Copy", "HM-SET-10.share": "Share", "HM-SET-10.copied": "Copied.", "HM-SET-10.copyFailed": "Couldn't copy it. Try again.", - "HM-SET-10.longCopied": "The report is too long for a link, so it's copied: paste it into the form's Report field.", - "HM-SET-10.openFailed": "Couldn't open the browser. Copy the report and file it at {address}.", + "HM-SET-10.fileCopied": "The report is copied too. If the form opens empty, paste it into the Report field. If the GitHub app shows a list of forms, pick Device report.", + "HM-SET-10.longCopied": "The report is too long for a link, so it's copied. Paste it into the form's Report field. If the GitHub app shows a list of forms, pick Device report.", + "HM-SET-10.openFailed": "Couldn't open GitHub. Copy the report and file it at {address}.", "HM-SET-10.shareSubject": "Hermit device report" } diff --git a/packages/copy/locales/es-419.json b/packages/copy/locales/es-419.json index a96fe1e..c8d6fcc 100644 --- a/packages/copy/locales/es-419.json +++ b/packages/copy/locales/es-419.json @@ -2229,13 +2229,14 @@ "HM-SET-10.hideExact": "Ocultar el texto exacto", "HM-SET-10.exactNote": "Este es exactamente el texto que usan Copiar, Compartir y Enviarlo a GitHub.", "HM-SET-10.shareTitle": "Compártelo, si quieres", - "HM-SET-10.shareBody": "Los informes de muchos teléfonos ayudan a ajustar la velocidad y la precisión de Hermit para cada uno. Enviarlo a GitHub abre en tu navegador el formulario de informes del proyecto Hermit, con el informe ya puesto. No se publica nada hasta que presiones Submit ahí, y necesitas una cuenta de GitHub.", + "HM-SET-10.shareBody": "Los informes de muchos teléfonos ayudan a ajustar la velocidad y la precisión de Hermit para cada uno. Enviarlo a GitHub copia el informe y luego abre el formulario de informes del proyecto Hermit en la app de GitHub o en tu navegador, con el informe ya puesto. No se publica nada hasta que presiones Submit ahí, y necesitas una cuenta de GitHub.", "HM-SET-10.file": "Enviarlo a GitHub", "HM-SET-10.copy": "Copiar", "HM-SET-10.share": "Compartir", "HM-SET-10.copied": "Copiado.", "HM-SET-10.copyFailed": "No se pudo copiar. Inténtalo de nuevo.", - "HM-SET-10.longCopied": "El informe es demasiado largo para un enlace, así que se copió: pégalo en el campo Report del formulario.", - "HM-SET-10.openFailed": "No se pudo abrir el navegador. Copia el informe y envíalo en {address}.", + "HM-SET-10.fileCopied": "El informe también se copió. Si el formulario se abre vacío, pégalo en el campo Report. Si la app de GitHub muestra una lista de formularios, elige Device report.", + "HM-SET-10.longCopied": "El informe es demasiado largo para un enlace, así que se copió. Pégalo en el campo Report del formulario. Si la app de GitHub muestra una lista de formularios, elige Device report.", + "HM-SET-10.openFailed": "No se pudo abrir GitHub. Copia el informe y envíalo en {address}.", "HM-SET-10.shareSubject": "Informe de dispositivo de Hermit" }