diff --git a/src-tauri/src/extensions/firmware.rs b/src-tauri/src/extensions/firmware.rs index 573ced6..5d72f4c 100644 --- a/src-tauri/src/extensions/firmware.rs +++ b/src-tauri/src/extensions/firmware.rs @@ -53,7 +53,10 @@ pub(super) fn identify(payload: &[u8], model: String) -> Option { eject_reboot: locate(payload, super::eject::FIRMWARE_PATH).is_some(), repriseos: version.into(), revision: revision.map(str::to_owned), - api: capabilities.map(|(api, _)| format!("{}.{}", api >> 16, api & 0xffff)), + api: capabilities.map(|(api, _)| super::api_text(api)), firmware_id: capabilities.map(|(_, id)| format!("{id:08x}")), + sdk_floor: capabilities + .and_then(|(api, _)| super::sdk_floor(api)) + .map(super::api_text), }) } diff --git a/src-tauri/src/extensions/mod.rs b/src-tauri/src/extensions/mod.rs index 03c8442..0552689 100644 --- a/src-tauri/src/extensions/mod.rs +++ b/src-tauri/src/extensions/mod.rs @@ -15,6 +15,25 @@ fn word(data: &[u8], i: usize) -> Option { Some(u32::from_le_bytes(data.get(i..i + 4)?.try_into().ok()?)) } +/// The catalog's "major.minor" form of an RVX API word. +fn api_text(api: u32) -> String { + format!("{}.{}", api >> 16, api & 0xffff) +} + +/// The APIs at which the core's package layout changed: rv_row and +/// rv_menu_entry grew in 1.86 and rv_pane in 1.89, and rv_pane_extra changed in +/// 1.92. A core loads packages an SDK at or above the last entry at or below +/// its own API packed. +const LAYOUT_APIS: [u32; 3] = [0x10056, 0x10059, 0x1005c]; + +/// The lowest header SDK a core at `api` loads, when it refuses older ones. +fn sdk_floor(api: u32) -> Option { + LAYOUT_APIS + .into_iter() + .rev() + .find(|&floor| api >= floor && api >> 16 == floor >> 16) +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct DeviceInfo { @@ -24,6 +43,8 @@ pub struct DeviceInfo { revision: Option, api: Option, firmware_id: Option, + /// The lowest SDK the firmware loads packages from, when it refuses older ones. + sdk_floor: Option, } impl DeviceInfo { @@ -40,10 +61,12 @@ impl DeviceInfo { let Some((major, minor)) = api.split_once('.') else { return false; }; - major.parse::() == Ok(pkg.minimum >> 16) - && minor - .parse::() - .is_ok_and(|v| v >= (pkg.minimum & 0xffff)) + let (Ok(major), Ok(minor)) = (major.parse::(), minor.parse::()) else { + return false; + }; + major == pkg.minimum >> 16 + && minor >= (pkg.minimum & 0xffff) + && sdk_floor(major << 16 | minor).is_none_or(|floor| pkg.sdk >= floor) && u32::from_str_radix(target, 16) == Ok(pkg.target) } _ => dev, @@ -61,6 +84,11 @@ pub struct Installed { #[serde(skip)] path: PathBuf, library: bool, + /// The package's minimum API and target firmware, in catalog form. + api: String, + firmware_id: String, + /// The SDK that packed it, in catalog form. + sdk: String, } #[derive(Serialize)] diff --git a/src-tauri/src/extensions/package.rs b/src-tauri/src/extensions/package.rs index a6ce441..27a8b60 100644 --- a/src-tauri/src/extensions/package.rs +++ b/src-tauri/src/extensions/package.rs @@ -8,6 +8,8 @@ pub(super) struct Package { pub minimum: u32, pub library: bool, pub target: u32, + /// The header's SDK API, at or above `minimum`. + pub sdk: u32, } pub(super) fn valid_id(id: &str) -> bool { @@ -85,5 +87,6 @@ pub(super) fn parse(bytes: &[u8]) -> Result { minimum, library: short(46) == 5, target: w(12)?, + sdk: w(8)?, }) } diff --git a/src-tauri/src/extensions/storage.rs b/src-tauri/src/extensions/storage.rs index eda6946..e28385d 100644 --- a/src-tauri/src/extensions/storage.rs +++ b/src-tauri/src/extensions/storage.rs @@ -120,6 +120,9 @@ pub(super) fn inventory(root: &Path) -> Result> { version: pkg.version, requires: pkg.requires, library: pkg.library, + api: super::api_text(pkg.minimum), + firmware_id: format!("{:08x}", pkg.target), + sdk: super::api_text(pkg.sdk), folder: which.into(), path, }); diff --git a/src-tauri/src/extensions/tests.rs b/src-tauri/src/extensions/tests.rs index f3207b9..e681ecf 100644 --- a/src-tauri/src/extensions/tests.rs +++ b/src-tauri/src/extensions/tests.rs @@ -8,14 +8,23 @@ use sha2::{Digest, Sha256}; use std::fs; fn image(version: &str) -> Vec { + core(version, 0x10051) +} + +fn core(version: &str, api: u32) -> Vec { let mut bytes = format!("\0Build: abc12345-dirty\0RepriseOS {version}\0RepriseRVX1\0").into_bytes(); - bytes.extend(0x10051u32.to_le_bytes()); + bytes.extend(api.to_le_bytes()); bytes.extend(0x660eb6ffu32.to_le_bytes()); bytes } fn request(id: &str, version: &str, minor: u32, dependency: Option<&str>) -> WritePackage { + packed(id, version, minor, 0x10060, dependency) +} + +/// A package whose manifest asks for API 1.`minor`, packed by SDK `sdk`. +fn packed(id: &str, version: &str, minor: u32, sdk: u32, dependency: Option<&str>) -> WritePackage { let mut manifest = vec![0; 64]; let mut strings = Vec::new(); for (index, value) in [id, id, "extension", version, "author", "MIT", ""] @@ -47,7 +56,7 @@ fn request(id: &str, version: &str, minor: u32, dependency: Option<&str>) -> Wri let hash = manifest.iter().fold(2166136261u32, |h, b| { (h ^ u32::from(*b)).wrapping_mul(16777619) }); - let mut data: Vec<_> = [0x30585652u32, 1, 0x10060, 0x660eb6ff, len, 1, hash] + let mut data: Vec<_> = [0x30585652u32, 1, sdk, 0x660eb6ff, len, 1, hash] .into_iter() .flat_map(u32::to_le_bytes) .collect(); @@ -81,16 +90,30 @@ fn mounted_install_update_and_remove() { let dir = folder(root, PRIMARY, false).unwrap().unwrap(); fs::rename(dir.join("crossfeed.rvx"), dir.join("custom-name.rvx")).unwrap(); write(&mount, request("crossfeed", "1.1.0", 81, Some("dsp"))).unwrap(); + let installed = inventory(root).unwrap(); + let crossfeed = installed.iter().find(|i| i.id == "crossfeed").unwrap(); + assert_eq!(crossfeed.version, "1.1.0"); assert_eq!( - inventory(root) - .unwrap() - .iter() - .find(|i| i.id == "crossfeed") - .unwrap() - .version, - "1.1.0" + ( + crossfeed.api.as_str(), + crossfeed.firmware_id.as_str(), + crossfeed.sdk.as_str() + ), + ("1.81", "660eb6ff", "1.96") ); assert!(write(&mount, request("crossfeed", "1.2.0", 82, Some("dsp"))).is_err()); + // A copy placed without the installer still reports the API it needs. + fs::write( + dir.join("newer.rvx"), + request("newer", "1.0.0", 84, None).data, + ) + .unwrap(); + let installed = inventory(root).unwrap(); + assert_eq!( + installed.iter().find(|i| i.id == "newer").unwrap().api, + "1.84" + ); + fs::remove_file(dir.join("newer.rvx")).unwrap(); remove(&mount, "crossfeed", PRIMARY).unwrap(); remove(&mount, "dsp", PRIMARY).unwrap(); assert!(inventory(root).unwrap().is_empty()); @@ -116,6 +139,50 @@ fn unknown_development_can_install_and_old_release_cannot() { .allows(&ext)); } +#[test] +fn layout_floor_refuses_packages_from_older_sdks() { + let old = parse(&packed("sample", "1.0.0", 82, 0x10058, None).data).unwrap(); + let rebuilt = parse(&packed("sample", "1.0.1", 82, 0x10059, None).data).unwrap(); + let before = firmware::identify(&core("0.4.0", 0x10052), "iPod".into()).unwrap(); + assert_eq!(before.sdk_floor, None); + assert!(before.allows(&old) && before.allows(&rebuilt)); + let pre_rows = parse(&packed("sample", "0.9.0", 82, 0x10055, None).data).unwrap(); + for api in [0x10056, 0x10058] { + let device = firmware::identify(&core("0.5.0", api), "iPod".into()).unwrap(); + assert_eq!(device.sdk_floor.as_deref(), Some("1.86")); + assert!(!device.allows(&pre_rows)); + assert!(device.allows(&old) && device.allows(&rebuilt)); + } + for (version, api) in [ + ("0.5.0", 0x10059), + ("0.5.0", 0x1005b), + ("Development", 0x10059), + ] { + let device = firmware::identify(&core(version, api), "iPod".into()).unwrap(); + assert_eq!(device.sdk_floor.as_deref(), Some("1.89")); + assert!(!device.allows(&old)); + assert!(device.allows(&rebuilt)); + } + let current = parse(&packed("sample", "1.0.2", 82, 0x1005c, None).data).unwrap(); + for api in [0x1005c, 0x1005d] { + let device = firmware::identify(&core("0.5.0", api), "iPod".into()).unwrap(); + assert_eq!(device.sdk_floor.as_deref(), Some("1.92")); + assert!(!device.allows(&old) && !device.allows(&rebuilt)); + assert!(device.allows(¤t)); + } + let next_major = firmware::identify(&core("0.5.0", 0x20000), "iPod".into()).unwrap(); + assert_eq!(next_major.sdk_floor, None); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::create_dir_all(root.join("iPod_Control/Device")).unwrap(); + fs::write(root.join("osos-cfw.bin"), core("0.5.0", 0x10059)).unwrap(); + fs::write(root.join("cfw-loader.bin"), vec![0; 0x25220]).unwrap(); + let mount = inspect(root).unwrap().unwrap(); + assert!(write(&mount, packed("sample", "1.0.0", 82, 0x10058, None)).is_err()); + write(&mount, packed("sample", "1.0.1", 82, 0x10059, None)).unwrap(); + assert_eq!(inventory(root).unwrap()[0].sdk, "1.89"); +} + #[test] #[ignore = "requires a mounted RepriseOS iPod; reads only"] fn read_connected_ipod() { diff --git a/src/components/extensions/ExtensionDetails.tsx b/src/components/extensions/ExtensionDetails.tsx index b47ec6b..c149afc 100644 --- a/src/components/extensions/ExtensionDetails.tsx +++ b/src/components/extensions/ExtensionDetails.tsx @@ -36,6 +36,18 @@ const ExtensionDetails: React.FC = ({ state, entry, onOp const busy = operationRunning(state); const deviceReady = state.device.status === "ready"; const compatible = !status.compatibility || status.compatibility.compatible; + const copy = status.installedCompatibility; + let note = formatSize(entry.package.size); + if (copy && !copy.compatible) { + note = copy.reason; + } else if (status.updateAvailable && status.compatibility && !status.compatibility.compatible) { + const { reason } = status.compatibility; + note = `Version ${entry.version} ${reason[0].toLowerCase()}${reason.slice(1)}`; + } else if (status.installed) { + note = `Version ${status.installed} installed`; + } else if (status.compatibility && !status.compatibility.compatible) { + note = status.compatibility.reason; + } const requires = entry.requires.map( (id) => state.catalog.entries.find((item) => item.id === id) ?? { id, name: id }, ); @@ -83,7 +95,7 @@ const ExtensionDetails: React.FC = ({ state, entry, onOp Remove )} - {(!status.installed || status.updateAvailable) && ( + {(!status.installed || status.updateAvailable || status.canReplace) && ( void installExtension(entry.id)} @@ -93,15 +105,7 @@ const ExtensionDetails: React.FC = ({ state, entry, onOp )} )} - {indicator ?? ( -

- {status.compatibility && !status.compatibility.compatible - ? status.compatibility.reason - : status.installed - ? `Version ${status.installed} installed` - : formatSize(entry.package.size)} -

- )} + {indicator ??

{note}

} {steps} diff --git a/src/components/extensions/ExtensionRow.tsx b/src/components/extensions/ExtensionRow.tsx index eae5df0..22553ad 100644 --- a/src/components/extensions/ExtensionRow.tsx +++ b/src/components/extensions/ExtensionRow.tsx @@ -6,6 +6,7 @@ import { type ExtensionsState, entryStatus, installExtension, + installedCompatibility, operationRunning, removeExtension, } from "../../lib/extensions"; @@ -32,17 +33,26 @@ const ExtensionRow: React.FC = ({ state, entry, copies, mode const deviceReady = state.device.status === "ready"; const legacy = copies?.some((copy) => copy.folder === "/Revola/Extensions/"); + // An installed copy is judged by its own package, the catalog version only for installing. + const problem = status + ? status.installed + ? status.installedCompatibility + : status.compatibility + : installedCompatibility(id, state); + const compatible = !status?.compatibility || status.compatibility.compatible; + const update = !!status?.updateAvailable && compatible; + const version = status?.installed ?? copies?.[0]?.version ?? entry?.version; const versionText = entry - ? status?.updateAvailable - ? `${status.installed} → ${entry.version}` + ? update + ? `${status?.installed} → ${entry.version}` : (version ?? "") : `${version} · Not in the catalog`; let label: { text: string; tone: "ok" | "update" | "warn" } | null = null; - if (status?.compatibility && !status.compatibility.compatible) { - label = { text: status.compatibility.reason, tone: "warn" }; - } else if (status?.updateAvailable) { + if (problem && !problem.compatible) { + label = { text: problem.reason, tone: "warn" }; + } else if (update) { label = { text: "Update available", tone: "update" }; } else if (status?.installed) { label = { text: "Installed", tone: "ok" }; @@ -52,15 +62,13 @@ const ExtensionRow: React.FC = ({ state, entry, copies, mode label = { text: "Compatible", tone: "ok" }; } - const compatible = !status?.compatibility || status.compatibility.compatible; - const action = - status?.updateAvailable && compatible - ? "update" - : mode === "installed" - ? "remove" - : !status?.installed && compatible - ? "install" - : null; + const action = update + ? "update" + : mode === "installed" + ? "remove" + : (!status?.installed && compatible) || status?.canReplace + ? "install" + : null; return (
  • @@ -97,9 +105,9 @@ const ExtensionRow: React.FC = ({ state, entry, copies, mode )} {indicator ?? - (mode === "browse" && status?.compatibility?.compatible === false ? ( + (mode === "browse" && problem?.compatible === false && !action ? ( - {status.compatibility.summary} + {problem.summary} ) : (
    diff --git a/src/dev/mockBackend.ts b/src/dev/mockBackend.ts index 740453d..354123e 100644 --- a/src/dev/mockBackend.ts +++ b/src/dev/mockBackend.ts @@ -2,7 +2,7 @@ import type { Backend, EventChannel } from "../lib/backend.ts"; import { simulateChecks, type Wait } from "./checks.ts"; import { mockDevice, mockFirmware, mockPackage } from "./fixtures.ts"; import { simulateInstallation, simulateUpdate } from "./progress.ts"; -import type { Scenario } from "./scenarios.ts"; +import type { InstalledCopy, Scenario } from "./scenarios.ts"; function channel(args: Record, name = "onEvent"): EventChannel { const value = args[name] as EventChannel | undefined; @@ -22,6 +22,10 @@ export function createMockBackend( let usbAttempts = 0; // Discovery polls that still miss the iPod while it is put back in DFU. let awayPolls = 0; + const copies = new Map((scenario.extensions?.installed ?? []).map((copy) => [copy.id, copy])); + let ejected = false; + const apiText = (bytes: number[], at: number) => + `${bytes[at + 2] | (bytes[at + 3] << 8)}.${bytes[at] | (bytes[at + 1] << 8)}`; const away = (operation: Promise) => operation.catch((error: unknown) => { awayPolls = 4; @@ -123,6 +127,60 @@ export function createMockBackend( }; case "install_installer_update": return simulateUpdate(scenario, channel(args), wait); + case "read_extension_device": { + // The mount key only changes when the iPod comes or goes, as on the real backend. + const mounted = scenario.extensions && !ejected; + const key = mounted ? "mock" : "none"; + if (args.knownMounts === key) return null; + if (!mounted) return { mounts: key, snapshot: null }; + const { api, sdkFloor = null } = scenario.extensions as NonNullable; + return { + mounts: key, + snapshot: { + token: "mock", + device: { + model: "iPod classic 7G", + repriseos: "0.5.0", + api, + firmwareId: "660eb6ff", + sdkFloor, + ejectReboot: true, + }, + installed: [...copies.values()].map((copy: InstalledCopy) => ({ + folder: "/Reprise/Extensions/", + firmware_id: "660eb6ff", + ...copy, + requires: copy.requires ?? [], + library: copy.library ?? false, + })), + }, + }; + } + case "write_extension": { + // The header's SDK word sits at byte 8, the manifest's minimum API at byte 36. + const { id, version, data } = args.package as { + id: string; + version: string; + data: number[]; + }; + const known = copies.get(id); + copies.set(id, { + id, + name: known?.name ?? id, + version, + api: apiText(data, 36), + sdk: apiText(data, 8), + requires: known?.requires ?? [], + library: known?.library ?? false, + }); + return; + } + case "remove_extension": + copies.delete(String(args.id)); + return; + case "eject_and_reboot": + ejected = true; + return; case "plugin:opener|open_url": case "open_installer_download": return; diff --git a/src/dev/scenarios.ts b/src/dev/scenarios.ts index 6f611cb..9896c99 100644 --- a/src/dev/scenarios.ts +++ b/src/dev/scenarios.ts @@ -24,8 +24,26 @@ export interface Scenario { debugExport?: "native" | "cancel" | "error"; update?: "available" | "manual" | "current" | "check-error" | "download-error" | "installing"; startUpdate?: boolean; + /** A mounted iPod with these extension copies in /Reprise/Extensions/. */ + extensions?: { api: string; sdkFloor?: string; installed: InstalledCopy[] }; } +export interface InstalledCopy { + id: string; + name: string; + version: string; + /** The manifest's minimum API. */ + api: string; + /** The SDK that packed the copy. */ + sdk: string; + requires?: string[]; + library?: boolean; +} + +const nightShift = { id: "night-shift", name: "Night Shift", version: "0.1.2" }; +const dsp = { id: "dsp", name: "DSP", version: "0.1.0", library: true }; +const crossfeed = { id: "crossfeed", name: "Crossfeed", requires: ["dsp"] }; + export const scenarios: Scenario[] = [ { id: "full-setup", @@ -353,6 +371,37 @@ export const scenarios: Scenario[] = [ update: "download-error", startUpdate: true, }, + { + id: "extensions-older-builds", + group: "Extensions", + label: "Older builds on a 1.89 core", + screen: "extensions", + hint: "A core at RVX API 1.89 skips packages from older SDKs. Night Shift and DSP are such copies, and so is every release in the live catalog.", + extensions: { + api: "1.89", + sdkFloor: "1.89", + installed: [ + { ...nightShift, api: "1.84", sdk: "1.84" }, + { ...dsp, api: "1.74", sdk: "1.85" }, + { ...crossfeed, version: "0.1.1", api: "1.84", sdk: "1.89" }, + ], + }, + }, + { + id: "extensions-installed", + group: "Extensions", + label: "Installed copies on a 1.82 core", + screen: "extensions", + hint: "Every build of the major loads. The catalog is live, so installs and updates download real packages.", + extensions: { + api: "1.82", + installed: [ + { ...nightShift, api: "1.81", sdk: "1.81" }, + { ...dsp, api: "1.74", sdk: "1.81" }, + { ...crossfeed, version: "0.1.0", api: "1.81", sdk: "1.81" }, + ], + }, + }, ]; export function findScenario(id: string | null): Scenario { diff --git a/src/lib/catalog.ts b/src/lib/catalog.ts index c27602a..773aaa8 100644 --- a/src/lib/catalog.ts +++ b/src/lib/catalog.ts @@ -53,6 +53,8 @@ export interface DeviceInfo { repriseos: string; api: string | null; firmwareId: string | null; + /** The lowest SDK the firmware loads packages from, when it refuses older ones. */ + sdkFloor?: string | null; revision?: string | null; token?: string; ejectReboot?: boolean; @@ -112,7 +114,10 @@ export type Compatibility = | { compatible: false; summary: string; reason: string }; /** Mirrors the firmware's package checks plus the listing's optional requirements. */ -export function checkCompatibility(entry: CatalogEntry, device: DeviceInfo): Compatibility { +export function checkCompatibility( + entry: Pick & { sdk?: string }, + device: DeviceInfo, +): Compatibility { const development = device.repriseos === "Development"; const release = device.repriseos.split("+")[0]; const releaseCore = release.split("-")[0]; @@ -137,21 +142,31 @@ export function checkCompatibility(entry: CatalogEntry, device: DeviceInfo): Com reason: "Built for different firmware", }; } + const newerRelease = + !development && + !!entry.min_repriseos && + (compareVersions(entry.min_repriseos, releaseCore) > 0 || + (entry.min_repriseos === releaseCore && release.includes("-"))); const [major] = entry.api.split("."); const deviceMajor = device.api?.split(".")[0]; if (device.api && (major !== deviceMajor || compareVersions(entry.api, device.api) > 0)) { return { compatible: false, summary: "Needs newer RepriseOS", - reason: `Needs a newer RepriseOS (API ${entry.api})`, + reason: newerRelease + ? `Needs RepriseOS ${entry.min_repriseos}` + : `Needs a newer RepriseOS (API ${entry.api})`, }; } - if ( - !development && - entry.min_repriseos && - (compareVersions(entry.min_repriseos, releaseCore) > 0 || - (entry.min_repriseos === releaseCore && release.includes("-"))) - ) { + // A catalog entry has no SDK field; the SDK that packed it is at least its api. + if (device.sdkFloor && compareVersions(entry.sdk ?? entry.api, device.sdkFloor) < 0) { + return { + compatible: false, + summary: "Older build", + reason: "Built for an older RepriseOS", + }; + } + if (newerRelease) { return { compatible: false, summary: "Needs newer RepriseOS", diff --git a/src/lib/extensionDevice.ts b/src/lib/extensionDevice.ts index 49c7dbc..5deaa6f 100644 --- a/src/lib/extensionDevice.ts +++ b/src/lib/extensionDevice.ts @@ -10,6 +10,11 @@ export interface InstalledExtension { folder: ExtensionFolder; requires: string[]; library: boolean; + /** The API and firmware the package needs, as in its catalog entry. */ + api: string; + firmware_id: string; + /** The SDK that packed it. */ + sdk: string; } export interface DeviceSnapshot { diff --git a/src/lib/extensions.ts b/src/lib/extensions.ts index ab6f26f..4073f69 100644 --- a/src/lib/extensions.ts +++ b/src/lib/extensions.ts @@ -122,10 +122,44 @@ export async function refreshCatalog(signal?: AbortSignal) { } } +function loads(copy: InstalledExtension, current = state) { + const info = current.device.info; + return !info || checkCompatibility(copy, info).compatible; +} + /** The loader uses the first valid copy in path order, with /Reprise first. */ function activeCopy(id: string, current = state) { - const copies = current.device.installed.filter((item) => item.id === id); - return copies.find((item) => item.folder === extensionFolder) ?? copies[0]; + const copies = current.device.installed + .filter((item) => item.id === id) + .sort((a, b) => Number(b.folder === extensionFolder) - Number(a.folder === extensionFolder)); + return copies.find((item) => loads(item, current)) ?? copies[0]; +} + +/** Whether the firmware on the iPod loads the copy of `id` it picks and its required libraries. */ +export function installedCompatibility( + id: string, + current = state, + seen = new Set(), +): Compatibility | null { + const copy = activeCopy(id, current); + const info = current.device.info; + if (!copy || !info) return null; + const result = checkCompatibility(copy, info); + seen.add(id); + for (const library of result.compatible ? copy.requires : []) { + if (seen.has(library)) continue; + const loaded = + activeCopy(library, current)?.library && + installedCompatibility(library, current, seen)?.compatible; + if (loaded) continue; + const name = activeCopy(library, current)?.name ?? library; + return { + compatible: false, + summary: "Missing library", + reason: `Missing required library ${name}`, + }; + } + return result; } export function installedVersion(id: string, current = state) { @@ -135,15 +169,24 @@ export function installedVersion(id: string, current = state) { export interface EntryStatus { installed?: string; updateAvailable: boolean; + /** The catalog version on this iPod. */ compatibility: Compatibility | null; + /** The installed copy, judged by its own package. */ + installedCompatibility: Compatibility | null; + /** The catalog version can replace an installed copy the firmware does not load. */ + canReplace: boolean; } export function entryStatus(entry: CatalogEntry, current = state): EntryStatus { const installed = installedVersion(entry.id, current); const info = current.device.info; + const compatibility = info ? checkCompatibility(entry, info) : null; + const copy = installed ? installedCompatibility(entry.id, current) : null; return { installed, updateAvailable: !!installed && compareVersions(entry.version, installed) > 0, - compatibility: info ? checkCompatibility(entry, info) : null, + compatibility, + installedCompatibility: copy, + canReplace: copy?.compatible === false && compatibility?.compatible !== false, }; } @@ -217,6 +260,7 @@ export async function installExtension(id: string) { entry.id === id || !installedVersion(entry.id) || activeCopy(entry.id)?.library === false || + installedCompatibility(entry.id)?.compatible === false || compareVersions(entry.version, installedVersion(entry.id) ?? "0") > 0, ); } catch (error) { diff --git a/tests/devScenarios.test.mjs b/tests/devScenarios.test.mjs index 415e67d..5bf8607 100644 --- a/tests/devScenarios.test.mjs +++ b/tests/devScenarios.test.mjs @@ -243,3 +243,54 @@ test("experimental hardware scenario requires a current explicit approval", asyn /changed/, ); }); + +test("extension scenarios simulate a mounted iPod and its copies", async () => { + const backend = createMockBackend(findScenario("extensions-older-builds"), immediate); + const first = await backend.invoke("read_extension_device", {}); + assert.equal(first.snapshot.device.sdkFloor, "1.89"); + assert.deepEqual( + first.snapshot.installed.map((copy) => [copy.id, copy.sdk, copy.library, copy.requires]), + [ + ["night-shift", "1.84", false, []], + ["dsp", "1.85", true, []], + ["crossfeed", "1.89", false, ["dsp"]], + ], + ); + assert.equal(await backend.invoke("read_extension_device", { knownMounts: first.mounts }), null); + // A package header carries the SDK at byte 8 and the manifest's minimum API at byte 36. + const data = new Array(64).fill(0); + data.splice(8, 4, 0x59, 0, 1, 0); + data.splice(36, 4, 0x54, 0, 1, 0); + await backend.invoke("write_extension", { package: { id: "dsp", version: "0.1.1", data } }); + await backend.invoke("write_extension", { package: { id: "balance", version: "0.1.0", data } }); + await backend.invoke("remove_extension", { id: "night-shift" }); + // Writes and removals keep the mount key; the refresh after an operation reads without one. + assert.equal(await backend.invoke("read_extension_device", { knownMounts: first.mounts }), null); + const next = await backend.invoke("read_extension_device", {}); + assert.equal(next.mounts, first.mounts); + assert.deepEqual( + next.snapshot.installed.map((copy) => [ + copy.id, + copy.version, + copy.api, + copy.sdk, + copy.requires, + ]), + [ + ["dsp", "0.1.1", "1.84", "1.89", []], + ["crossfeed", "0.1.1", "1.84", "1.89", ["dsp"]], + ["balance", "0.1.0", "1.84", "1.89", []], + ], + ); + await backend.invoke("eject_and_reboot", {}); + assert.deepEqual(await backend.invoke("read_extension_device", {}), { + mounts: "none", + snapshot: null, + }); + assert.equal(await backend.invoke("read_extension_device", { knownMounts: "none" }), null); + const bare = createMockBackend(findScenario("checks-passed"), immediate); + assert.deepEqual(await bare.invoke("read_extension_device", {}), { + mounts: "none", + snapshot: null, + }); +}); diff --git a/tests/extensions.test.mjs b/tests/extensions.test.mjs index 133377c..f8878ec 100644 --- a/tests/extensions.test.mjs +++ b/tests/extensions.test.mjs @@ -14,8 +14,10 @@ import { checkExtensionMounts, configureExtensions, ejectAndReboot, + entryStatus, getExtensionsState, installExtension, + installedCompatibility, installedVersion, loadExtensions, refreshCatalog, @@ -101,9 +103,9 @@ test("an open catalog picks up new screenshots and keeps them if the next refres assert.equal(getExtensionsState().catalog, catalog); }); -function simulatedDevice() { +function simulatedDevice(copies = [], info = device) { const installed = new Map(); - function store(id, version, folder) { + function store(id, version, folder, api, sdk) { const entry = document.extensions.find((item) => item.id === id); installed.set(folder + id, { id, @@ -112,15 +114,19 @@ function simulatedDevice() { name: entry.name, requires: entry.requires, library: entry.category === "library", + api: api ?? entry.api, + firmware_id: entry.firmware_id, + sdk: sdk ?? api ?? entry.api, }); } store("balance", "0.1.0", "/Reprise/Extensions/"); store("night-shift", "0.0.9", "/Revola/Extensions/"); + for (const copy of copies) store(...copy); return { async read() { return { mounts: "first", - snapshot: { device: { ...device, token: "first" }, installed: [...installed.values()] }, + snapshot: { device: { ...info, token: "first" }, installed: [...installed.values()] }, }; }, async write({ id, version }) { @@ -162,6 +168,155 @@ test("compatibility follows firmware, API, RepriseOS version and models", () => ); }); +test("a known release names the RepriseOS to install instead of the API", () => { + const future = parseCatalog(document, base).find((item) => item.id === "future"); + assert.equal(checkCompatibility(future, device).reason, "Needs a newer RepriseOS (API 1.90)"); + assert.equal( + checkCompatibility({ ...future, min_repriseos: "0.6.0" }, device).reason, + "Needs RepriseOS 0.6.0", + ); + assert.equal( + checkCompatibility({ ...future, min_repriseos: "0.4.0" }, device).reason, + "Needs a newer RepriseOS (API 1.90)", + ); +}); + +test("installed copies are judged by their own API and the loader's choice", async () => { + configureExtensions({ + fetch: fakeFetch(), + device: simulatedDevice([ + ["night-shift", "0.2.0", "/Reprise/Extensions/", "1.90"], + ["crossfeed", "0.2.0", "/Reprise/Extensions/", "1.90"], + ]), + catalogUrl: base, + }); + await loadExtensions(); + // The too-new /Reprise copy is skipped, so the /Revola copy runs and can update. + assert.equal(installedVersion("night-shift"), "0.0.9"); + assert.deepEqual(installedCompatibility("night-shift"), { compatible: true }); + assert.deepEqual( + availableUpdates().map((item) => item.id), + ["night-shift"], + ); + // The only crossfeed copy is too new: newer than the catalog, but not loaded. + assert.equal(installedVersion("crossfeed"), "0.2.0"); + assert.equal(installedCompatibility("crossfeed").reason, "Needs a newer RepriseOS (API 1.90)"); + assert.equal(installedCompatibility("dsp"), null); + const crossfeed = getExtensionsState().catalog.entries.find((item) => item.id === "crossfeed"); + assert.equal(entryStatus(crossfeed).canReplace, true); +}); + +test("a copy whose required library the firmware skips does not load either", async () => { + configureExtensions({ + fetch: fakeFetch(), + device: simulatedDevice([ + ["dsp", "0.2.0", "/Reprise/Extensions/", "1.90"], + ["crossfeed", "0.1.0", "/Reprise/Extensions/"], + ]), + catalogUrl: base, + }); + await loadExtensions(); + assert.equal(installedCompatibility("crossfeed").reason, "Missing required library Dsp"); + const crossfeed = getExtensionsState().catalog.entries.find((item) => item.id === "crossfeed"); + assert.equal(entryStatus(crossfeed).canReplace, true); +}); + +test("a library copy the firmware skips is reinstalled with its dependent", async () => { + configureExtensions({ + fetch: fakeFetch(), + device: simulatedDevice([["dsp", "0.2.0", "/Reprise/Extensions/", "1.90"]]), + catalogUrl: base, + }); + await loadExtensions(); + await installExtension("crossfeed"); + assert.deepEqual( + getExtensionsState().operations.crossfeed.steps.map((step) => step.label), + [ + "Check compatibility", + "Download and verify Dsp 0.1.0", + "Download and verify Crossfeed 0.1.0", + "Copy to /Reprise/Extensions/", + ], + ); + assert.deepEqual(installedCompatibility("dsp"), { compatible: true }); +}); + +test("an update the iPod cannot load leaves the installed copy compatible", async () => { + configureExtensions({ + fetch: fakeFetch(), + device: simulatedDevice([["future", "0.0.1", "/Reprise/Extensions/", "1.78"]]), + catalogUrl: base, + }); + await loadExtensions(); + assert.deepEqual(installedCompatibility("future"), { compatible: true }); + const future = getExtensionsState().catalog.entries.find((item) => item.id === "future"); + assert.equal(entryStatus(future).canReplace, false); + assert.equal( + availableUpdates().some((item) => item.id === "future"), + false, + ); +}); + +test("a firmware with an SDK floor refuses older builds and offers rebuilt releases", async () => { + const floor = { ...device, repriseos: "0.5.0", api: "1.86", sdkFloor: "1.86" }; + const rebuilt = { + ...document, + extensions: document.extensions.map((item) => + item.id === "night-shift" ? { ...item, version: "0.1.3", api: "1.86" } : item, + ), + }; + configureExtensions({ + fetch: async (url) => + url === base ? Response.json(rebuilt) : new Response("missing", { status: 404 }), + device: simulatedDevice( + [ + ["night-shift", "0.1.2", "/Reprise/Extensions/", "1.84", "1.84"], + ["crossfeed", "0.1.1", "/Reprise/Extensions/", "1.84", "1.86"], + ["dsp", "0.1.0", "/Reprise/Extensions/", "1.74", "1.85"], + ], + floor, + ), + catalogUrl: base, + }); + await loadExtensions(); + // The copy of Night Shift predates the floor; the catalog's rebuilt release loads. + assert.equal(installedCompatibility("night-shift").reason, "Built for an older RepriseOS"); + const entries = getExtensionsState().catalog.entries; + const nightShift = entries.find((item) => item.id === "night-shift"); + assert.deepEqual(entryStatus(nightShift).compatibility, { compatible: true }); + assert.equal(entryStatus(nightShift).canReplace, true); + // A library packed before the floor fails its user; the catalog's build is as old. + assert.equal(installedCompatibility("dsp").summary, "Older build"); + assert.equal(installedCompatibility("crossfeed").reason, "Missing required library Dsp"); + const dsp = entries.find((item) => item.id === "dsp"); + assert.equal(entryStatus(dsp).compatibility.summary, "Older build"); + assert.equal(entryStatus(dsp).canReplace, false); + // Catalog builds that predate the floor are neither installable nor updates. + assert.deepEqual( + availableUpdates().map((item) => item.id), + ["night-shift"], + ); + assert.equal( + entryStatus(entries.find((item) => item.id === "balance")).compatibility.summary, + "Older build", + ); + // An entry above the device's API still asks for a newer RepriseOS. + assert.equal( + entryStatus(entries.find((item) => item.id === "future")).compatibility.summary, + "Needs newer RepriseOS", + ); +}); + +test("a firmware without an SDK floor loads every build of its major", async () => { + configureExtensions({ + fetch: fakeFetch(), + device: simulatedDevice([["night-shift", "0.1.2", "/Reprise/Extensions/", "1.81", "1.81"]]), + catalogUrl: base, + }); + await loadExtensions(); + assert.deepEqual(installedCompatibility("night-shift"), { compatible: true }); +}); + test("development bypasses the OS release gate but respects known RVX requirements", () => { const balance = parseCatalog(document, base)[0]; const dev = { ...device, repriseos: "Development", api: "1.81" };