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
1 change: 1 addition & 0 deletions apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@
}
}
],
"./plugins/with-ios-purpose-strings",
"expo-secure-store",
[
"expo-local-authentication",
Expand Down
32 changes: 32 additions & 0 deletions apps/mobile/plugins/ios-purpose-strings-core.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Issue 128: the iOS permission prompts (Info.plist purpose strings), read from packages/copy so they have one source,
// in both locales. Pure: tested by ios-purpose-strings.test.mjs.
"use strict";

const fs = require("node:fs");

/** Each purpose key the Face ID and calendar plugins write, and the copy key that says it. */
const PURPOSE_KEYS = {
NSFaceIDUsageDescription: "common.ios.faceIdUsage",
NSCalendarsUsageDescription: "common.ios.calendarsUsage",
NSCalendarsFullAccessUsageDescription: "common.ios.calendarsUsage",
NSRemindersUsageDescription: "common.ios.remindersUsage",
NSRemindersFullAccessUsageDescription: "common.ios.remindersUsage",
};

/** The purpose strings for one locale's dictionary. A missing key fails the prebuild instead of shipping Expo's default. */
function purposeStrings(dict) {
const out = {};
for (const [plistKey, copyKey] of Object.entries(PURPOSE_KEYS)) {
const text = dict[copyKey];
if (typeof text !== "string" || !text) throw new Error(`Hermit: packages/copy has no ${copyKey} for ${plistKey}.`);
out[plistKey] = text;
}
return out;
}

/** packages/copy's locales, as JSON. */
function readCopy(locale) {
return JSON.parse(fs.readFileSync(require.resolve(`@hermit/copy/locales/${locale}.json`), "utf8"));
}

module.exports = { PURPOSE_KEYS, purposeStrings, readCopy };
55 changes: 55 additions & 0 deletions apps/mobile/plugins/ios-purpose-strings.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Issue 128: the iOS permission prompts come from packages/copy, in English and Spanish, and replace every default the
// Expo plugins would write. Run through Expo's own Info.plist mods, with no prebuild.
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import { createRequire } from "node:module";

const require = createRequire(import.meta.url);
const withIosPurposeStrings = require("./with-ios-purpose-strings.js");
const { PURPOSE_KEYS, purposeStrings } = require("./ios-purpose-strings-core.js");
const plugin = (name) => require(name).default;
const withSecureStore = plugin("expo-secure-store/app.plugin.js");
const withCalendar = plugin("expo-calendar/app.plugin.js");
const withLocalAuthentication = plugin("expo-local-authentication/app.plugin.js");

const en = JSON.parse(fs.readFileSync(new URL("../../../packages/copy/locales/en.json", import.meta.url), "utf8"));
const es = JSON.parse(fs.readFileSync(new URL("../../../packages/copy/locales/es-419.json", import.meta.url), "utf8"));
const app = JSON.parse(fs.readFileSync(new URL("../app.json", import.meta.url), "utf8")).expo;

const EXPO_DEFAULT = /Allow \$\(PRODUCT_NAME\)/;

test("every Info.plist purpose key the calendar and Face ID plugins write has copy in both locales", () => {
for (const plistKey of ["NSFaceIDUsageDescription", "NSCalendarsUsageDescription", "NSCalendarsFullAccessUsageDescription", "NSRemindersUsageDescription", "NSRemindersFullAccessUsageDescription"]) {
const copyKey = PURPOSE_KEYS[plistKey];
assert.ok(copyKey, plistKey);
assert.ok(en[copyKey], `${copyKey} in en`);
assert.ok(es[copyKey], `${copyKey} in es-419`);
}
assert.deepEqual(Object.keys(purposeStrings(en)).sort(), Object.keys(purposeStrings(es)).sort());
assert.throws(() => purposeStrings({}), /common\.ios\./);
});

test("the plugin writes the English prompts to Info.plist and both languages to InfoPlist.strings", async () => {
// The order app.json uses: ours, then the plugins whose defaults it replaces.
let config = { name: "Hermit", slug: "hermit", ios: {} };
config = withIosPurposeStrings(config);
config = withSecureStore(config);
config = withLocalAuthentication(config, { faceIDPermission: false });
config = withCalendar(config);
const result = await config.mods.ios.infoPlist({ ...config, modResults: { ...config.ios.infoPlist }, modRequest: { platform: "ios", modName: "infoPlist", projectRoot: "/app", platformProjectRoot: "/app/ios", introspect: true } });
const plist = result.modResults;
for (const [plistKey, copyKey] of Object.entries(PURPOSE_KEYS)) {
assert.equal(plist[plistKey], en[copyKey], plistKey);
assert.doesNotMatch(plist[plistKey], EXPO_DEFAULT, plistKey);
assert.equal(config.locales.en[plistKey], en[copyKey]);
assert.equal(config.locales.es[plistKey], es[copyKey]);
}
});

test("app.json lists the plugin before the plugins whose defaults it replaces", () => {
const names = app.plugins.map((p) => (Array.isArray(p) ? p[0] : p));
const ours = names.indexOf("./plugins/with-ios-purpose-strings");
assert.ok(ours >= 0, "listed");
for (const other of ["expo-secure-store", "expo-local-authentication", "expo-calendar"]) assert.ok(ours < names.indexOf(other), other);
});
22 changes: 22 additions & 0 deletions apps/mobile/plugins/with-ios-purpose-strings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Issue 128: Expo config plugin that writes the iOS permission prompts from packages/copy. Info.plist gets the English
// text, in place of the defaults expo-secure-store and expo-calendar would write, and `locales` gets English and Spanish,
// so prebuild writes en.lproj and es.lproj InfoPlist.strings. iOS uses es.lproj for any Spanish, as resolveLocale does.
//
// app.json: "./plugins/with-ios-purpose-strings", listed before expo-secure-store, expo-local-authentication and
// expo-calendar. Mods run last-listed first, so this one runs after theirs and its text is what stays.
"use strict";

const { withInfoPlist } = require("expo/config-plugins");
const { purposeStrings, readCopy } = require("./ios-purpose-strings-core.js");

function withIosPurposeStrings(config) {
const en = purposeStrings(readCopy("en"));
const es = purposeStrings(readCopy("es-419"));
config.locales = { ...config.locales, en: { ...config.locales?.en, ...en }, es: { ...config.locales?.es, ...es } };
return withInfoPlist(config, (c) => {
Object.assign(c.modResults, en);
return c;
});
}

module.exports = withIosPurposeStrings;
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
9 changes: 9 additions & 0 deletions apps/mobile/src/adapters/fingerprint.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import * as LocalAuthentication from "expo-local-authentication";
import { Platform } from "react-native";
import { biometricKind } from "../biometric-name";
import { setBiometricKind } from "../i18n";

export type FingerprintCheck = "confirmed" | "not_confirmed" | "unavailable";

Expand All @@ -17,3 +20,9 @@ export async function confirmWithFingerprint(prompt: string, cancelLabel: string
});
return auth.success ? "confirmed" : "not_confirmed";
}

/** Issue 128: the copy names this phone's biometric: Face ID or Touch ID on an iPhone, fingerprint on Android. */
export async function applyBiometricName(): Promise<void> {
const supported = Platform.OS === "ios" ? await LocalAuthentication.supportedAuthenticationTypesAsync().catch(() => undefined) : undefined;
setBiometricKind(biometricKind(Platform.OS, supported));
}
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
Loading
Loading