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
2 changes: 1 addition & 1 deletion apps/mobile/src/adapters/device-lab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export async function shareReport(text: string, subject: string): Promise<void>
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<void> {
return Linking.openURL(url);
}
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
24 changes: 5 additions & 19 deletions apps/mobile/src/app/device-lab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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();
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -251,7 +237,7 @@ function Report({ report, onAgain }: { report: DeviceReport; onAgain(): void })
<Btn label={t("HM-SET-10.copy")} kind="secondary" icon="copy" style={{ flexGrow: 1 }} onPress={() => void copy()} />
<Btn label={t("HM-SET-10.share")} kind="secondary" icon="send" style={{ flexGrow: 1 }} onPress={() => void share()} />
</View>
{notice ? <Notice text={notice} tone={shared === "copied" ? "ok" : shared === "longCopied" ? "info" : "bad"} /> : null}
{notice ? <Notice text={notice} tone={shared === "copied" ? "ok" : shared === "fileCopied" || shared === "longCopied" ? "info" : "bad"} /> : null}
</View>

<View style={{ marginTop: s.xl }}>
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
71 changes: 70 additions & 1 deletion apps/mobile/src/device-lab-view.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down Expand Up @@ -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));
Expand Down
Loading
Loading