From 1cff83dd49dec845d73b3454320da8b6b44f7b2c Mon Sep 17 00:00:00 2001 From: Ionut Mladin Date: Thu, 3 Dec 2026 00:21:05 +0200 Subject: [PATCH 1/2] Installer: a system snapshot on iPadOS 12-14 is held space, and can go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an iPad Air (J71) with iPadOS 12.5.8 and checkra1n 0.12.4, --split said "iPadOS 32 GB, 32 GB used" and "can spare 0 GB" while iPadOS used 12.6 GB. The companion reported 12,638,662,656 bytes allocated but an APFS minimum of 31,711,035,392: iPadOS's update snapshot, which iPadOS doesn't run from under checkra1n 0.12.4, held about 19 GB (resize-apfs#28). The installer showed max(allocated, minimum) as used, and told the user to delete apps, which frees nothing there. - The layout now tells used (allocated) from what iPadOS keeps (APFS's minimum), and carries the system snapshot the companion already reported. The split still never goes below the minimum. - The companion's helper answers remove_snapshot with resize-apfs's engine (its checks: current revision, the reported name, removable, no operation) and has the vfs snapshot entitlement for it. The installer waits up to 150 s, and reads the layout again after a dropped connection. - The CLI explains the snapshot and asks before removing it (--remove-snapshot without a terminal); the window's no-room screen offers "Remove the snapshot…" and asks once more. Both offer it only where it gives the system its 10 GB. Where the snapshot can't go, both say what holds the space and point to Resize APFS instead of "delete some apps". - ORCHARD_DEMO_SNAPSHOT=1 shows that case in the window's demo. - A removal counts by APFS's own minimum: on the J71 the engine's answer still listed the snapshot (its scan from before) while the minimum had fallen from 31.7 to 13.1 GB. A snapshot reported to hold more than the minimum keeps above what is allocated is taken as gone. - The storage numbers the split is sized from go into the run log. Assisted-by: LLM Co-Authored-By: Claude Opus 5.5 --- companion/Helper/helper.entitlements.plist | 2 + companion/Helper/main.swift | 13 ++ companion/PROTOCOL.md | 10 + crates/app/src/install_screens.rs | 42 +++- crates/cli/src/commands/install.rs | 141 +++++++++++++- crates/flow/src/lib.rs | 137 ++++++++++++- crates/flow/src/tests.rs | 106 +++++++++- crates/runtime/src/companion.rs | 214 ++++++++++++++++++++- crates/runtime/src/demo.rs | 33 +++- crates/runtime/src/driver.rs | 1 + crates/runtime/src/install.rs | 2 +- docs/install.md | 9 + 12 files changed, 670 insertions(+), 40 deletions(-) diff --git a/companion/Helper/helper.entitlements.plist b/companion/Helper/helper.entitlements.plist index 5f664ae..ca502d8 100644 --- a/companion/Helper/helper.entitlements.plist +++ b/companion/Helper/helper.entitlements.plist @@ -8,6 +8,8 @@ com.apple.security.iokit-user-client-class AppleAPFSUserClientAppleKeyStoreUserClient + + com.apple.private.vfs.snapshot com.apple.springboard.launchapplications com.apple.frontboard.launchapplications diff --git a/companion/Helper/main.swift b/companion/Helper/main.swift index 21e6a19..32aba86 100644 --- a/companion/Helper/main.swift +++ b/companion/Helper/main.swift @@ -393,6 +393,19 @@ final class Server: @unchecked Sendable { try reply(fd, okJSON: data) // The copy shows the running split from now on. publish(try? engine.snapshot()) + case "remove_snapshot": + // iPadOS 12-14: the system snapshot that keeps APFS from shrinking, + // which the user approved removing. The engine checks it again (the + // layout's revision, the name, that iPadOS neither runs from it nor + // reverts to it) and inspects the storage afterwards. + guard let name = args["name"] as? String, !name.isEmpty, + let revisionText = args["revision"] as? String, let revision = UUID(uuidString: revisionText) + else { throw ResizeError("Removing a snapshot needs its name and the layout's revision.") } + log("removing the snapshot \(name)") + let snapshot = try engine.removeSnapshot(SnapshotRequest(revision: revision, name: name)) + log("removed the snapshot \(name)") + try reply(fd, okJSON: JSONEncoder().encode(snapshot)) + publish(snapshot) default: throw ResizeError("Unknown request.") } } catch { diff --git a/companion/PROTOCOL.md b/companion/PROTOCOL.md index 8879e57..c903925 100644 --- a/companion/PROTOCOL.md +++ b/companion/PROTOCOL.md @@ -64,6 +64,7 @@ anything else, or a wrong token, closes the connection. {"hello": {"token": "…", "protocol": 1}} {"snapshot": {}} {"split": {"apfs_bytes": 64000000000, "revision": "…", "replacing": ["…"]}} +{"remove_snapshot": {"name": "…", "revision": "…"}} {"ping": {}} {"log": {}} ``` @@ -85,6 +86,15 @@ Answers are `{"ok": …}` or `{"error": {"message": "…"}}`. approved erasing on the split screen. It must name exactly all of them; the split removes their GPT entries in its verified GPT write, so it always leaves iPadOS and free space after it (resize-apfs's plan). +- `remove_snapshot` → the new snapshot, as `snapshot` answers it. iPadOS 12-14: + removes the system snapshot `layout.systemSnapshot` names (iPadOS's update + snapshot, or checkra1n's orig-fs), whose blocks keep APFS from shrinking + below `minimumContainerBytes`. The user approves it on the split screen. + resize-apfs's engine refuses it unless `revision` is the current layout's, + the name is the one it reports, it is `removable` (iPadOS neither runs from + it nor reverts to it) and no operation runs; afterwards it asks APFS for the + new minimum. The answer can take two minutes: the installer waits that long, + and reads the layout again after a dropped connection. - `log` → `{"text": "…"}`: the last 64 KiB of the helper's log (see the table above), with seconds since the helper started. The installer saves it after connecting, to see where the time between diff --git a/crates/app/src/install_screens.rs b/crates/app/src/install_screens.rs index 15cad98..8801514 100644 --- a/crates/app/src/install_screens.rs +++ b/crates/app/src/install_screens.rs @@ -396,21 +396,43 @@ pub fn split_erase_dialog(layout: &Layout, approved: bool, connected: bool, stuc } /// 2.2c: not enough free space. -fn no_room(layout: &Layout, cx: &mut Context) -> Div { +/// `removing`: the companion is removing the system snapshot; +/// `confirming`: the user is asked whether to; `problem`: why it didn't. +fn no_room(layout: &Layout, removing: bool, confirming: bool, problem: Option<&str>, cx: &mut Context) -> Div { let free = layout.max_omarchy_gb(); - let subtitle = orchard_flow::for_device(&format!( - "{} needs at least {MIN_OMARCHY_GB} GB, and iPadOS only has {free} GB free right now. Delete some apps or files on your iPad, then check again.", - sys() - )) - .to_owned(); - div() + // A snapshot that may go and would make room: removing it is the way on. + let freeable = layout.snapshot_offer(); + let reason = match freeable { + Some((snap, after)) => orchard_flow::snapshot_reason(layout, &snap.name, after, &sys()), + None => orchard_flow::no_room_hint(layout), + }; + let subtitle = format!("{} {reason}", orchard_flow::for_device(&format!("{} needs at least {MIN_OMARCHY_GB} GB, and iPadOS can spare {free} GB right now.", sys()))); + let mut col = div() .w_full() .flex() .flex_col() .gap(px(22.)) .child(header(orchard_flow::for_device("Not enough free space on your iPad"), subtitle, TITLE)) - .child(div().w_full().flex().flex_col().gap(px(12.)).child(split_labels(layout.total_gb, 0)).child(split_bar(layout, 0., OmarchyNote::Needs, None, cx))) - .child(actions().child(primary("check-again", "Check again", 18., 9., Event::Retry, cx))) + .child(div().w_full().flex().flex_col().gap(px(12.)).child(split_labels(layout.total_gb, 0)).child(split_bar(layout, 0., OmarchyNote::Needs, None, cx))); + if let Some(problem) = problem { + let line = orchard_flow::for_device(&format!("Your iPad didn't remove the snapshot: {problem}")).to_owned(); + col = col.child(div().w_full().text_size(px(13.)).line_height(px(19.)).text_color(c(AMBER)).child(line)); + } + let buttons = match (freeable, removing, confirming) { + (Some(_), true, _) => actions().child(div().text_size(px(13.)).text_color(c(MUTED)).child("Removing the snapshot. This can take a few minutes.")), + // Removing it can't be undone: asked once more. + (Some(_), false, true) => { + col = col.child(div().w_full().text_size(px(13.)).line_height(px(19.)).text_color(c(AMBER)).child("Remove the snapshot? This can't be undone.")); + actions() + .child(secondary("keep-snapshot", "Cancel", 18., 9., Event::AskRemoveSnapshot(false), cx)) + .child(primary("remove-snapshot", "Remove", 18., 9., Event::RemoveSnapshot, cx)) + } + (Some(_), false, false) => actions() + .child(secondary("check-again", "Check again", 18., 9., Event::Retry, cx)) + .child(primary("ask-remove-snapshot", "Remove the snapshot…", 18., 9., Event::AskRemoveSnapshot(true), cx)), + (None, _, _) => actions().child(primary("check-again", "Check again", 18., 9., Event::Retry, cx)), + }; + col.child(buttons) } /// The split's three steps (2.4, 2.4b, 2.5): done, now, later. @@ -1266,7 +1288,7 @@ pub fn text_column(installer: &mut Installer, cx: &mut Context) -> Op State::ChooseSplit { layout, omarchy_gb, approved, .. } => { installer.layout = Some(layout.clone()); if layout.max_omarchy_gb() < MIN_OMARCHY_GB { - no_room(layout, cx).into_any_element() + no_room(layout, installer.flow.removing_snapshot, installer.flow.confirming_snapshot, installer.flow.split_problem.as_deref(), cx).into_any_element() } else { // While dragging, the window's own position; else the flow's. let shown = installer.drag.as_ref().map(|d| d.value).unwrap_or(*omarchy_gb as f32); diff --git a/crates/cli/src/commands/install.rs b/crates/cli/src/commands/install.rs index 66bac74..18b840c 100644 --- a/crates/cli/src/commands/install.rs +++ b/crates/cli/src/commands/install.rs @@ -50,6 +50,11 @@ pub struct InstallArgs { /// Don't resize and don't ask: the system goes into the existing split #[arg(long, conflicts_with = "split")] pub no_split: bool, + /// With --split, iPadOS 12 to 14: approve removing iPadOS's update + /// snapshot (or checkra1n's orig-fs) where it keeps iPadOS from giving up + /// space; asked when not given + #[arg(long, requires = "split")] + pub remove_snapshot: bool, /// Install into a disk file on this computer instead of the device's /// storage: FILE, else -.img in Orchard's disks /// folder. The device and iPadOS stay as they are @@ -507,6 +512,38 @@ fn layout_bar(layout: &Layout, ipados_gb: u32, system_gb: Option, width: us row } +/// What the run does about a system snapshot whose removal gives the +/// system room (`Layout::snapshot_offer`): `max` is what iPadOS can spare +/// with it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SnapshotStep { + /// --remove-snapshot approved it. + Remove, + /// Too little room without it: ask (a terminal). + Ask, + /// Too little room and nobody to ask: stop and name the option. + NeedsFlag, + /// There is room as it is: only say what removing it would add. + Mention, +} + +fn snapshot_step(max: u32, approved: bool, tty: bool) -> SnapshotStep { + match (approved, max < MIN_OMARCHY_GB, tty) { + (true, _, _) => SnapshotStep::Remove, + (false, true, true) => SnapshotStep::Ask, + (false, true, false) => SnapshotStep::NeedsFlag, + (false, false, _) => SnapshotStep::Mention, + } +} + +/// Why a removable system snapshot should go, before asking. +fn snapshot_note(out: &mut Out, layout: &Layout, snap: &orchard_flow::HeldSnapshot, after: u32, name: &str) { + let held = layout.held_gb(); + out.term.blank(); + out.heading("A system snapshot holds space", Some(format!("{held} GB"))); + out.sub(orchard_flow::snapshot_reason(layout, &snap.name, after, name)); +} + /// T.3: the storage now and after. fn split_overview(out: &mut Out, layout: &Layout, gb: u32, name: &str) { out.term.blank(); @@ -514,6 +551,9 @@ fn split_overview(out: &mut Out, layout: &Layout, gb: u32, name: &str) { out.sub("Your apps and data stay where they are."); out.term.blank(); let mut note = orchard_flow::for_device(&format!("iPadOS {} GB, {} GB used", layout.ipados_gb, layout.ipados_used_gb)).to_owned(); + if layout.held_gb() > 0 { + note.push_str(&format!(", {} GB more held", layout.held_gb())); + } for p in &layout.outside { note.push_str(&format!(" · {} {} GB", p.name, p.gb)); } @@ -1472,6 +1512,12 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { // --apple-password-file, read when the sign-in asks. let mut apple_password = args.apple_password_file.as_ref().map(read_secret); let mut split_done = false; + // The system snapshot: whether its removal was offered, the one being + // removed (its name) while the companion works on it, and whether the + // iPadOS line was said. + let mut snapshot_offered = false; + let mut removing: Option<(String, bool, u32)> = None; + let mut ipados_said = false; let mut erase_done = false; let mut account_sent = false; let mut account_continued = false; @@ -1503,7 +1549,7 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { Err(RecvTimeoutError::Disconnected) => return finish(&mut out, Exit::Failed, "driver", "the installer stopped"), }; let interrupts = INTERRUPTS.load(Ordering::SeqCst); - let busy = shared.last == "splitting" || shared.last == "installing"; + let busy = shared.last == "splitting" || shared.last == "installing" || removing.is_some(); if interrupts > 0 { if busy && interrupts == 1 { if !ctrl_c_said { @@ -1793,17 +1839,86 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } } State::ChooseSplit { layout, omarchy_gb, .. } => { + // The companion removes the snapshot: wait for its new layout. + // Flows sent before the removal started don't end the wait. + if let Some((_, seen, _)) = removing.as_mut() { + if flow.removing_snapshot { + *seen = true; + continue; + } + if !*seen { + continue; + } + } + if let Some((removed, _, kept_before)) = removing.take() { + out.term.live(None); + if let Some(why) = &flow.split_problem { + out.fail(orchard_flow::for_device("The snapshot wasn't removed").to_owned()); + out.sub(why.clone()); + send(Event::Quit); + std::thread::sleep(Duration::from_secs(1)); + return finish(&mut out, Exit::Failed, "snapshot", why); + } + // Gone by APFS's own minimum, whatever the snapshot list says. + if layout.snapshot.as_ref().is_some_and(|s| s.name == removed) && layout.ipados_kept_gb() >= kept_before { + out.fail(orchard_flow::for_device("The snapshot is still there").to_owned()); + out.sub(orchard_flow::for_device("Your iPad didn't confirm removing it. Restart your iPad, then try again.").to_owned()); + send(Event::Quit); + std::thread::sleep(Duration::from_secs(1)); + return finish(&mut out, Exit::Failed, "snapshot", "the snapshot is still there"); + } + out.ok(format!("Removed the snapshot {removed}")); + split_done = false; + } if !split_done { split_done = true; out.term.live(None); - out.ok(orchard_flow::for_device("Your iPad is running iPadOS with the installer's app")); + if !ipados_said { + ipados_said = true; + out.ok(orchard_flow::for_device("Your iPad is running iPadOS with the installer's app")); + } let max = layout.max_omarchy_gb(); - out.event(json!({"event": "split", "total_gb": layout.total_gb, "ipados_gb": layout.ipados_gb, "ipados_used_gb": layout.ipados_used_gb, "suggested_gb": omarchy_gb, "min_gb": MIN_OMARCHY_GB, "max_gb": max, "after_ipados": layout.outside.iter().map(|p| json!({"name": p.name, "filesystem": p.filesystem, "gb": p.gb})).collect::>()})); + let snapshot = layout.snapshot.as_ref().map(|s| json!({"name": s.name, "held_gb": s.held_gb, "removable": s.removable, "runs_from": s.runs_from, "max_gb_without": layout.max_omarchy_gb_without_snapshot()})); + out.event(json!({"event": "split", "total_gb": layout.total_gb, "ipados_gb": layout.ipados_gb, "ipados_used_gb": layout.ipados_used_gb, "ipados_floor_gb": layout.ipados_kept_gb(), "snapshot": snapshot, "suggested_gb": omarchy_gb, "min_gb": MIN_OMARCHY_GB, "max_gb": max, "after_ipados": layout.outside.iter().map(|p| json!({"name": p.name, "filesystem": p.filesystem, "gb": p.gb})).collect::>()})); let shown = args.split.flatten().map(|g| g.min(max)).unwrap_or(*omarchy_gb); split_overview(&mut out, layout, shown, &name); + // A snapshot that may go and would give the system the room it lacks. + if let Some((snap, after)) = layout.snapshot_offer().filter(|_| !snapshot_offered) { + snapshot_offered = true; + let snap = snap.clone(); + let choice = snapshot_step(max, args.remove_snapshot, out.term.tty); + if choice != SnapshotStep::Mention { + snapshot_note(&mut out, layout, &snap, after, &name); + } + let approved = match choice { + SnapshotStep::Remove => true, + SnapshotStep::Ask => out + .term + .ask(vec![s(" Remove the snapshot? ", FG), s("y", BLUE), s("/", MUTED), s("N", BLUE), s(": ", MUTED)], false) + .is_some_and(|a| matches!(a.trim(), "y" | "Y" | "yes")), + SnapshotStep::NeedsFlag => { + out.event(json!({"event": "needs", "action": "input", "flag": "--remove-snapshot"})); + out.fail(orchard_flow::for_device(&format!("iPadOS can spare {max} GB with the snapshot and about {after} GB without it. Run again with --remove-snapshot to remove it")).to_owned()); + send(Event::Quit); + std::thread::sleep(Duration::from_secs(1)); + return finish(&mut out, Exit::NeedsInput, "needs-input", "--remove-snapshot"); + } + SnapshotStep::Mention => { + out.muted(orchard_flow::for_device(&format!(" A system snapshot holds space: without it iPadOS could spare about {after} GB (--remove-snapshot)")).to_owned()); + false + } + }; + if approved { + out.event(json!({"event": "remove-snapshot", "name": snap.name})); + out.term.live_restart(vec![s("Removing the snapshot", SUB), s(" up to a few minutes", MUTED)]); + removing = Some((snap.name.clone(), false, layout.ipados_kept_gb())); + send(Event::RemoveSnapshot); + continue; + } + } if max < MIN_OMARCHY_GB { out.fail(orchard_flow::for_device(&format!("{name} needs at least {MIN_OMARCHY_GB} GB, and iPadOS can spare {max} GB right now")).to_owned()); - out.sub(orchard_flow::for_device("Delete some apps or files on your iPad, then try again.")); + out.sub(orchard_flow::no_room_hint(layout)); send(Event::Quit); std::thread::sleep(Duration::from_secs(1)); return finish(&mut out, Exit::Failed, "no-room", "not enough free space"); @@ -2377,6 +2492,20 @@ fn not_pwned(out: &mut Out) -> ExitCode { #[cfg(test)] mod tests { + #[test] + fn a_snapshot_is_removed_only_when_approved_and_asked_only_when_needed() { + use super::{snapshot_step, SnapshotStep}; + // No room with it: a terminal asks; without one the run stops before + // removing it and names the option. + assert_eq!(snapshot_step(0, false, true), SnapshotStep::Ask); + assert_eq!(snapshot_step(0, false, false), SnapshotStep::NeedsFlag); + assert_eq!(snapshot_step(0, true, false), SnapshotStep::Remove); + // Room as it is: only mentioned, unless approved. + assert_eq!(snapshot_step(12, false, true), SnapshotStep::Mention); + assert_eq!(snapshot_step(12, false, false), SnapshotStep::Mention); + assert_eq!(snapshot_step(12, true, true), SnapshotStep::Remove); + } + use super::*; fn install_args(given: &[&str]) -> Option { @@ -2489,7 +2618,7 @@ mod tests { use orchard_flow::assets::{Asset, AssetState}; let device = run(Sequence::HomePower, Phase::ready()).device; let installing = |percent, streamed| State::Installing { device: device.clone(), percent, link: Link::Up, streamed, step: None }; - let layout = Layout { total_gb: 128, ipados_gb: 58, ipados_used_gb: 41, outside: vec![], outside_bytes: 0 }; + let layout = Layout { total_gb: 128, ipados_gb: 58, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: 0 }; let account = |env| State::CreateAccount { device: device.clone(), account: Default::default(), env, erase_approved: false, slow: false }; let mut flow = Flow::new(); for asset in [Asset::Palera1n, Asset::Chain, Asset::RootImage, Asset::PlatformLayer, Asset::Firmware, Asset::KernelPackage] { @@ -2635,7 +2764,7 @@ mod tests { #[test] fn the_layout_bars_fill_their_width() { - let layout = Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, outside: vec![], outside_bytes: 0 }; + let layout = Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: 0 }; let width = |row: Vec| row.iter().map(|(t, _)| t.chars().count()).sum::(); assert_eq!(width(layout_bar(&layout, 128, None, 40)), 40); assert_eq!(width(layout_bar(&layout, 58, Some(70), 40)), 40); diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index de0149d..b8a8c1e 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -167,12 +167,36 @@ pub struct Partition { pub gb: u32, } +/// A system snapshot of iPadOS 12-14 (its update snapshot, or checkra1n's +/// orig-fs): its blocks stay where they are, so APFS can't shrink below them +/// even though iPadOS doesn't use that space. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeldSnapshot { + pub name: String, + /// What it holds above what iPadOS uses, where that is known. + pub held_gb: Option, + /// It may be removed now (iPadOS neither runs from it nor reverts to it). + pub removable: bool, + /// iPadOS runs from it (a stock checkra1n boot): it is renamed and the + /// device restarted before it can go, which resize-apfs's app does. + pub runs_from: bool, + /// What iPadOS can't shrink below once it is gone, where that is known. + pub floor_after_gb: Option, +} + /// The storage as iPadOS (split) or the install environment (install) reads it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Layout { pub total_gb: u32, pub ipados_gb: u32, + /// What iPadOS really uses (APFS's allocated blocks). pub ipados_used_gb: u32, + /// What iPadOS can't shrink below right now (APFS's own minimum), when + /// that is more than it uses: a snapshot can hold it up. 0 where only + /// the used space limits it. + pub ipados_floor_gb: u32, + /// The system snapshot that holds space, if there is one. + pub snapshot: Option, /// Everything after iPadOS; overwritten by the install. pub outside: Vec, /// The bytes after iPadOS, where they were read off the disk; 0 where @@ -181,9 +205,34 @@ pub struct Layout { } impl Layout { + /// What iPadOS keeps at least: what it uses, or more where APFS can't + /// shrink that far. + pub fn ipados_kept_gb(&self) -> u32 { + self.ipados_used_gb.max(self.ipados_floor_gb) + } /// The most iPadOS can give up while keeping its used space. pub fn max_omarchy_gb(&self) -> u32 { - self.total_gb.saturating_sub(self.ipados_used_gb + HEADROOM_GB) + self.total_gb.saturating_sub(self.ipados_kept_gb() + HEADROOM_GB) + } + /// The most iPadOS could give up once its removable snapshot is gone; + /// None without one, or where what it frees isn't known. + pub fn max_omarchy_gb_without_snapshot(&self) -> Option { + let snapshot = self.snapshot.as_ref().filter(|s| s.removable)?; + let kept = self.ipados_used_gb.max(snapshot.floor_after_gb?); + Some(self.total_gb.saturating_sub(kept + HEADROOM_GB)) + } + /// The removable system snapshot whose removal would give the system + /// room it lacks now (at least [`MIN_OMARCHY_GB`], more than without it), + /// with what iPadOS could spare then: what the apps offer to remove. + pub fn snapshot_offer(&self) -> Option<(&HeldSnapshot, u32)> { + let after = self.max_omarchy_gb_without_snapshot()?; + let snapshot = self.snapshot.as_ref()?; + (after >= MIN_OMARCHY_GB && after > self.max_omarchy_gb()).then_some((snapshot, after)) + } + /// Space APFS can't give up although iPadOS doesn't use it (a snapshot + /// holds it), in GB. + pub fn held_gb(&self) -> u32 { + self.ipados_floor_gb.saturating_sub(self.ipados_used_gb) } pub fn outside_gb(&self) -> u32 { self.total_gb - self.ipados_gb @@ -198,6 +247,42 @@ impl Layout { } } +/// What to do when iPadOS can't spare enough (both apps): free space, unless +/// a system snapshot (or anything else APFS keeps) holds what iPadOS doesn't +/// use. Deleting apps doesn't help then. +pub fn no_room_hint(layout: &Layout) -> String { + let held = layout.held_gb(); + match &layout.snapshot { + Some(snap) if snap.runs_from && held > 0 => for_device(&format!( + "iPadOS uses {} GB, but it runs from its update snapshot {}, which keeps it from shrinking below {} GB. Resize APFS (orchard resize) renames that snapshot and restarts the iPad; then it can be removed.", + layout.ipados_used_gb, snap.name, layout.ipados_kept_gb() + )) + .to_owned(), + Some(snap) if held > 0 => for_device(&format!( + "iPadOS uses {} GB, but the system snapshot {} keeps it from shrinking below {} GB. Resize APFS (orchard resize) shows it and can remove it.", + layout.ipados_used_gb, snap.name, layout.ipados_kept_gb() + )) + .to_owned(), + // Nothing named: APFS still keeps more than iPadOS uses (a snapshot, most likely). + None if held > 0 => for_device(&format!( + "iPadOS uses {} GB, but APFS can't shrink it below {} GB right now, most likely because of a system snapshot. Resize APFS (orchard resize) shows what holds it.", + layout.ipados_used_gb, layout.ipados_kept_gb() + )) + .to_owned(), + _ => for_device("Delete some apps or files on your iPad, then try again.").to_owned(), + } +} + +/// Why removing a removable system snapshot gives `system` room (both apps). +pub fn snapshot_reason(layout: &Layout, name: &str, after_gb: u32, system: &str) -> String { + for_device(&format!( + "iPadOS uses {} GB, but its snapshot {name} keeps it from shrinking below {} GB. The snapshot is a copy of the system from iPadOS's last update, and iPadOS doesn't run from it now. Without it iPadOS starts from its system as it is, and can give {system} about {after_gb} GB. Your apps and data stay. Removing it can't be undone.", + layout.ipados_used_gb, + layout.ipados_kept_gb() + )) + .to_owned() +} + /// Space iPadOS keeps free on top of what it uses. pub const HEADROOM_GB: u32 = 2; /// The least the install system takes, until the release states its unpacked @@ -424,6 +509,14 @@ pub enum Event { /// The companion refused the split or it stopped, with the reason: as /// a failed split, and the reason shows on the split screen. SplitRefused(String), + /// The window asks whether to remove the snapshot (true) or no longer + /// does (false, Cancel). + AskRemoveSnapshot(bool), + /// The user approved removing the layout's removable system snapshot + /// (split screen); the companion's new layout follows as IpadosReady. + RemoveSnapshot, + /// The companion didn't remove it, with the reason (split screen). + SnapshotRefused(String), EnvReady { layout: Layout }, /// Stream progress, from the receiver's `stream` events. InstallProgress(u8), @@ -479,6 +572,9 @@ pub enum Event { pub enum Effect { BootIpadosWithOverlay(DeviceId), StartSplit { omarchy_gb: u32 }, + /// Remove this system snapshot through the companion, then read the + /// storage again. + RemoveSnapshot { name: String }, /// Read iPadOS's storage again ("Check again" after freeing space). RefreshLayout, BootInstallEnv(DeviceId), @@ -535,6 +631,10 @@ pub struct Flow { pub companion: bool, /// Why the last split didn't happen, until the user changes the split. pub split_problem: Option, + /// The companion is removing the system snapshot (split screen). + pub removing_snapshot: bool, + /// The window asks whether to remove it. + pub confirming_snapshot: bool, /// Why the install failed (3.9). pub install_problem: Option, /// The account is asked again to continue an install found under way. @@ -695,7 +795,7 @@ impl Flow { } pub fn new() -> Flow { - Flow { ask_entry: false, state: State::start(), assets: Assets::default(), write_waiting: false, start_waiting: None, boot_waiting: None, companion: false, split_problem: None, install_problem: None, resuming: false, boot_stalled: false, booting: false, unresponsive: false, disk_exists: None, disk_file: None, system_ready: false, ssh_name: None, confirming_split: false, entry_started: false, start_attempt: 0, start_problem: None, start_log: Vec::new(), others: Vec::new(), held: Vec::new(), options: Options::default(), at: None, welcome: false, enter_problem: None } + Flow { ask_entry: false, state: State::start(), assets: Assets::default(), write_waiting: false, start_waiting: None, boot_waiting: None, companion: false, split_problem: None, removing_snapshot: false, confirming_snapshot: false, install_problem: None, resuming: false, boot_stalled: false, booting: false, unresponsive: false, disk_exists: None, disk_file: None, system_ready: false, ssh_name: None, confirming_split: false, entry_started: false, start_attempt: 0, start_problem: None, start_log: Vec::new(), others: Vec::new(), held: Vec::new(), options: Options::default(), at: None, welcome: false, enter_problem: None } } /// The asset the current step waits for, for "Getting your iPad ready…". @@ -1007,6 +1107,32 @@ fn step_inner(app: App, mut flow: Flow, event: Event) -> (Flow, Vec) { flow.split_problem = Some(reason); return step(app, flow, Event::SplitFinished { ok: false }); } + // Only on the split screen, for a snapshot the companion said may go, + // and once at a time. + Event::AskRemoveSnapshot(ask) => { + if let State::ChooseSplit { layout, .. } = &flow.state { + flow.confirming_snapshot = ask && !flow.removing_snapshot && layout.snapshot.as_ref().is_some_and(|s| s.removable); + } + return (flow, out); + } + Event::RemoveSnapshot => { + if let State::ChooseSplit { layout, .. } = &flow.state { + if let Some(snapshot) = layout.snapshot.as_ref().filter(|s| s.removable && !flow.removing_snapshot) { + out.push(Effect::RemoveSnapshot { name: snapshot.name.clone() }); + flow.removing_snapshot = true; + flow.confirming_snapshot = false; + flow.split_problem = None; + } + } + return (flow, out); + } + Event::SnapshotRefused(reason) => { + if flow.removing_snapshot { + flow.removing_snapshot = false; + flow.split_problem = Some(reason); + } + return (flow, out); + } Event::DiskExists(path) => { flow.disk_exists = Some(path); return (flow, out); @@ -1094,6 +1220,7 @@ fn step_inner(app: App, mut flow: Flow, event: Event) -> (Flow, Vec) { } if matches!(event, Event::IpadosReady { .. }) { flow.companion = true; + flow.removing_snapshot = false; } // A changed split is a new attempt: the old reason no longer applies. if matches!(event, Event::SetOmarchySize(_) | Event::Approve(_)) && matches!(flow.state, State::ChooseSplit { .. }) { @@ -1143,6 +1270,8 @@ fn step_inner(app: App, mut flow: Flow, event: Event) -> (Flow, Vec) { } if !matches!(flow.state, State::ChooseSplit { .. }) { flow.confirming_split = false; + flow.removing_snapshot = false; + flow.confirming_snapshot = false; } // A held boot only counts while the flow still waits for it. if !matches!(flow.state, State::WaitingForIpados { .. }) { @@ -1438,7 +1567,7 @@ fn update_plain(app: App, ctx: &Ctx, state: State, event: Event) -> (State, Vec< S::CreateAccount { device, account: Account::default(), - env: Some(Layout { total_gb: 0, ipados_gb: 0, ipados_used_gb: 0, outside: Vec::new(), outside_bytes: 0 }), + env: Some(Layout { total_gb: 0, ipados_gb: 0, ipados_used_gb: 0, ipados_floor_gb: 0, snapshot: None, outside: Vec::new(), outside_bytes: 0 }), erase_approved: true, slow: false, }, @@ -1884,7 +2013,7 @@ fn suggested_size(layout: &Layout) -> u32 { return layout.outside_gb().min(max); } let half = layout.total_gb / 2; - let leaving = layout.total_gb.saturating_sub(layout.ipados_used_gb + SUGGESTED_BUFFER_GB); + let leaving = layout.total_gb.saturating_sub(layout.ipados_kept_gb() + SUGGESTED_BUFFER_GB); half.min(leaving).max(MIN_OMARCHY_GB).min(max) } diff --git a/crates/flow/src/tests.rs b/crates/flow/src/tests.rs index 2b0de13..b72dbb6 100644 --- a/crates/flow/src/tests.rs +++ b/crates/flow/src/tests.rs @@ -65,7 +65,7 @@ fn ipad8() -> Device { } fn fresh() -> Layout { - Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, outside: vec![], outside_bytes: 0 } + Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: 0 } } fn split_before() -> Layout { @@ -73,6 +73,8 @@ fn split_before() -> Layout { total_gb: 128, ipados_gb: 64, ipados_used_gb: 41, + ipados_floor_gb: 0, + snapshot: None, outside: vec![ Partition { name: "BOOT".into(), filesystem: "FAT32".into(), gb: 1 }, Partition { name: "omarchy-a".into(), filesystem: "ext4".into(), gb: 63 }, @@ -772,7 +774,7 @@ fn create_account() -> State { } fn installed_layout() -> Layout { - Layout { total_gb: 128, ipados_gb: 96, ipados_used_gb: 41, outside: vec![], outside_bytes: 0 } + Layout { total_gb: 128, ipados_gb: 96, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: 0 } } #[test] @@ -1307,7 +1309,7 @@ fn an_install_system_found_at_start_continues_by_its_phase() { #[test] fn reopening_the_app_on_a_ready_install_system_prepares_into_free_space() { - let free = Layout { total_gb: 128, ipados_gb: 64, ipados_used_gb: 20, outside: Vec::new(), outside_bytes: 0 }; + let free = Layout { total_gb: 128, ipados_gb: 64, ipados_used_gb: 20, ipados_floor_gb: 0, snapshot: None, outside: Vec::new(), outside_bytes: 0 }; let (flow, e) = step(App::Installer, with_install_system(), Event::EnvReady { layout: free }); assert!(matches!(flow.state, State::CreateAccount { env: Some(_), .. })); // Preparing starts once the files it needs are in (they were started @@ -1317,7 +1319,7 @@ fn reopening_the_app_on_a_ready_install_system_prepares_into_free_space() { let (flow, _) = step(App::Installer, flow, Event::Continue); assert!(matches!(flow.state, State::Installing { .. })); // Too little room: not prepared. - let small = Layout { total_gb: 64, ipados_gb: 60, ipados_used_gb: 20, outside: Vec::new(), outside_bytes: 0 }; + let small = Layout { total_gb: 64, ipados_gb: 60, ipados_used_gb: 20, ipados_floor_gb: 0, snapshot: None, outside: Vec::new(), outside_bytes: 0 }; let (flow, _) = step(App::Installer, with_install_system(), Event::EnvReady { layout: small }); assert!(matches!(flow.state, State::NotPrepared { .. })); } @@ -1389,7 +1391,7 @@ fn a_split_that_erases_partitions_is_confirmed_in_a_dialog() { // ---- Suggested split and resume ---- fn layout_of(total: u32, used: u32) -> Layout { - Layout { total_gb: total, ipados_gb: total, ipados_used_gb: used, outside: Vec::new(), outside_bytes: 0 } + Layout { total_gb: total, ipados_gb: total, ipados_used_gb: used, ipados_floor_gb: 0, snapshot: None, outside: Vec::new(), outside_bytes: 0 } } #[test] @@ -1602,7 +1604,7 @@ fn a_device_other_work_holds_is_waited_for_not_unplugged() { #[test] fn space_that_is_there_is_measured_in_bytes_against_orchards_least() { - let layout = |bytes: u64| Layout { total_gb: 64, ipados_gb: 54, ipados_used_gb: 20, outside: vec![], outside_bytes: bytes }; + let layout = |bytes: u64| Layout { total_gb: 64, ipados_gb: 54, ipados_used_gb: 20, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: bytes }; // 9.5 GB reads as 10 GB and is less than an 8 GiB root and a 1 GiB boot partition. assert_eq!(layout(0).outside_gb(), MIN_OMARCHY_GB); assert!(!layout(9_500_000_000).has_room()); @@ -1610,7 +1612,7 @@ fn space_that_is_there_is_measured_in_bytes_against_orchards_least() { assert!(!layout(MIN_SYSTEM_BYTES - 1).has_room()); // Where only whole GB are known, they decide. assert!(layout(0).has_room()); - let small = Layout { total_gb: 64, ipados_gb: 55, ipados_used_gb: 20, outside: vec![], outside_bytes: 0 }; + let small = Layout { total_gb: 64, ipados_gb: 55, ipados_used_gb: 20, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: 0 }; assert!(!small.has_room()); } @@ -1813,3 +1815,93 @@ fn stopping_in_dfu_starts_nothing_there() { let (flow, _) = steps(App::Launcher, vec![dfu(ipad6()), Event::Continue]); assert!(matches!(flow.state, State::Launching { .. }), "{:?}", flow.state); } + +// ---- iPadOS 12-14: a system snapshot holds space ---- + +fn snapshot_layout(removable: bool) -> Layout { + Layout { + total_gb: 32, + ipados_gb: 32, + ipados_used_gb: 13, + ipados_floor_gb: 32, + snapshot: Some(HeldSnapshot { name: "com.apple.os.update-AB".into(), held_gb: Some(18), removable, runs_from: !removable, floor_after_gb: Some(13) }), + outside: vec![], + outside_bytes: 0, + } +} + +#[test] +fn a_held_floor_limits_the_split_not_the_used_space() { + let l = snapshot_layout(true); + assert_eq!((l.ipados_kept_gb(), l.held_gb(), l.max_omarchy_gb()), (32, 19, 0)); + assert_eq!(l.max_omarchy_gb_without_snapshot(), Some(17)); + assert_eq!(snapshot_layout(false).max_omarchy_gb_without_snapshot(), None); + // The suggestion leaves iPadOS what it keeps, not only what it uses. + let roomy = Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 20, ipados_floor_gb: 60, snapshot: None, outside: vec![], outside_bytes: 0 }; + assert!(matches!(choose_split(roomy), State::ChooseSplit { omarchy_gb: 58, .. }), "128 - 60 - 10"); + assert_eq!(kind(App::Installer, &choose_split(snapshot_layout(true))), ScreenKind::ChooseSplitNoRoom); +} + +#[test] +fn removing_a_snapshot_asks_the_companion_once_then_takes_its_layout() { + let (flow, _) = steps(App::Installer, vec![Event::Started, dfu(ipad6()), Event::Continue, Event::IpadosReady { layout: snapshot_layout(true) }]); + let (flow, e) = step(App::Installer, flow, Event::RemoveSnapshot); + assert_eq!(e, vec![Effect::RemoveSnapshot { name: "com.apple.os.update-AB".into() }]); + assert!(flow.removing_snapshot); + let (flow, e) = step(App::Installer, flow, Event::RemoveSnapshot); + assert!(e.is_empty(), "once at a time"); + let freed = Layout { ipados_floor_gb: 13, snapshot: None, ..snapshot_layout(true) }; + let (flow, _) = step(App::Installer, flow, Event::IpadosReady { layout: freed }); + assert!(!flow.removing_snapshot); + assert!(matches!(flow.state, State::ChooseSplit { omarchy_gb: 10, .. }), "iPadOS keeps its 13 GB and 10 more; the system at least 10"); + assert_eq!(kind(App::Installer, &flow.state), ScreenKind::ChooseSplitLittleRoom); +} + +#[test] +fn a_refused_removal_says_why_and_a_kept_snapshot_is_never_asked_for() { + let (flow, _) = steps(App::Installer, vec![Event::Started, dfu(ipad6()), Event::Continue, Event::IpadosReady { layout: snapshot_layout(true) }]); + let (flow, _) = step(App::Installer, flow, Event::RemoveSnapshot); + let (flow, e) = step(App::Installer, flow, Event::SnapshotRefused("Storage changed.".into())); + assert!(e.is_empty()); + assert!(!flow.removing_snapshot); + assert_eq!(flow.split_problem.as_deref(), Some("Storage changed.")); + // iPadOS runs from it: nothing to remove here. + let (flow, _) = steps(App::Installer, vec![Event::Started, dfu(ipad6()), Event::Continue, Event::IpadosReady { layout: snapshot_layout(false) }]); + let (flow, e) = step(App::Installer, flow, Event::RemoveSnapshot); + assert!(e.is_empty() && !flow.removing_snapshot); + // Not on another screen. + let (flow, _) = steps(App::Installer, vec![Event::Started, dfu(ipad6())]); + assert!(step(App::Installer, flow, Event::RemoveSnapshot).1.is_empty()); +} + +#[test] +fn no_room_says_what_holds_the_space() { + let roomless = Layout { ipados_used_gb: 25, ..layout_of(32, 25) }; + assert!(no_room_hint(&roomless).starts_with("Delete some apps")); + let held = Layout { ipados_floor_gb: 31, ..layout_of(32, 13) }; + assert!(no_room_hint(&held).contains("can't shrink it below 31 GB"), "{}", no_room_hint(&held)); + let runs = snapshot_layout(false); + assert!(no_room_hint(&runs).contains("orchard resize")); + assert!(!no_room_hint(&runs).contains("Delete some apps")); + let reason = snapshot_reason(&snapshot_layout(true), "com.apple.os.update-AB", 17, "Omarchy A"); + assert!(reason.contains("uses 13 GB") && reason.contains("below 32 GB") && reason.contains("about 17 GB") && reason.contains("can't be undone")); +} + +#[test] +fn the_window_asks_before_removing_and_only_offers_what_makes_room() { + let (flow, _) = steps(App::Installer, vec![Event::Started, dfu(ipad6()), Event::Continue, Event::IpadosReady { layout: snapshot_layout(true) }]); + let (flow, e) = step(App::Installer, flow, Event::AskRemoveSnapshot(true)); + assert!(e.is_empty() && flow.confirming_snapshot); + let (flow, _) = step(App::Installer, flow, Event::AskRemoveSnapshot(false)); + assert!(!flow.confirming_snapshot); + let (flow, _) = step(App::Installer, flow, Event::AskRemoveSnapshot(true)); + let (flow, e) = step(App::Installer, flow, Event::RemoveSnapshot); + assert_eq!(e.len(), 1); + assert!(!flow.confirming_snapshot && flow.removing_snapshot); + // Offered only where it gives the system its minimum. + assert_eq!(snapshot_layout(true).snapshot_offer().map(|(_, gb)| gb), Some(17)); + let little = Layout { total_gb: 24, ipados_gb: 24, ..snapshot_layout(true) }; + assert_eq!(little.max_omarchy_gb_without_snapshot(), Some(9)); + assert!(little.snapshot_offer().is_none(), "9 GB is still too little"); + assert!(snapshot_layout(false).snapshot_offer().is_none()); +} diff --git a/crates/runtime/src/companion.rs b/crates/runtime/src/companion.rs index 8e5f802..57168d9 100644 --- a/crates/runtime/src/companion.rs +++ b/crates/runtime/src/companion.rs @@ -3,7 +3,7 @@ //! storage layout and the split's progress to the flow as events. use crate::usbmux; use orchard_cache::{Code, Error, Result}; -use orchard_flow::{Device, Event, Layout, Partition}; +use orchard_flow::{Device, Event, HeldSnapshot, Layout, Partition}; use serde::Deserialize; use serde_json::{json, Value}; use std::io::{BufRead, BufReader, Write}; @@ -16,6 +16,9 @@ pub const PORT: u16 = 49720; const PROTOCOL: u64 = 1; const PING: Duration = Duration::from_secs(2); const POLL: Duration = Duration::from_secs(5); +/// How long removing a system snapshot may take before the installer reads +/// the storage again instead (the helper allows itself 120 s). +const SNAPSHOT_REMOVAL: Duration = Duration::from_secs(150); fn fail(message: impl Into) -> Error { Error::new(Code::Network, message.into()) @@ -64,10 +67,29 @@ pub struct StorageLayout { pub minimum_container_bytes: Option, #[serde(default)] pub issue: Option, + /// The system snapshot that can hold APFS's minimum up (iOS 12-14). + #[serde(default)] + pub system_snapshot: Option, #[serde(skip)] backing: Option, } +/// resize-apfs's `SystemSnapshot`: iOS's update snapshot or checkra1n's +/// orig-fs on iOS 12-14, whose blocks stay where they are, so APFS can't +/// shrink below them. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SystemSnapshot { + pub name: String, + pub present: bool, + pub removable: bool, + /// How much it raises APFS's minimum, as resize-apfs estimates it. + #[serde(default)] + pub held_bytes: Option, + #[serde(default)] + pub mounted_as_system: Option, +} + #[derive(Debug, Clone, Deserialize)] pub struct Operation { pub status: String, @@ -90,7 +112,34 @@ pub struct Snapshot { pub operation: Option, } +impl Snapshot { + fn parse(raw: Value) -> Result { + let mut snapshot: Snapshot = + serde_json::from_value(raw.clone()).map_err(|e| fail(format!("unreadable snapshot: {e}")))?; + snapshot.layout = snapshot.layout.resolve(&raw["layout"])?; + Ok(snapshot) + } +} + impl StorageLayout { + /// The numbers the split is sized from, for the run log. + pub fn describe(&self) -> String { + let snapshot = match &self.system_snapshot { + None => "none reported".to_owned(), + Some(s) => format!( + "{} (present {}, removable {}, holds {:?} bytes, iPadOS runs from it {:?})", + s.name, s.present, s.removable, s.held_bytes, s.mounted_as_system + ), + }; + format!( + "storage: splittable {} bytes, APFS container {} bytes, allocated {} bytes, APFS minimum {:?} bytes; system snapshot: {snapshot}", + self.splittable_bytes(), + self.container_bytes, + self.allocated_bytes, + self.minimum_container_bytes + ) + } + fn apfs(&self) -> Option<&StoragePartition> { self.backing.map(|i| &self.partitions[i]) } @@ -114,13 +163,33 @@ impl StorageLayout { (self.last_usable_lba - apfs.first_lba + 1) * self.sector_size } - /// The flow's view: iPadOS keeps at least what APFS reports as its - /// smallest size; everything after it becomes Omarchy A's. + /// The flow's view: iPadOS uses what APFS has allocated, and keeps at + /// least what APFS reports as its smallest size (more than it uses where + /// a system snapshot holds blocks); everything after it becomes Omarchy A's. pub fn flow_layout(&self) -> Layout { let gb = |b: i64| (b.max(0) as f64 / 1e9).round() as u32; let up = |b: i64| (b.max(0) as f64 / 1e9).ceil() as u32; let apfs = self.apfs().unwrap(); - let used = self.allocated_bytes.max(self.minimum_container_bytes.unwrap_or(0)); + let floor = self.allocated_bytes.max(self.minimum_container_bytes.unwrap_or(0)); + // A snapshot can't hold more than APFS's minimum keeps above what is + // allocated. Reported so after its removal (resize-apfs's engine can + // answer its scan from before), it is gone: APFS's own minimum decides. + let stale = |s: &&SystemSnapshot| match (self.minimum_container_bytes, s.held_bytes) { + (Some(minimum), Some(held)) => held > minimum - self.allocated_bytes + 1_000_000_000, + _ => false, + }; + let snapshot = self.system_snapshot.as_ref().filter(|s| s.present).filter(|s| !stale(s)).map(|s| HeldSnapshot { + name: s.name.clone(), + held_gb: s.held_bytes.map(gb), + removable: s.removable, + runs_from: s.mounted_as_system == Some(true), + // APFS's minimum without what the snapshot holds, never below + // what iPadOS has allocated (resize-apfs's estimate, rounded up). + floor_after_gb: match (self.minimum_container_bytes, s.held_bytes) { + (Some(minimum), Some(held)) => Some(up(self.allocated_bytes.max(minimum - held))), + _ => None, + }, + }); let outside = self .partitions .iter() @@ -134,7 +203,9 @@ impl StorageLayout { Layout { total_gb: gb(self.splittable_bytes()), ipados_gb: gb((apfs.last_lba - apfs.first_lba + 1) * self.sector_size), - ipados_used_gb: up(used), + ipados_used_gb: up(self.allocated_bytes), + ipados_floor_gb: up(floor), + snapshot, outside, outside_bytes: (self.splittable_bytes() - (apfs.last_lba - apfs.first_lba + 1) * self.sector_size).max(0) as u64, } @@ -222,10 +293,18 @@ impl Client { pub fn snapshot(&mut self) -> Result { let raw = self.request(json!({"snapshot": {}}))?; - let mut snapshot: Snapshot = - serde_json::from_value(raw.clone()).map_err(|e| fail(format!("unreadable snapshot: {e}")))?; - snapshot.layout = snapshot.layout.resolve(&raw["layout"])?; - Ok(snapshot) + Snapshot::parse(raw) + } + + /// Removes the system snapshot `name` of the layout `revision` (the one + /// the user saw) and answers the storage as it is then. The helper + /// remounts the system volume, removes it and asks APFS for its new + /// minimum, which can take minutes (resize-apfs#34). + pub fn remove_snapshot(&mut self, name: &str, revision: &str) -> Result { + self.stream.set_read_timeout(Some(SNAPSHOT_REMOVAL))?; + let raw = self.request(json!({"remove_snapshot": {"name": name, "revision": revision}})); + let _ = self.stream.set_read_timeout(Some(Duration::from_secs(10))); + Snapshot::parse(raw?) } pub fn split(&mut self, apfs_bytes: i64, revision: &str, replacing: &[String]) -> Result<()> { @@ -244,6 +323,8 @@ pub enum Job { Split { omarchy_gb: u32 }, /// Read the storage again and report it. Refresh, + /// Remove the system snapshot of this name, then report the storage. + RemoveSnapshot { name: String }, /// Restart the iPad; answers when the companion took the request (or not). Restart(Sender), } @@ -309,6 +390,9 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { // reconnect, which may find it already done (the connection can drop // while the iPad works). let mut split_pending = false; + // A snapshot removal whose answer didn't come (the connection dropped or + // timed out): the layout is reported again after the reconnect. + let mut layout_pending = false; let mut next_try = Instant::now(); let mut last_error = String::new(); let (mut last_ping, mut last_poll) = (Instant::now(), Instant::now()); @@ -364,6 +448,35 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { let ok = session.as_mut().is_some_and(|s| s.client.restart().map_err(|e| eprintln!("companion: restart: {e}")).is_ok()); let _ = done.send(ok); } + Some(Job::RemoveSnapshot { name }) => match session.as_mut() { + None => { + let _ = events.send(Event::SnapshotRefused("The installer lost the connection to your iPad. Try again.".into())); + } + Some(s) => { + let revision = s.layout.revision.clone(); + match s.client.remove_snapshot(&name, &revision) { + Ok(fresh) => { + eprintln!("companion: removed snapshot {name}; {}", fresh.layout.describe()); + s.layout = fresh.layout; + let _ = events.send(Event::IpadosReady { layout: s.layout.flow_layout() }); + } + // The helper's answer: it didn't remove it. + Err(e) if e.code == Code::InvalidInput => { + eprintln!("companion: remove snapshot: {e}"); + let _ = events.send(Event::SnapshotRefused(e.to_string())); + } + // No answer: it may have been removed all the same. + // Read the storage again once reconnected. + Err(e) => { + eprintln!("companion: remove snapshot: {e}; reading the storage again"); + session = None; + layout_pending = true; + next_try = Instant::now() + RETRY; + let _ = events.send(Event::CompanionLost); + } + } + } + }, Some(Job::Refresh) => match session.as_mut().map(|s| s.client.snapshot().map(|f| (f, s))) { Some(Ok((fresh, s))) => { s.layout = fresh.layout; @@ -395,6 +508,9 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { let splitting = running.is_some() || split_pending; if announced { let _ = events.send(Event::CompanionBack); + if std::mem::take(&mut layout_pending) { + let _ = events.send(Event::IpadosReady { layout: snapshot.layout.flow_layout() }); + } } else if let Some(op) = running { // A split this run didn't start is running (the // installer was closed during it): watch it again. @@ -499,6 +615,7 @@ fn open(socket: &Path, t: &Target) -> Result { Ok(s) => s, Err(e) => return Ok(Opened::NotYet(e.to_string())), }; + eprintln!("companion: {}", snapshot.layout.describe()); if let Some(issue) = &snapshot.layout.issue { return Ok(Opened::Refused(issue.clone())); } @@ -538,11 +655,88 @@ mod tests { fn the_engine_layout_becomes_the_flow_layout() { let s = parse(snapshot()); let l = s.layout.flow_layout(); - assert_eq!((l.total_gb, l.ipados_gb, l.ipados_used_gb), (32, 32, 20), "iPadOS keeps APFS's minimum"); + assert_eq!((l.total_gb, l.ipados_gb, l.ipados_used_gb), (32, 32, 19), "used is what APFS has allocated"); + assert_eq!(l.ipados_kept_gb(), 20, "iPadOS keeps APFS's minimum"); assert!(l.outside.is_empty()); + assert!(l.snapshot.is_none()); assert_eq!(l.max_omarchy_gb(), 10); } + /// Ionuț's iPad Air (J71, iPadOS 12.5.8, checkra1n 0.12.4), as its + /// companion reported it on 3 December 2026: 12.6 GB allocated, but iPadOS's + /// update snapshot holds APFS's minimum at 31.7 of 32 GB. + fn j71_ios12() -> Value { + let mut raw = snapshot(); + let layout = &mut raw["layout"]; + layout["sectorSize"] = json!(4096); + layout["lastUsableLBA"] = json!(7_812_494); + layout["partitions"] = json!([ + {"id": "B", "name": "Container", "bsdName": "disk0s1", "kind": "apfs", "firstLBA": 8, "lastLBA": 7_812_487, "typeGUID": "x", "contents": "APFS"} + ]); + layout["containerBytes"] = json!(31_999_918_080u64); + layout["allocatedBytes"] = json!(12_638_662_656u64); + layout["minimumContainerBytes"] = json!(31_711_035_392u64); + layout["systemSnapshot"] = json!({ + "name": "com.apple.os.update-70289BA1F6D56969172F9644158091682F160483", + "present": true, "removable": true, "heldBytes": 18_998_099_968u64 + }); + raw + } + + #[test] + fn a_system_snapshot_is_held_space_not_used_space() { + let s = parse(j71_ios12()); + assert_eq!(s.layout.splittable_bytes(), 31_999_946_752); + let l = s.layout.flow_layout(); + assert_eq!((l.total_gb, l.ipados_used_gb, l.ipados_kept_gb(), l.held_gb()), (32, 13, 32, 19), "13 GB used, the rest held"); + assert_eq!(l.max_omarchy_gb(), 0, "no more than APFS can shrink to"); + let snap = l.snapshot.clone().unwrap(); + assert!(snap.removable && !snap.runs_from); + assert_eq!((snap.held_gb, snap.floor_after_gb), (Some(19), Some(13))); + assert_eq!(l.max_omarchy_gb_without_snapshot(), Some(17)); + // The split itself never goes below APFS's minimum while it is there. + assert!(s.layout.apfs_bytes_for(10).is_err()); + assert!(s.layout.describe().contains("allocated 12638662656 bytes, APFS minimum Some(31711035392) bytes")); + } + + #[test] + fn once_the_snapshot_is_gone_the_split_has_room() { + let mut raw = j71_ios12(); + raw["layout"]["minimumContainerBytes"] = json!(12_713_000_960u64); + raw["layout"]["systemSnapshot"] = Value::Null; + let s = parse(raw); + let l = s.layout.flow_layout(); + assert_eq!((l.ipados_used_gb, l.ipados_kept_gb(), l.max_omarchy_gb()), (13, 13, 17)); + assert!(l.snapshot.is_none()); + assert!(s.layout.apfs_bytes_for(17).is_ok()); + } + + /// The J71's answer to remove_snapshot (3 December 2026): APFS's minimum + /// fell to 13.1 GB, but the engine still listed the snapshot as before. + #[test] + fn a_removed_snapshot_reported_as_before_is_gone_by_apfs_minimum() { + let mut raw = j71_ios12(); + raw["layout"]["allocatedBytes"] = json!(12_642_488_320u64); + raw["layout"]["minimumContainerBytes"] = json!(13_134_462_976u64); + raw["layout"]["systemSnapshot"]["heldBytes"] = json!(18_981_322_752u64); + let s = parse(raw); + let l = s.layout.flow_layout(); + assert!(l.snapshot.is_none(), "it can't hold 19 GB under a 13.1 GB minimum"); + assert_eq!((l.ipados_used_gb, l.ipados_kept_gb(), l.max_omarchy_gb()), (13, 14, 16)); + assert!(s.layout.apfs_bytes_for(16).is_ok()); + } + + #[test] + fn a_snapshot_ios_runs_from_is_reported_but_not_removable() { + let mut raw = j71_ios12(); + raw["layout"]["systemSnapshot"]["removable"] = json!(false); + raw["layout"]["systemSnapshot"]["mountedAsSystem"] = json!(true); + let l = parse(raw).layout.flow_layout(); + let snap = l.snapshot.clone().unwrap(); + assert!(snap.runs_from && !snap.removable); + assert_eq!(l.max_omarchy_gb_without_snapshot(), None); + } + #[test] fn a_split_names_all_partitions_after_apfs() { let mut raw = snapshot(); diff --git a/crates/runtime/src/demo.rs b/crates/runtime/src/demo.rs index 9be6877..dc0773a 100644 --- a/crates/runtime/src/demo.rs +++ b/crates/runtime/src/demo.rs @@ -52,11 +52,34 @@ fn earlier_system(gb: u32) -> Vec { /// What iPadOS reports before the split: 128 GB, 41 GB used. /// ORCHARD_DEMO_EXISTING=1: an earlier system of 32 GB is there, so the /// split asks before it erases it. +/// ORCHARD_DEMO_SNAPSHOT=1: iPadOS 12's update snapshot holds the space +/// (an iPad Air on iPadOS 12.5.8: 32 GB, 13 GB used, APFS's minimum 32 GB), +/// until the demo removes it. +static SNAPSHOT_GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + fn ipados_layout() -> Layout { + if std::env::var_os("ORCHARD_DEMO_SNAPSHOT").is_some() { + let gone = SNAPSHOT_GONE.load(std::sync::atomic::Ordering::Relaxed); + return Layout { + total_gb: 32, + ipados_gb: 32, + ipados_used_gb: 13, + ipados_floor_gb: if gone { 13 } else { 32 }, + snapshot: (!gone).then(|| orchard_flow::HeldSnapshot { + name: "com.apple.os.update-70289BA1F6D56969172F9644158091682F160483".into(), + held_gb: Some(19), + removable: true, + runs_from: false, + floor_after_gb: Some(13), + }), + outside: Vec::new(), + outside_bytes: 0, + }; + } if std::env::var_os("ORCHARD_DEMO_EXISTING").is_some() && !SPLIT.load(std::sync::atomic::Ordering::Relaxed) { - return Layout { total_gb: 128, ipados_gb: 96, ipados_used_gb: 41, outside: earlier_system(32), outside_bytes: 0 }; + return Layout { total_gb: 128, ipados_gb: 96, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: earlier_system(32), outside_bytes: 0 }; } - Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, outside: Vec::new(), outside_bytes: 0 } + Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: Vec::new(), outside_bytes: 0 } } /// What the install system reports: empty space after a split, which asked @@ -67,6 +90,8 @@ fn env_layout(omarchy_gb: u32) -> Layout { total_gb: 128, ipados_gb: 128 - omarchy_gb, ipados_used_gb: 41, + ipados_floor_gb: 0, + snapshot: None, outside: if SPLIT.load(std::sync::atomic::Ordering::Relaxed) { Vec::new() } else { earlier_system(omarchy_gb) }, outside_bytes: 0, } @@ -149,6 +174,10 @@ pub fn run(app: App, mut observer: impl Observer, input: Receiver, _event due.push((at(5.), Event::IpadosReady { layout: ipados_layout() })); } Effect::RefreshLayout => due.push((at(1.), Event::IpadosReady { layout: ipados_layout() })), + Effect::RemoveSnapshot { .. } => { + SNAPSHOT_GONE.store(true, std::sync::atomic::Ordering::Relaxed); + due.push((at(4.), Event::IpadosReady { layout: ipados_layout() })); + } Effect::StartSplit { omarchy_gb: gb } => { *omarchy_gb = gb; // ORCHARD_DEMO_REFUSE=1: the first split is refused, to see that screen. diff --git a/crates/runtime/src/driver.rs b/crates/runtime/src/driver.rs index e6404d3..3e724e7 100644 --- a/crates/runtime/src/driver.rs +++ b/crates/runtime/src/driver.rs @@ -333,6 +333,7 @@ impl Driver { Effect::BootEntry(id) => drop(self.launcher_jobs.send(crate::launcher::Job::Boot(id))), Effect::StartSplit { omarchy_gb } => drop(self.companion_jobs.send(CompanionJob::Split { omarchy_gb })), Effect::RefreshLayout => drop(self.companion_jobs.send(CompanionJob::Refresh)), + Effect::RemoveSnapshot { name } => drop(self.companion_jobs.send(CompanionJob::RemoveSnapshot { name: name.clone() })), Effect::PrepareRecovery(id) => crate::recovery_mode::spawn(id, false, self.events.clone()), Effect::RestartFromRecovery(id) => crate::recovery_mode::spawn(id, true, self.events.clone()), Effect::BootInstallEnv(_) | Effect::BootIpadosWithOverlay(_) => { diff --git a/crates/runtime/src/install.rs b/crates/runtime/src/install.rs index 66d2aa0..271ee16 100644 --- a/crates/runtime/src/install.rs +++ b/crates/runtime/src/install.rs @@ -116,7 +116,7 @@ pub fn flow_layout(gpt: &Gpt) -> Layout { 0 => blocks(gpt.partitions.iter().map(|p| p.blocks).sum::() + gpt.free.iter().map(|f| f.blocks).sum::()), bytes => bytes, }; - Layout { total_gb: total, ipados_gb: gb(ipados), ipados_used_gb: 0, outside, outside_bytes: disk.saturating_sub(blocks(ipados)) } + Layout { total_gb: total, ipados_gb: gb(ipados), ipados_used_gb: 0, ipados_floor_gb: 0, snapshot: None, outside, outside_bytes: disk.saturating_sub(blocks(ipados)) } } impl Worker { diff --git a/docs/install.md b/docs/install.md index 35b0056..48b8574 100644 --- a/docs/install.md +++ b/docs/install.md @@ -34,6 +34,14 @@ the release. Each file is checked before it is used. the existing split. With a terminal and neither, the run offers both to choose from. Resizing runs a helper in iPadOS ([The helper that resizes](#the-helper-that-resizes)). + On iPadOS 12 to 14 a system snapshot (iPadOS's update snapshot, or + checkra1n's orig-fs) can keep APFS from shrinking far below its size + although iPadOS uses much less. The run shows what iPadOS uses and what + the snapshot holds. When iPadOS doesn't run from the snapshot and it keeps + the system from fitting, the run explains it and asks whether to remove + it (it can't be undone; apps and data stay); `--remove-snapshot` approves + that, also where there is room without it. A snapshot iPadOS runs from is + renamed and the device restarted by Resize APFS ([resize.md](resize.md)). 3. **DFU mode.** To start the install system, orchard restarts the device into recovery mode and guides it from there into DFU mode ([DFU mode](#dfu-mode)). @@ -80,6 +88,7 @@ into iPadOS. Nothing is asked. What no option answers ends the run with exit status 5 and names the option: `--yes`, `--password-file`, `--pin-file`, `--split GB`, +`--remove-snapshot`, `--replace` or `--another` (with `--disk`), `--apple-id` with `--apple-password-file`. Apple's sign-in code can only be typed, so a first sign-in with the Dopamine helper needs a terminal. From 6c8dbd626fb07ec91d440f9d5c7d7243c8f3d6af Mon Sep 17 00:00:00 2001 From: Ionut Mladin Date: Thu, 3 Dec 2026 01:01:06 +0200 Subject: [PATCH 2/2] CHANGELOG: a system snapshot on iPadOS 12-14 no longer blocks the split Assisted-by: LLM Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b44e632..8f550ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ is on main, the release is published with that section as its notes (AGENTS.md, ### Installer and launcher +- On iPadOS 12 to 14, splitting the storage tells the space iPadOS uses + from the space a system snapshot holds (iPadOS's update snapshot after a + checkra1n 0.12.4 start, or checkra1n's orig-fs). Before, such an iPad + could show all its storage as used and "can spare 0 GB". Where iPadOS + doesn't run from the snapshot, the installer explains it and offers to + remove it (`--remove-snapshot` without a terminal), which gives the + space back. + - Choosing Dopamine in the Options after a start with palera1n didn't work now switches to Dopamine: the installer finds the device again as it is, and Continue installs the helper app. Before, it kept sending the device