From ccce9d0145931b62cdc635943c668e64f80b91bf Mon Sep 17 00:00:00 2001 From: Grier Johnson Date: Fri, 4 Dec 2026 17:01:40 -0700 Subject: [PATCH] Installer: show size-based shrink time estimate and live progress Large APFS shrinks (100+ GB) take well over an hour (~1 min/GB), so the hardcoded 'around 30 minutes' estimate misled users into thinking the operation had hung, and neither the GUI nor CLI surfaced the helper's live step or byte progress. - Compute upfront split action (shrink/grow/partition-only) from the actual APFS container size and show a size-based estimate (~1 min/GB) on the split picker and while splitting. - Parse the helper's optional telemetry fields tolerantly into SplitProgress (released/total bytes, step count, finishing stage, and rate-paired elapsed time) without breaking terminal status handling. - Track both locally started and adopted splits through reconnects so a split that finishes or stops during a disconnect always delivers its terminal outcome, and mark adopted splits connected so GUI/CLI show live progress instead of a reconnect warning. - Surface live progress, paired ETA, and finishing state in the GUI and CLI (80-column-safe live TTY line, non-TTY milestones, JSON events, and clean exit on split refusal). - Update companion app copy to avoid a fixed 30-minute claim. Fixes #157 Assisted-by: LLM --- companion/App/App.swift | 2 +- crates/app/src/install_screens.rs | 110 +++++-- crates/app/src/lib.rs | 11 +- crates/cli/src/commands/install.rs | 218 +++++++++++++- crates/flow/src/lib.rs | 216 +++++++++++++- crates/flow/src/tests.rs | 164 +++++++++- crates/flow/src/view.rs | 2 +- crates/runtime/src/companion.rs | 460 +++++++++++++++++++++++++++-- crates/runtime/src/demo.rs | 8 +- crates/runtime/src/install.rs | 12 +- 10 files changed, 1110 insertions(+), 93 deletions(-) diff --git a/companion/App/App.swift b/companion/App/App.swift index 71afdc9a..60d40141 100644 --- a/companion/App/App.swift +++ b/companion/App/App.swift @@ -204,7 +204,7 @@ private func splitting(minutes: UILabel) -> UIView { width.priority = .defaultHigh width.isActive = true return column([badge(.accent, 0.08, fixed(Spinner(), 40, 40)), - heading("Splitting the storage", "This can take around 30 minutes. Your computer shows how it's going."), + heading("Splitting the storage", "Shrinking can take around 1 minute per GB. Your computer shows how it's going."), minutes, box]) } diff --git a/crates/app/src/install_screens.rs b/crates/app/src/install_screens.rs index 0c84d3a2..6a545f02 100644 --- a/crates/app/src/install_screens.rs +++ b/crates/app/src/install_screens.rs @@ -6,7 +6,7 @@ use crate::screens::{column, event_link, icon, paragraph, pressable, primary, se use crate::theme::*; use crate::Installer; use gpui::{div, linear_color_stop, linear_gradient, prelude::*, px, Context, Div, FontWeight, MouseButton, SharedString}; -use orchard_flow::{Account, Event, Flow, Layout, Link, SnapshotOffer, State, MIN_OMARCHY_GB}; +use orchard_flow::{Account, Event, Flow, Layout, Link, SnapshotOffer, SplitAction, SplitProgress, State, MIN_OMARCHY_GB}; use std::time::Instant; /// The text column's width on the full-width split screens (960 − 2 × 72). @@ -400,13 +400,23 @@ fn choose_split(layout: &Layout, shown_gb: f32, approved: bool, flow: &Flow, stu let snapshot = snapshot_box(layout, flow, seconds, cx); // Little room, and no snapshot box that offers more: say how to get more. let little = max < orchard_flow::RECOMMENDED_OMARCHY_GB && snapshot.is_none(); - let slider = div() + let chosen = shown_gb.round() as u32; + let mut slider = div() .w_full() .flex() .flex_col() .gap(px(12.)) - .child(split_labels(layout.total_gb - shown_gb.round() as u32, shown_gb.round() as u32)) + .child(split_labels(layout.total_gb - chosen, chosen)) .child(split_bar(layout, shown_gb, if replaces { OmarchyNote::Replaces } else { OmarchyNote::None }, Some((focus, ring)), cx)); + if let SplitAction::Shrink { gb } = orchard_flow::split_action(layout, chosen) { + let approx = orchard_flow::format_approx_minutes(orchard_flow::shrink_estimate_minutes(gb)); + slider = slider.child( + div() + .text_size(px(12.)) + .text_color(c(MUTED)) + .child(orchard_flow::for_device(&format!("Shrinking iPadOS by {gb} GB typically takes {approx} (~1 min per GB, depending on data layout).")).to_owned()), + ); + } let mut col = div().w_full().flex().flex_col().gap(px(22.)).child(header("Split the storage", split_subtitle(), TITLE)).child(slider); if let Some(snapshot) = snapshot { col = col.child(snapshot); @@ -518,7 +528,7 @@ fn no_room(layout: &Layout, flow: &Flow, seconds: f32, cx: &mut Context, seconds: f32) -> Div { +fn split_steps(lost: bool, action: Option, replaces: bool, finishing: bool, seconds: f32) -> Div { let row = |label: &'static str, state: u8, first: bool| { let (color, weight) = match state { 0 => (c(SUBTITLE), FontWeight::NORMAL), @@ -547,6 +557,13 @@ fn split_steps(lost: bool, grow: Option, seconds: f32) -> Div { } r }; + let resize_label = match action { + Some(SplitAction::Grow) => orchard_flow::for_device("Grow iPadOS"), + Some(SplitAction::Shrink { .. }) | None => orchard_flow::for_device("Shrink iPadOS"), + Some(SplitAction::PartitionOnly) if replaces => "Remove the old partitions", + Some(SplitAction::PartitionOnly) => "Update partitions", + }; + let (resize_state, check_state) = if finishing { (0, 1) } else { (1, 2) }; div() .w_full() .flex() @@ -555,8 +572,8 @@ fn split_steps(lost: bool, grow: Option, seconds: f32) -> Div { .border_1() .border_color(c(PANEL_LINE)) .child(row("Check storage", 0, true)) - .child(row(match grow { Some(true) => orchard_flow::for_device("Grow iPadOS"), Some(false) => orchard_flow::for_device("Shrink iPadOS"), None => "Remove the old partitions" }, 1, false)) - .child(row("Check the result", 2, false)) + .child(row(resize_label, resize_state, false)) + .child(row("Check the result", check_state, false)) } fn minutes(since: Instant) -> u64 { @@ -564,39 +581,72 @@ fn minutes(since: Instant) -> u64 { } /// 2.4 / 2.4b / 2.5: splitting, after a relaunch, or the link lost. -/// `ipados`: iPadOS's size (GB) after and before the split, when known. -fn splitting(link: Link, reopened: bool, ipados: Option<(u32, u32)>, stuck: bool, since: Instant, seconds: f32) -> Div { +#[allow(clippy::too_many_arguments)] +fn splitting(link: Link, reopened: bool, layout: Option<&Layout>, omarchy_gb: u32, split_progress: Option, stuck: bool, since: Instant, seconds: f32) -> Div { let lost = link == Link::Lost; - // Growing into removed partitions is quick; shrinking APFS takes long. - // None: the same size, only the old partitions go. - let grow = match ipados { - Some((after, before)) if after == before => None, - Some((after, before)) => Some(after > before), - None => Some(false), - }; - let progress = div().w_full().flex().flex_col().gap(px(10.)).child(split_steps(lost, grow, seconds)); + let action = layout.map(|l| orchard_flow::split_action(l, omarchy_gb)); + let target_gb = layout.map(|l| l.total_gb.saturating_sub(omarchy_gb)).or_else(|| split_progress.and_then(|p| p.target_ipados_gb)); + let replaces = layout.is_some_and(|l| !l.outside.is_empty()); + let finishing = split_progress.is_some_and(|p| p.is_finishing()); + let progress = div().w_full().flex().flex_col().gap(px(10.)).child(split_steps(lost, action, replaces, finishing, seconds)); if lost { return column() .gap(px(24.)) .child(header(orchard_flow::for_device("Reconnect your iPad"), orchard_flow::for_device("The connection to your iPad was lost. Plug it back in to continue."), RED)) .child(progress); } - let subtitle = if reopened { + let subtitle = if finishing { + orchard_flow::for_device("iPadOS finished shrinking. Checking the storage and updating the partition table…").to_owned() + } else if reopened && split_progress.is_none() { orchard_flow::for_device("The installer was closed while the storage was being split. Checking on your iPad…").to_owned() } else { - match (ipados, grow) { - (Some((gb, _)), Some(true)) => orchard_flow::for_device(&format!("iPadOS is growing to {gb} GB. This takes a moment.")).to_owned(), - (Some((gb, _)), Some(false)) => orchard_flow::for_device(&format!("iPadOS is shrinking to {gb} GB. This can take around 30 minutes.")).to_owned(), - (Some(_), None) => format!("Removing the old {} partitions. This takes a moment.", sys()), - (None, _) => "This can take around 30 minutes.".to_owned(), + let remaining = split_progress.and_then(|p| p.remaining_minutes()); + match (action, target_gb) { + (Some(SplitAction::Grow), Some(gb)) => orchard_flow::for_device(&format!("iPadOS is growing to {gb} GB. This takes a moment.")).to_owned(), + (Some(SplitAction::PartitionOnly), _) if replaces => format!("Removing the old {} partitions. This takes a moment.", sys()), + (Some(SplitAction::PartitionOnly), _) => "Updating the partition table. This takes a moment.".to_owned(), + (Some(SplitAction::Shrink { gb: shrink_gb }), Some(gb)) => { + if let Some(left) = remaining { + orchard_flow::for_device(&format!("iPadOS is shrinking to {gb} GB. {}.", orchard_flow::format_remaining_minutes(left))).to_owned() + } else { + let approx = orchard_flow::format_approx_minutes(orchard_flow::shrink_estimate_minutes(shrink_gb)); + orchard_flow::for_device(&format!("iPadOS is shrinking to {gb} GB. This can take {approx} (~1 min per GB, depending on data layout).")).to_owned() + } + } + (_, Some(gb)) => { + if let Some(left) = remaining { + orchard_flow::for_device(&format!("iPadOS is shrinking to {gb} GB. {}.", orchard_flow::format_remaining_minutes(left))).to_owned() + } else { + orchard_flow::for_device(&format!("iPadOS is shrinking to {gb} GB. Shrinking typically takes around 1 minute per GB, depending on data layout.")).to_owned() + } + } + (_, None) => { + if let Some(left) = remaining { + format!("{}.", orchard_flow::format_remaining_minutes(left)) + } else { + "Shrinking typically takes around 1 minute per GB, depending on data layout.".to_owned() + } + } } }; - // Not designed beyond the example line: only what the window knows. - let status = format!("still working · {} min so far", minutes(since)); - // Only after a minute (fading in), its place kept from the start so - // nothing moves (after a relaunch too). + let elapsed = split_progress.and_then(|p| p.elapsed_secs).map(|s| s / 60).unwrap_or_else(|| minutes(since)); + let status = match split_progress { + Some(p) if p.is_finishing() => format!("finishing up · {elapsed} min"), + Some(p) => { + let done_gb = p.released_bytes as f64 / 1e9; + let total_gb = p.total_bytes as f64 / 1e9; + let pct = p.percent(); + match (p.step, p.planned_steps) { + (Some(step), Some(total)) if total > 0 => format!("{done_gb:.1} / {total_gb:.1} GB ({pct}%) · step {step}/{total} · {elapsed} min"), + _ => format!("{done_gb:.1} / {total_gb:.1} GB ({pct}%) · {elapsed} min"), + } + } + None => format!("still working · {elapsed} min so far"), + }; + // Visible immediately once live progress arrives; otherwise fades in after + // a minute, its place kept from the start so nothing moves. let after = since.elapsed().as_secs_f32(); - let visible = ((after - 60.) / 0.4).clamp(0., 1.); + let visible = if split_progress.is_some() { 1. } else { ((after - 60.) / 0.4).clamp(0., 1.) }; let liveness = div() .opacity(visible) .flex() @@ -1381,10 +1431,10 @@ pub fn text_column(installer: &mut Installer, cx: &mut Context) -> Op choose_split(layout, shown, *approved, &flow, stuck, seconds, &focus, ring, cx).into_any_element() } } - State::Splitting { link, reopened, omarchy_gb, .. } => { - let ipados = installer.layout.as_ref().map(|l| (l.total_gb - omarchy_gb, l.ipados_gb)); + State::Splitting { link, reopened, omarchy_gb, progress, .. } => { + let layout = installer.layout.clone(); let seconds = installer.started.elapsed().as_secs_f32(); - splitting(*link, *reopened, ipados, installer.link_stuck(), installer.since, seconds).into_any_element() + splitting(*link, *reopened, layout.as_ref(), *omarchy_gb, *progress, installer.link_stuck(), installer.since, seconds).into_any_element() } State::SplitDone { omarchy_gb, .. } => { let layout = installer.layout.clone(); diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 5463c05c..a8c48c16 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -566,7 +566,16 @@ impl Installer { shown.device = device; } if shown.content != content { - self.since = now; + let same_work = matches!( + (shown.content, content), + (ScreenKind::Splitting | ScreenKind::SplittingReopened, ScreenKind::Reconnect) + | (ScreenKind::Reconnect, ScreenKind::Splitting | ScreenKind::SplittingReopened) + | (ScreenKind::Installing, ScreenKind::Reconnect) + | (ScreenKind::Reconnect, ScreenKind::Installing) + ); + if !same_work { + self.since = now; + } self.refocus = true; // A new screen closes the trouble dialog; focus starts afresh. self.trouble = false; diff --git a/crates/cli/src/commands/install.rs b/crates/cli/src/commands/install.rs index aa5d3b25..72c2a8a4 100644 --- a/crates/cli/src/commands/install.rs +++ b/crates/cli/src/commands/install.rs @@ -8,7 +8,7 @@ use crate::args::Global; use super::term::{bar, gradient, s, KeyReader, Span, Term, Typed, BLUE, FG, GREEN, MUTED, RED, SUB, TITLE, TRACK, YELLOW}; use orchard_flow::recovery::{self, Phase, Run}; -use orchard_flow::{Again, App, Event, Flow, Layout, Link, Sequence, State, UsbMode, MIN_OMARCHY_GB}; +use orchard_flow::{Again, App, Event, Flow, Layout, Link, Sequence, SplitAction, SplitProgress, State, UsbMode, MIN_OMARCHY_GB}; use orchard_runtime::disk_file::{Clash, DiskFile}; use orchard_runtime::driver::{self, Observer, Options}; use orchard_runtime::release::{Platform, Receipt}; @@ -575,6 +575,90 @@ fn after_row(out: &mut Out, layout: &Layout, gb: u32, name: &str) { after.extend(layout_bar(layout, ipados, Some(gb), 40)); after.push(s(orchard_flow::for_device(&format!(" iPadOS {ipados} GB · {name} {gb} GB")).to_owned(), MUTED)); out.term.line(after); + if let SplitAction::Shrink { gb: shrink_gb } = orchard_flow::split_action(layout, gb) { + let approx = orchard_flow::format_approx_minutes(orchard_flow::shrink_estimate_minutes(shrink_gb)); + out.muted(orchard_flow::for_device(&format!("Shrinking iPadOS by {shrink_gb} GB typically takes {approx} (~1 min per GB, depending on data layout).")).to_owned()); + } +} + +fn split_heading_sub(action: Option, target_ipados: Option, replaces: bool, name: &str) -> String { + match (action, target_ipados) { + (Some(SplitAction::Grow), Some(ipados)) => orchard_flow::for_device(&format!("iPadOS is growing to {ipados} GB. This takes a moment.")).to_owned(), + (Some(SplitAction::PartitionOnly), _) if replaces => format!("Removing the old {name} partitions. This takes a moment."), + (Some(SplitAction::PartitionOnly), _) => "Updating the partition table. This takes a moment.".to_owned(), + (Some(SplitAction::Shrink { gb }), Some(ipados)) => { + let approx = orchard_flow::format_approx_minutes(orchard_flow::shrink_estimate_minutes(gb)); + orchard_flow::for_device(&format!("iPadOS is shrinking to {ipados} GB. This can take {approx} (~1 min per GB, depending on data layout).")).to_owned() + } + (_, Some(ipados)) => orchard_flow::for_device(&format!("iPadOS is shrinking to {ipados} GB. Shrinking typically takes around 1 minute per GB, depending on data layout.")).to_owned(), + (_, None) => "Shrinking typically takes around 1 minute per GB, depending on data layout.".to_owned(), + } +} + +fn split_step_label(action: Option, replaces: bool) -> &'static str { + match action { + Some(SplitAction::Grow) => orchard_flow::for_device("Grow iPadOS"), + Some(SplitAction::PartitionOnly) if replaces => "Remove old partitions", + Some(SplitAction::PartitionOnly) => "Update partitions", + Some(SplitAction::Shrink { .. }) | None => orchard_flow::for_device("Shrink iPadOS"), + } +} + +/// Compact live TTY status line for a running split, kept within 80 columns +/// including `Term::draw_live`'s spinner prefix and elapsed-time suffix. +fn split_live_spans(action: Option, replaces: bool, progress: Option, name: &str, omarchy_gb: u32) -> Vec { + match progress { + Some(p) if p.is_finishing() => vec![s("Check the result", FG), s(" 100% · finishing up", MUTED)], + Some(p) => { + let done_gb = p.released_bytes as f64 / 1e9; + let total_gb = p.total_bytes as f64 / 1e9; + let pct = p.percent(); + let mut detail = format!(" {done_gb:.1}/{total_gb:.1} GB ({pct}%)"); + if let (Some(step), Some(total)) = (p.step, p.planned_steps) { + if total > 0 { + detail.push_str(&format!(" · {step}/{total}")); + } + } + if let Some(left) = p.remaining_minutes() { + detail.push_str(&format!(" · {}", orchard_flow::format_remaining_compact(left))); + } + vec![s(split_step_label(action, replaces), FG), s(detail, MUTED)] + } + None => vec![s(split_step_label(action, replaces), FG), s(format!(" {name} gets {omarchy_gb} GB"), MUTED)], + } +} + +/// Permanent progress line for non-TTY output (emitted on first progress, +/// every 5% thereafter, and once when entering the finishing stage). +fn split_non_tty_milestone(progress: SplitProgress, last_pct: &mut Option, finishing_said: &mut bool) -> Option { + if progress.is_finishing() { + if *finishing_said { + return None; + } + *finishing_said = true; + return Some("Shrink reached 100%; checking the storage and updating the partition table…".to_owned()); + } + let pct = progress.percent(); + let emit = match *last_pct { + None => progress.released_bytes > 0 || pct >= 5, + Some(prev) => pct >= prev.saturating_add(5), + }; + if !emit { + return None; + } + *last_pct = Some(pct); + let done_gb = progress.released_bytes as f64 / 1e9; + let total_gb = progress.total_bytes as f64 / 1e9; + let mut line = format!("Shrink progress: {done_gb:.1} / {total_gb:.1} GB ({pct}%)"); + if let (Some(step), Some(total)) = (progress.step, progress.planned_steps) { + if total > 0 { + line.push_str(&format!(" · step {step}/{total}")); + } + } + if let Some(left) = progress.remaining_minutes() { + line.push_str(&format!(" · {}", orchard_flow::format_remaining_minutes(left))); + } + Some(line) } /// The red list of what gets erased, and the consent. @@ -1531,6 +1615,10 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { let mut account_sent = false; let mut account_continued = false; let mut split_layout: Option<(Layout, u32)> = None; + let mut split_progress_said: Option = None; + let mut split_milestone_pct: Option = None; + let mut split_finishing_said = false; + let mut split_target_ipados: Option = None; let mut installed_at: Option = None; // Since when the system is written, for its speed, and the download // the write waits for, as said last. @@ -1891,6 +1979,18 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } split_done = false; } + // A split that this run started or adopted was refused: show + // the iPad's reason and exit instead of hanging on ChooseSplit. + if split_done { + if let Some(problem) = flow.split_problem.as_deref() { + out.term.live(None); + out.fail(orchard_flow::for_device("Your iPad didn't split the storage")); + out.para(problem); + send(Event::Quit); + std::thread::sleep(Duration::from_secs(1)); + return finish(&mut out, Exit::Failed, "split-refused", problem); + } + } if !split_done { split_done = true; out.term.live(None); @@ -1980,21 +2080,48 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } } } - State::Splitting { omarchy_gb, link, .. } => { + State::Splitting { omarchy_gb, link, progress, .. } => { + let action = split_layout.as_ref().map(|(l, gb)| orchard_flow::split_action(l, *gb)); + let replaces = split_layout.as_ref().is_some_and(|(l, _)| !l.outside.is_empty()); + if let Some(gb) = progress.and_then(|p| p.target_ipados_gb) { + split_target_ipados = Some(gb); + } + let target_ipados = split_layout.as_ref().map(|(l, gb)| l.total_gb.saturating_sub(*gb)).or(split_target_ipados); if first { - let (grow, ipados) = match &split_layout { - Some((l, gb)) => (l.total_gb.saturating_sub(*gb) > l.ipados_gb, l.total_gb.saturating_sub(*gb)), - None => (false, 0), - }; + split_done = true; + split_progress_said = None; + split_milestone_pct = None; + split_finishing_said = false; out.term.blank(); out.heading("Splitting the storage", None); - out.sub(if grow { orchard_flow::for_device(&format!("iPadOS is growing to {ipados} GB. This takes a moment.")).to_owned() } else { orchard_flow::for_device(&format!("iPadOS is shrinking to {ipados} GB. This can take around 30 minutes.")).to_owned() }); + out.sub(split_heading_sub(action, target_ipados, replaces, &name)); out.term.blank(); out.warn(orchard_flow::for_device("Keep your iPad connected and leave it alone.")); out.sub("It may freeze or look idle for a long time. That doesn't mean it's finished or failed."); out.term.blank(); out.term.line(vec![s(" ✓ ", GREEN), s("Check storage", MUTED)]); - out.term.live_restart(vec![s(if grow { orchard_flow::for_device("Grow iPadOS") } else { orchard_flow::for_device("Shrink iPadOS") }, FG), s(format!(" {name} gets {omarchy_gb} GB"), MUTED)]); + out.term.live_restart(split_live_spans(action, replaces, *progress, &name, *omarchy_gb)); + } + if let Some(p) = *progress { + if split_progress_said != Some(p) { + split_progress_said = Some(p); + out.event(json!({ + "event": "split-progress", + "released_bytes": p.released_bytes, + "total_bytes": p.total_bytes, + "percent": p.percent(), + "step": p.step, + "planned_steps": p.planned_steps, + "finishing": p.is_finishing(), + "remaining_minutes": p.remaining_minutes(), + })); + out.term.live(Some(split_live_spans(action, replaces, Some(p), &name, *omarchy_gb))); + if !out.term.tty { + if let Some(line) = split_non_tty_milestone(p, &mut split_milestone_pct, &mut split_finishing_said) { + out.sub(line); + } + } + } } if matches!(link, Link::Lost) && !lost_said { lost_said = true; @@ -2009,9 +2136,13 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { out.term.live(None); out.term.line(vec![s(" ✓ ", GREEN), s(orchard_flow::for_device("Resize iPadOS"), MUTED), s(format!(" {}:{:02}", took / 60, took % 60), MUTED)]); out.term.line(vec![s(" ✓ ", GREEN), s("Check the result", MUTED)]); - let ipados = split_layout.as_ref().map(|(l, _)| l.total_gb.saturating_sub(*omarchy_gb)).unwrap_or(0); + let ipados = split_layout.as_ref().map(|(l, _)| l.total_gb.saturating_sub(*omarchy_gb)).or(split_target_ipados); out.term.blank(); - out.ok_note("The storage is split", orchard_flow::for_device(&format!("iPadOS {ipados} GB · {name} {omarchy_gb} GB")).to_owned()); + let note = match ipados { + Some(gb) => orchard_flow::for_device(&format!("iPadOS {gb} GB · {name} {omarchy_gb} GB")).to_owned(), + None => format!("{name} {omarchy_gb} GB"), + }; + out.ok_note("The storage is split", note); send(Event::Continue); } } @@ -2803,7 +2934,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_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] { @@ -2949,9 +3080,72 @@ mod tests { #[test] fn the_layout_bars_fill_their_width() { - 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 layout = Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: vec![], outside_bytes: 0, splittable_bytes: 0, ipados_container_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); } + + #[test] + fn split_live_line_fits_within_80_columns_and_handles_finishing() { + orchard_flow::set_device_model(orchard_flow::Model::IpadHome); + let p = SplitProgress { + released_bytes: 256_000_000_000, + total_bytes: 256_100_000_000, + target_ipados_gb: Some(131), + step: Some(999), + planned_steps: Some(999), + stage: orchard_flow::SplitStage::Shrinking, + rate_elapsed_secs: Some(3_600), + rate_released_bytes: Some(25_600_000_000), + elapsed_secs: Some(3_600), + }; + let spans = split_live_spans(Some(SplitAction::Shrink { gb: 256 }), false, Some(p), "Omarchy A", 256); + let text = plain(&spans); + // Term::draw_live adds 2 columns for spinner ("⠋ ") and 8 for " 999:59". + assert!(2 + text.chars().count() + 8 <= 80, "live line too wide for 80 cols: {text:?} ({} cols)", 2 + text.chars().count() + 8); + assert!(text.contains("256.0/256.1 GB") && text.contains("999/999"), "{text}"); + + // Finishing stage switches to checking copy instead of flashing an estimate. + let fin = SplitProgress { stage: orchard_flow::SplitStage::Finishing, ..p }; + let fin_text = plain(&split_live_spans(Some(SplitAction::Shrink { gb: 256 }), false, Some(fin), "Omarchy A", 256)); + assert!(fin_text.contains("Check the result") && fin_text.contains("finishing up"), "{fin_text}"); + } + + #[test] + fn split_heading_never_prints_zero_gb_on_resume() { + orchard_flow::set_device_model(orchard_flow::Model::IpadHome); + let unknown = split_heading_sub(None, None, false, "Omarchy A"); + assert!(!unknown.contains("0 GB"), "{unknown}"); + let with_target = split_heading_sub(None, Some(131), false, "Omarchy A"); + assert!(with_target.contains("131 GB") && !with_target.contains("0 GB"), "{with_target}"); + let part_only = split_heading_sub(Some(SplitAction::PartitionOnly), Some(80), false, "Omarchy A"); + assert!(part_only.contains("partition table"), "{part_only}"); + } + + #[test] + fn split_non_tty_milestones_emit_at_start_every_5_percent_and_finishing() { + let mut last_pct = None; + let mut finishing_said = false; + let mk = |pct_gb: u64, stage| SplitProgress { + released_bytes: pct_gb * 1_000_000_000, + total_bytes: 100_000_000_000, + target_ipados_gb: Some(156), + step: Some(pct_gb as u32), + planned_steps: Some(100), + stage, + rate_elapsed_secs: Some(600), + rate_released_bytes: Some(10_000_000_000), + elapsed_secs: Some(600), + }; + assert!(split_non_tty_milestone(mk(0, orchard_flow::SplitStage::Shrinking), &mut last_pct, &mut finishing_said).is_none()); + let first = split_non_tty_milestone(mk(2, orchard_flow::SplitStage::Shrinking), &mut last_pct, &mut finishing_said); + assert!(first.as_deref().is_some_and(|s| s.contains("(2%)")), "{first:?}"); + assert!(split_non_tty_milestone(mk(6, orchard_flow::SplitStage::Shrinking), &mut last_pct, &mut finishing_said).is_none()); + let next = split_non_tty_milestone(mk(7, orchard_flow::SplitStage::Shrinking), &mut last_pct, &mut finishing_said); + assert!(next.as_deref().is_some_and(|s| s.contains("(7%)")), "{next:?}"); + let fin = split_non_tty_milestone(mk(100, orchard_flow::SplitStage::Finishing), &mut last_pct, &mut finishing_said); + assert!(fin.as_deref().is_some_and(|s| s.contains("100%")), "{fin:?}"); + assert!(split_non_tty_milestone(mk(100, orchard_flow::SplitStage::Finishing), &mut last_pct, &mut finishing_said).is_none()); + } } diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index b30fa70d..a25cc91c 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -202,6 +202,12 @@ pub struct Layout { /// The bytes after iPadOS, where they were read off the disk; 0 where /// only whole GB are known. pub outside_bytes: u64, + /// Total splittable bytes (from APFS start to the end of usable disk), + /// where read off the disk; 0 where only whole GB are known. + pub splittable_bytes: u64, + /// Current APFS container size in bytes (may be smaller than the backing + /// partition after an interrupted shrink); 0 where only whole GB are known. + pub ipados_container_bytes: u64, } impl Layout { @@ -338,6 +344,192 @@ pub fn no_room_hint(layout: &Layout) -> Option { /// Space iPadOS keeps free on top of what it uses. pub const HEADROOM_GB: u32 = 2; +/// Rough rule of thumb for APFS shrink time: about 1 minute per GB shrunk +/// (actual time varies with how much allocated data sits past the new boundary +/// and storage speed). +pub const SHRINK_MINUTES_PER_GB: u32 = 1; + +/// What a chosen split size will actually do to the APFS container. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SplitAction { + /// Shrink APFS by roughly `gb` GB (rounded once from exact bytes). + Shrink { gb: u32 }, + /// Grow APFS into adjacent space. + Grow, + /// APFS container is already at the target size; only partition table / + /// trailing partitions change. + PartitionOnly, +} + +/// Which stage of a split operation the helper is currently in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SplitStage { + /// Relocating APFS blocks in steps toward the target container size. + Shrinking, + /// APFS reached its target size; verifying metadata and updating GPT. + Finishing, +} + +/// Observed progress of a stepwise APFS shrink, reported by the companion +/// helper from `Operation.observedCapacityBytes`, `Operation.apfsStep`, and +/// operation timestamps. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SplitProgress { + /// Container bytes released so far (0 before the first step completes). + pub released_bytes: u64, + /// Total container bytes the split is shrinking away. + pub total_bytes: u64, + /// Target iPadOS container size in rounded decimal GB, when known. + pub target_ipados_gb: Option, + /// 1-based shrink step currently running, when reported. + pub step: Option, + /// Total steps currently estimated, when reported. + pub planned_steps: Option, + /// Stage of the operation (shrinking APFS vs verifying / updating GPT). + pub stage: SplitStage, + /// Elapsed seconds paired with `rate_released_bytes` (from helper + /// `observedAt - startedAt`, or delta seconds since this process's first + /// sample when helper timestamps are absent). + pub rate_elapsed_secs: Option, + /// Bytes released over `rate_elapsed_secs`. + pub rate_released_bytes: Option, + /// Total seconds elapsed since the helper started the operation, when known. + pub elapsed_secs: Option, +} + +impl SplitProgress { + /// Percentage of the planned shrink released so far, rounded down so it + /// reaches 100 only once all planned bytes are released. + pub fn percent(&self) -> u8 { + if self.total_bytes == 0 { + return 0; + } + let released = u128::from(self.released_bytes.min(self.total_bytes)); + let total = u128::from(self.total_bytes); + (released * 100 / total) as u8 + } + + /// True once APFS has reached its target size and the helper is verifying + /// or updating the partition table. + pub fn is_finishing(&self) -> bool { + self.stage == SplitStage::Finishing || (self.total_bytes > 0 && self.released_bytes >= self.total_bytes) + } + + /// Estimated remaining minutes from paired `(rate_released_bytes, + /// rate_elapsed_secs)`, once at least 30 seconds have elapsed with bytes + /// released and shrinking is still under way. + pub fn remaining_minutes(&self) -> Option { + if self.is_finishing() || self.total_bytes == 0 { + return None; + } + let rate_released = self.rate_released_bytes?; + let rate_elapsed = self.rate_elapsed_secs?; + if rate_released == 0 || rate_elapsed < 30 { + return None; + } + let remaining = self.total_bytes.saturating_sub(self.released_bytes) as f64; + if remaining <= 0.0 { + return None; + } + let mins = (rate_elapsed as f64 * remaining / rate_released as f64 / 60.0).ceil().max(1.0); + Some(mins.min(f64::from(u32::MAX)) as u32) + } +} + +/// Classifies what choosing `omarchy_gb` will do to APFS, using exact +/// container bytes when available so an interrupted shrink (where the APFS +/// container is already smaller than its backing partition) is not misread as +/// a shrink when APFS actually needs to grow or stay the same size. +pub fn split_action(layout: &Layout, omarchy_gb: u32) -> SplitAction { + // Tolerance for sector/MiB rounding when comparing container to target. + const TOLERANCE_BYTES: u64 = 1 << 20; + if layout.splittable_bytes > 0 && layout.ipados_container_bytes > 0 { + let target = layout.splittable_bytes.saturating_sub(u64::from(omarchy_gb) * 1_000_000_000); + if layout.ipados_container_bytes > target.saturating_add(TOLERANCE_BYTES) { + let diff = layout.ipados_container_bytes - target; + let gb = ((diff as f64) / 1e9).round().max(1.0) as u32; + SplitAction::Shrink { gb } + } else if target > layout.ipados_container_bytes.saturating_add(TOLERANCE_BYTES) { + SplitAction::Grow + } else { + SplitAction::PartitionOnly + } + } else { + let target_ipados = layout.total_gb.saturating_sub(omarchy_gb); + if layout.ipados_gb > target_ipados { + SplitAction::Shrink { gb: layout.ipados_gb - target_ipados } + } else if target_ipados > layout.ipados_gb { + SplitAction::Grow + } else { + SplitAction::PartitionOnly + } + } +} + +/// How many GB APFS shrinks by to leave `omarchy_gb` for the Linux system +/// (0 when growing or keeping the same APFS container size). +pub fn shrink_gb_for(layout: &Layout, omarchy_gb: u32) -> u32 { + match split_action(layout, omarchy_gb) { + SplitAction::Shrink { gb } => gb, + SplitAction::Grow | SplitAction::PartitionOnly => 0, + } +} + +/// Rough upfront shrink duration in minutes (~1 min per GB shrunk). +pub fn shrink_estimate_minutes(shrink_gb: u32) -> u32 { + shrink_gb.saturating_mul(SHRINK_MINUTES_PER_GB) +} + +fn format_hours_minutes(minutes: u32) -> String { + if minutes <= 1 { + return "1 minute".into(); + } + if minutes < 60 { + return format!("{minutes} minutes"); + } + // Round to the nearest 10 minutes above an hour (in u64 to avoid overflow). + let rounded = (u64::from(minutes) + 5) / 10 * 10; + let hours = rounded / 60; + let rem = rounded % 60; + let h = if hours == 1 { "1 hour".to_owned() } else { format!("{hours} hours") }; + if rem == 0 { + h + } else { + format!("{h} {rem} minutes") + } +} + +/// Human-readable rough upfront estimate, e.g. `"around 25 minutes"` or `"around 2 hours"`. +pub fn format_approx_minutes(minutes: u32) -> String { + if minutes <= 1 { + "around a minute".into() + } else { + format!("around {}", format_hours_minutes(minutes)) + } +} + +/// Human-readable live remaining-time line, e.g. `"About 45 minutes left"` or `"About 1 hour 20 minutes left"`. +pub fn format_remaining_minutes(minutes: u32) -> String { + format!("About {} left", format_hours_minutes(minutes)) +} + +/// Compact ETA for single-line 80-column terminal progress, e.g. `"~45m left"` or `"~1h 20m left"`. +pub fn format_remaining_compact(minutes: u32) -> String { + if minutes <= 1 { + return "~1m left".into(); + } + if minutes < 60 { + return format!("~{minutes}m left"); + } + let rounded = (u64::from(minutes) + 5) / 10 * 10; + let hours = rounded / 60; + let rem = rounded % 60; + if rem == 0 { + format!("~{hours}h left") + } else { + format!("~{hours}h {rem}m left") + } +} /// The least the install system takes, until the release states its unpacked /// size: orchard's install layout needs an 8 GiB root and a 1 GiB boot /// partition (9.7 GB). @@ -444,7 +636,7 @@ pub enum State { HelperSteps { device: Device }, WaitingForIpados { device: Device, slow: bool }, ChooseSplit { device: Device, layout: Layout, omarchy_gb: u32, approved: bool }, - Splitting { device: Device, omarchy_gb: u32, link: Link, reopened: bool }, + Splitting { device: Device, omarchy_gb: u32, link: Link, reopened: bool, progress: Option }, SplitDone { device: Device, omarchy_gb: u32 }, // A round into DFU mode /// `seen`: the mode the device was last seen in. `recovery`: it is in @@ -558,6 +750,8 @@ pub enum Event { CompanionLost, /// It is back. CompanionBack, + /// Observed APFS shrink progress from the companion's snapshot. + SplitProgress(SplitProgress), SplitFinished { ok: bool }, /// The companion refused the split or it stopped, with the reason: as /// a failed split, and the reason shows on the split screen. @@ -1343,6 +1537,9 @@ fn step_inner(app: App, mut flow: Flow, event: Event) -> (Flow, Vec) { flow.companion = true; flow.removing_snapshot = false; } + if matches!(event, Event::SplitRunning { .. } | Event::SplitProgress(_)) { + flow.companion = true; + } let fresh_layout = matches!(event, Event::IpadosReady { .. }); // 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 { .. }) { @@ -1715,7 +1912,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 }), erase_approved: true, slow: false, }, @@ -1801,25 +1998,28 @@ fn update_plain(app: App, ctx: &Ctx, state: State, event: Event) -> (State, Vec< (S::ChooseSplit { device, layout, omarchy_gb, approved: true }, E::Continue) if omarchy_gb >= MIN_OMARCHY_GB && omarchy_gb <= layout.max_omarchy_gb() => { - (S::Splitting { device, omarchy_gb, link: Link::Up, reopened: false }, vec![Effect::StartSplit { omarchy_gb }]) + (S::Splitting { device, omarchy_gb, link: Link::Up, reopened: false, progress: None }, vec![Effect::StartSplit { omarchy_gb }]) } (S::ChooseSplit { device, .. }, E::IpadosReady { layout }) => { // "Check again" after the user freed up space. let omarchy_gb = suggested_size(&layout); (S::ChooseSplit { device, layout, omarchy_gb, approved: false }, none()) } - (S::Splitting { device, omarchy_gb, reopened, .. }, E::Detached { id }) if device.id == id => { - (S::Splitting { device, omarchy_gb, link: Link::Lost, reopened }, none()) + (S::Splitting { device, omarchy_gb, reopened, progress, .. }, E::Detached { id }) if device.id == id => { + (S::Splitting { device, omarchy_gb, link: Link::Lost, reopened, progress }, none()) } - (S::Splitting { device: d, omarchy_gb, reopened, .. }, E::Attached { device, mode }) if d.id == device.id => { + (S::Splitting { device: d, omarchy_gb, reopened, progress, .. }, E::Attached { device, mode }) if d.id == device.id => { let device = carried(&d, device); match mode { // Still running iPadOS: re-attach, never restart the chain. - UsbMode::Normal => (S::Splitting { device, omarchy_gb, link: Link::Up, reopened }, none()), + UsbMode::Normal => (S::Splitting { device, omarchy_gb, link: Link::Up, reopened, progress }, none()), // It reset: the result is unknown until the installer looks. _ => (dfu_round(device, Again::CheckSplit, Some(mode)), none()), } } + (S::Splitting { device, omarchy_gb, reopened, .. }, E::SplitProgress(progress)) => { + (S::Splitting { device, omarchy_gb, link: Link::Up, reopened, progress: Some(progress) }, none()) + } (S::Splitting { device, omarchy_gb, .. }, E::SplitFinished { ok: true }) => { let mut effects = vec![Effect::Notify("The storage is split.".into())]; // checkra1n's helper app is on the device for the session only. @@ -1839,7 +2039,7 @@ fn update_plain(app: App, ctx: &Ctx, state: State, event: Event) -> (State, Vec< (S::WaitPwned { device, why: Again::Install, failed: 0, left: false, restarting: true }, vec![Effect::RestartIpad]) } (S::SplitDone { device, .. }, E::Continue) => to_dfu(device, Again::Install, ctx.at), - (_, E::SplitRunning { device, omarchy_gb }) => (S::Splitting { device, omarchy_gb, link: Link::Lost, reopened: true }, none()), + (_, E::SplitRunning { device, omarchy_gb }) => (S::Splitting { device, omarchy_gb, link: Link::Up, reopened: true, progress: None }, none()), // ---- A round into DFU mode ---- // Dopamine chosen in its Options (palera1n's start didn't work, say): diff --git a/crates/flow/src/tests.rs b/crates/flow/src/tests.rs index bdb8e8fa..ea086bab 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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 } } fn split_before() -> Layout { @@ -80,6 +80,8 @@ fn split_before() -> Layout { Partition { name: "omarchy-a".into(), filesystem: "ext4".into(), gb: 63 }, ], outside_bytes: 0, + splittable_bytes: 0, + ipados_container_bytes: 0, } } @@ -583,10 +585,10 @@ fn a_version_dopamine_does_not_take_is_caught_once_ios_tells_it() { #[test] fn checkra1ns_helper_app_is_taken_off_after_the_split() { let app = App::Installer; - let splitting = State::Splitting { device: on(ipad6(), "14.8"), omarchy_gb: 64, link: Link::Up, reopened: false }; + let splitting = State::Splitting { device: on(ipad6(), "14.8"), omarchy_gb: 64, link: Link::Up, reopened: false, progress: None }; let (_, e) = update(app, splitting, Event::SplitFinished { ok: true }); assert!(e.contains(&Effect::RemoveHelper(ipad6().id)), "{e:?}"); - let splitting = State::Splitting { device: on(ipad6(), "16.5"), omarchy_gb: 64, link: Link::Up, reopened: false }; + let splitting = State::Splitting { device: on(ipad6(), "16.5"), omarchy_gb: 64, link: Link::Up, reopened: false, progress: None }; let (_, e) = update(app, splitting, Event::SplitFinished { ok: true }); assert!(!e.iter().any(|e| matches!(e, Effect::RemoveHelper(_))), "{e:?}"); } @@ -774,7 +776,7 @@ fn create_account() -> State { } fn installed_layout() -> Layout { - Layout { total_gb: 128, ipados_gb: 96, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 } } #[test] @@ -1309,7 +1311,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_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 @@ -1319,7 +1321,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 }; let (flow, _) = step(App::Installer, with_install_system(), Event::EnvReady { layout: small }); assert!(matches!(flow.state, State::NotPrepared { .. })); } @@ -1391,7 +1393,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 } } #[test] @@ -1604,7 +1606,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 }; // 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()); @@ -1612,7 +1614,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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_bytes: 0 }; assert!(!small.has_room()); } @@ -1827,6 +1829,8 @@ fn snapshot_layout(removable: bool) -> Layout { 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, + splittable_bytes: 0, + ipados_container_bytes: 0, } } @@ -1837,7 +1841,7 @@ fn a_held_floor_limits_the_split_not_the_used_space() { assert_eq!(l.max_omarchy_gb_without_snapshot(), Some(17)); assert_eq!(snapshot_layout(false).max_omarchy_gb_without_snapshot(), Some(17), "after the restart without it"); // 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 }; + let roomy = Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 20, ipados_floor_gb: 60, snapshot: None, outside: vec![], outside_bytes: 0, splittable_bytes: 0, ipados_container_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); } @@ -1880,7 +1884,7 @@ fn a_refused_removal_says_why_in_the_box_and_a_running_snapshot_is_not_removed_d #[test] fn the_offer_does_not_depend_on_the_room() { // Room enough as it is: the snapshot is still offered. - let roomy = Layout { total_gb: 64, ipados_gb: 64, ipados_used_gb: 20, ipados_floor_gb: 39, snapshot: Some(HeldSnapshot { name: "u".into(), held_gb: Some(19), removable: true, runs_from: false, floor_after_gb: Some(20) }), outside: vec![], outside_bytes: 0 }; + let roomy = Layout { total_gb: 64, ipados_gb: 64, ipados_used_gb: 20, ipados_floor_gb: 39, snapshot: Some(HeldSnapshot { name: "u".into(), held_gb: Some(19), removable: true, runs_from: false, floor_after_gb: Some(20) }), outside: vec![], outside_bytes: 0, splittable_bytes: 0, ipados_container_bytes: 0 }; assert_eq!(roomy.max_omarchy_gb(), 23); assert_eq!(roomy.snapshot_offer().map(|(_, o)| o), Some(SnapshotOffer::Remove)); assert_eq!(roomy.max_omarchy_gb_without_snapshot(), Some(42)); @@ -1993,3 +1997,141 @@ fn the_window_asks_before_removing() { assert_eq!(e.len(), 1); assert!(!flow.confirming_snapshot && flow.removing_snapshot); } + +#[test] +fn adopting_a_running_split_marks_link_up_and_handles_progress_and_refusal() { + let progress = SplitProgress { + released_bytes: 17_800_000_000, + total_bytes: 125_000_000_000, + target_ipados_gb: Some(131), + step: Some(35), + planned_steps: Some(487), + stage: SplitStage::Shrinking, + rate_elapsed_secs: Some(900), + rate_released_bytes: Some(17_800_000_000), + elapsed_secs: Some(900), + }; + // Exact event sequence emitted by the companion watcher on reopen: + // SplitRunning immediately followed by SplitProgress, with no second USB + // Attached event. + let (flow, _) = steps( + App::Installer, + vec![ + Event::Started, + Event::Attached { device: ipad6(), mode: UsbMode::Normal }, + Event::SplitRunning { device: ipad6(), omarchy_gb: 125 }, + Event::SplitProgress(progress), + ], + ); + assert!(flow.companion, "helper is answering when adopting a running split"); + assert_eq!(kind(App::Installer, &flow.state), ScreenKind::SplittingReopened); + assert!( + matches!(flow.state, State::Splitting { link: Link::Up, reopened: true, progress: Some(p), .. } if p == progress), + "adopted split must stay connected and keep progress: {:?}", + flow.state + ); + // A refusal while connected must return to WaitingForIpados (not DFU) so + // the fresh IpadosReady shows the problem on ChooseSplit. + let (flow, effects) = step(App::Installer, flow, Event::SplitRefused("stopped".into())); + assert!(effects.is_empty()); + assert!(matches!(flow.state, State::WaitingForIpados { .. }), "got {:?}", flow.state); + assert_eq!(flow.split_problem.as_deref(), Some("stopped")); + // If the cable really disconnects during an adopted split, the screen + // switches to Reconnect until USB or progress comes back. + let (flow, _) = steps( + App::Installer, + vec![ + Event::Started, + Event::SplitRunning { device: ipad6(), omarchy_gb: 32 }, + Event::Detached { id: ipad6().id }, + ], + ); + assert_eq!(kind(App::Installer, &flow.state), ScreenKind::Reconnect); + let (flow, _) = step(App::Installer, flow, Event::SplitProgress(progress)); + assert_eq!(kind(App::Installer, &flow.state), ScreenKind::SplittingReopened); + assert!(flow.companion); +} + +#[test] +fn split_action_and_estimates_handle_shrink_grow_and_interrupted_container() { + // Fresh 128 GB iPadOS shrinking to leave 64 GB for Omarchy -> shrink 64 GB. + assert_eq!(split_action(&fresh(), 64), SplitAction::Shrink { gb: 64 }); + assert_eq!(shrink_gb_for(&fresh(), 64), 64); + assert_eq!(shrink_estimate_minutes(64), 64); + + // Already split (64 GB iPadOS): growing iPadOS to 96 GB (32 GB Omarchy) + // is Grow; keeping 64 GB iPadOS (64 GB Omarchy) is PartitionOnly. + assert_eq!(split_action(&split_before(), 32), SplitAction::Grow); + assert_eq!(split_action(&split_before(), 64), SplitAction::PartitionOnly); + assert_eq!(split_action(&split_before(), 80), SplitAction::Shrink { gb: 16 }); + + // Interrupted shrink: backing partition is still 128 GB, but the APFS + // container inside it is already 80 GB. + let interrupted = Layout { + total_gb: 128, + ipados_gb: 128, + ipados_used_gb: 41, + ipados_floor_gb: 0, + snapshot: None, + outside: vec![], + outside_bytes: 0, + splittable_bytes: 128 * 1_000_000_000, + ipados_container_bytes: 80 * 1_000_000_000, + }; + assert_eq!(split_action(&interrupted, 32), SplitAction::Grow, "target 96 GB > 80 GB container"); + assert_eq!(split_action(&interrupted, 48), SplitAction::PartitionOnly, "target 80 GB == 80 GB container"); + assert_eq!(split_action(&interrupted, 64), SplitAction::Shrink { gb: 16 }, "target 64 GB < 80 GB container"); +} + +#[test] +fn split_progress_percent_eta_finishing_and_overflow_bounds() { + let p = SplitProgress { + released_bytes: 25_000_000_000, + total_bytes: 100_000_000_000, + target_ipados_gb: Some(156), + step: Some(10), + planned_steps: Some(40), + stage: SplitStage::Shrinking, + rate_elapsed_secs: Some(1_500), // 25 min + rate_released_bytes: Some(25_000_000_000), + elapsed_secs: Some(1_500), + }; + assert_eq!(p.percent(), 25); + assert!(!p.is_finishing()); + assert_eq!(p.remaining_minutes(), Some(75)); + + // Reopened split using a delta baseline: 50 GB already released before + // reopen, 5 GB released in 300 s since reopen -> 50 GB left at 1 GB/min = 50 min. + let reopened = SplitProgress { + released_bytes: 50_000_000_000, + total_bytes: 100_000_000_000, + rate_elapsed_secs: Some(300), + rate_released_bytes: Some(5_000_000_000), + elapsed_secs: None, + ..p + }; + assert_eq!(reopened.remaining_minutes(), Some(50)); + + // At 100% or in Finishing stage: is_finishing() is true and no ETA. + let at_end = SplitProgress { released_bytes: 100_000_000_000, ..p }; + assert_eq!(at_end.percent(), 100); + assert!(at_end.is_finishing()); + assert_eq!(at_end.remaining_minutes(), None); + + let verifying = SplitProgress { stage: SplitStage::Finishing, ..p }; + assert!(verifying.is_finishing()); + assert_eq!(verifying.remaining_minutes(), None); + + // Huge byte counts and u32::MAX minutes never overflow. + let huge = SplitProgress { released_bytes: (u64::MAX - 1) / 2, total_bytes: u64::MAX - 1, ..p }; + assert_eq!(huge.percent(), 50); + assert_eq!(format_approx_minutes(0), "around a minute"); + assert_eq!(format_approx_minutes(45), "around 45 minutes"); + assert_eq!(format_approx_minutes(120), "around 2 hours"); + assert_eq!(format_approx_minutes(125), "around 2 hours 10 minutes"); + assert_eq!(format_approx_minutes(u32::MAX), "around 71582788 hours 20 minutes"); + assert_eq!(format_remaining_minutes(0), "About 1 minute left"); + assert_eq!(format_remaining_minutes(90), "About 1 hour 30 minutes left"); + assert_eq!(format_remaining_compact(110), "~1h 50m left"); + assert_eq!(format_remaining_compact(u32::MAX), "~71582788h 20m left"); +} diff --git a/crates/flow/src/view.rs b/crates/flow/src/view.rs index 2e0706ab..6f810a6b 100644 --- a/crates/flow/src/view.rs +++ b/crates/flow/src/view.rs @@ -165,7 +165,7 @@ pub fn view_with(app: App, options: &rules::Options, state: &State) -> (DeviceVi }; (DeviceView { visible: false, ..lit(m, G::None) }, kind) } - S::Splitting { link: Link::Lost, reopened: false, .. } => { + S::Splitting { link: Link::Lost, .. } => { (DeviceView { rings: true, ..error(m, G::Unplugged) }, ScreenKind::Reconnect) } S::Splitting { reopened: true, .. } => (lit(m, G::Spinner), ScreenKind::SplittingReopened), diff --git a/crates/runtime/src/companion.rs b/crates/runtime/src/companion.rs index eb66e323..b334fd73 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, HeldSnapshot, Layout, Partition}; +use orchard_flow::{Device, Event, HeldSnapshot, Layout, Partition, SplitProgress, SplitStage}; use serde::Deserialize; use serde_json::{json, Value}; use std::io::{BufRead, BufReader, Write}; @@ -91,19 +91,126 @@ pub struct SystemSnapshot { } #[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct Operation { + #[serde(default)] + pub id: Option, pub status: String, #[serde(default)] pub message: Option, - /// The plan it carries out (only its target is read). + /// The plan it carries out. #[serde(default)] pub plan: Option, + /// Index into `plan.steps` of the step currently running. + #[serde(default)] + pub step_index: Option, + /// Seconds since Apple's 2001 reference date when the operation began. + #[serde(default)] + pub started_at: Option, + /// Seconds since Apple's 2001 reference date when `observed_capacity_bytes` + /// was measured. + #[serde(default)] + pub observed_at: Option, + /// Latest APFS container capacity observed by the helper. + #[serde(default)] + pub observed_capacity_bytes: Option, + /// Current stepwise APFS shrink metadata, decoded tolerantly so partial or + /// changed optional telemetry can never reject a valid snapshot. + #[serde(default)] + pub apfs_step: Option, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OperationPlan { - pub target_bytes: i64, + #[serde(default)] + pub target_bytes: Option, + #[serde(default)] + pub before: Option, + #[serde(default)] + pub steps: Option, +} + +impl Operation { + /// Target APFS container size in bytes, when present and non-negative. + pub fn target_bytes(&self) -> Option { + self.plan.as_ref()?.target_bytes.filter(|&b| b >= 0) + } + + fn current_step_name(&self) -> Option<&str> { + let steps = self.plan.as_ref()?.steps.as_ref()?.as_array()?; + let index = self.step_index?; + steps.get(index)?.as_str() + } + + /// Observed APFS shrink progress from the helper's operation snapshot. + /// Tolerates missing, null, partial, or unexpected optional fields. + pub fn split_progress(&self) -> Option { + let plan = self.plan.as_ref()?; + let target = plan.target_bytes.filter(|&b| b >= 0)?; + let before = plan + .before + .as_ref() + .and_then(|v| v.get("containerBytes")) + .and_then(Value::as_i64) + .filter(|&b| b > 0)?; + if before <= target { + return None; + } + let total_bytes = (before - target) as u64; + let current = self + .observed_capacity_bytes + .filter(|&b| b >= 0) + .unwrap_or(before) + .clamp(target, before); + let released_bytes = (before - current) as u64; + let step = self + .apfs_step + .as_ref() + .and_then(|v| v.get("number")) + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .filter(|&n| n > 0); + let planned_steps = self + .apfs_step + .as_ref() + .and_then(|v| v.get("plannedCount")) + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .map(|p| step.map_or(p, |s| p.max(s))) + .filter(|&n| n > 0); + let finishing_step = matches!( + self.current_step_name(), + Some("verifyAPFS" | "shrinkPartition" | "verifyPartition" | "verifyLayout") + ); + let stage = if finishing_step || released_bytes >= total_bytes { + SplitStage::Finishing + } else { + SplitStage::Shrinking + }; + let elapsed_secs = match (self.started_at, self.observed_at) { + (Some(start), Some(obs)) if start.is_finite() && obs.is_finite() && obs >= start => { + Some((obs - start).floor() as u64) + } + _ => None, + }; + let (rate_elapsed_secs, rate_released_bytes) = match elapsed_secs { + Some(secs) => (Some(secs), Some(released_bytes)), + None => (None, None), + }; + let target_ipados_gb = Some((target as f64 / 1e9).round() as u32); + Some(SplitProgress { + released_bytes, + total_bytes, + target_ipados_gb, + step, + planned_steps, + stage, + rate_elapsed_secs, + rate_released_bytes, + elapsed_secs, + }) + } } #[derive(Debug, Clone, Deserialize)] @@ -208,6 +315,8 @@ impl StorageLayout { snapshot, outside, outside_bytes: (self.splittable_bytes() - (apfs.last_lba - apfs.first_lba + 1) * self.sector_size).max(0) as u64, + splittable_bytes: self.splittable_bytes().max(0) as u64, + ipados_container_bytes: self.container_bytes.max(0) as u64, } } @@ -317,12 +426,17 @@ impl Client { raw.map(|_| ()) } - pub fn split(&mut self, apfs_bytes: i64, revision: &str, replacing: &[String]) -> Result<()> { + fn split_start(&mut self, apfs_bytes: i64, revision: &str, replacing: &[String]) -> Result> { let mut body = json!({"apfs_bytes": apfs_bytes, "revision": revision}); if !replacing.is_empty() { body["replacing"] = json!(replacing); } - self.request(json!({ "split": body })).map(drop) + let ok = self.request(json!({ "split": body }))?; + Ok(ok.get("operation").and_then(|o| o.get("id")).and_then(Value::as_str).map(str::to_owned)) + } + + pub fn split(&mut self, apfs_bytes: i64, revision: &str, replacing: &[String]) -> Result<()> { + self.split_start(apfs_bytes, revision, replacing).map(drop) } } @@ -391,6 +505,107 @@ fn save_log(client: &mut Client, logs: &Path, udid: &str) { } } +/// Tracks an active split (either started by this process or adopted when +/// attaching to a running operation) across disconnects and provides a paired +/// local delta baseline when helper timestamps are absent. +#[derive(Debug, Default)] +struct SplitWatcher { + watched: Option<(String, Option)>, + last_progress: Option, + first_sample: Option<(Instant, u64)>, +} + +#[derive(Debug, PartialEq, Eq)] +enum SplitOutcome { + StillRunning { progress: Option }, + Completed, + Stopped { why: String }, + None, +} + +impl SplitWatcher { + fn on_device(&mut self, udid: &str) { + if self.watched.as_ref().is_some_and(|(u, _)| u != udid) { + self.clear(); + } + } + + fn watch(&mut self, udid: &str, operation_id: Option) { + self.watched = Some((udid.to_owned(), operation_id)); + self.last_progress = None; + self.first_sample = None; + } + + fn clear(&mut self) { + self.watched = None; + self.last_progress = None; + self.first_sample = None; + } + + fn is_watching(&self, udid: &str) -> bool { + self.watched.as_ref().is_some_and(|(u, _)| u == udid) + } + + fn matches(&self, udid: &str, op: &Operation) -> bool { + match &self.watched { + Some((u, Some(wid))) if u == udid => op.id.as_deref().is_none_or(|oid| oid == wid), + Some((u, None)) if u == udid => true, + _ => false, + } + } + + fn progress_for(&mut self, op: &Operation, now: Instant) -> Option { + let mut progress = op.split_progress()?; + if progress.rate_elapsed_secs.is_none() { + let (first_at, first_released) = *self.first_sample.get_or_insert((now, progress.released_bytes)); + if progress.released_bytes > first_released { + progress.rate_elapsed_secs = Some(now.saturating_duration_since(first_at).as_secs()); + progress.rate_released_bytes = Some(progress.released_bytes - first_released); + } + } + Some(progress) + } + + fn handle_snapshot(&mut self, udid: &str, snapshot: &Snapshot, now: Instant) -> SplitOutcome { + let Some(op) = snapshot.operation.as_ref() else { + return SplitOutcome::None; + }; + if self.is_watching(udid) && !self.matches(udid, op) { + return SplitOutcome::None; + } + match op.status.as_str() { + "completed" => { + self.clear(); + SplitOutcome::Completed + } + "stopped" | "unknown" => { + let why = unknown_outcome(op) + .or_else(|| op.message.clone()) + .unwrap_or_else(|| "The split stopped.".into()); + self.clear(); + SplitOutcome::Stopped { why } + } + "running" => { + if let Some((_, id_slot)) = &mut self.watched { + if id_slot.is_none() { + *id_slot = op.id.clone(); + } + } + let progress = self.progress_for(op, now); + let emitted = match progress { + Some(p) if self.last_progress != Some(p) => { + self.last_progress = Some(p); + Some(p) + } + _ => None, + }; + SplitOutcome::StillRunning { progress: emitted } + } + _ => SplitOutcome::None, + } + } +} + fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { let socket = Path::new(usbmux::SOCKET); let mut target: Option = None; @@ -398,10 +613,9 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { // Whether the flow has this target's layout (later connections are // reconnects), and when to try connecting next. let mut announced = false; - // A split this run started and hasn't seen end: watched again after a - // reconnect, which may find it already done (the connection can drop - // while the iPad works). - let mut split_pending = false; + // Any split this worker is watching (started here or adopted on attach): + // tracked across disconnects until its terminal status is delivered. + let mut watcher = SplitWatcher::default(); // 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; @@ -422,6 +636,7 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { if !(same && session.is_some()) { if !same { announced = false; + watcher.on_device(&udid); } target = Some(Target { udid, device, token }); session = None; @@ -429,23 +644,25 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { } } Some(Job::Split { omarchy_gb }) => { + let udid = target.as_ref().map(|t| t.udid.clone()).unwrap_or_default(); let result = session.as_mut().ok_or_else(|| fail("the companion is not connected")).and_then(|s| { let bytes = s.layout.apfs_bytes_for(omarchy_gb)?; let replacing = s.layout.following(); // Already split exactly so (only free space after APFS, the // same size, e.g. after an accidental close): nothing to do. if s.layout.split_as(bytes) { + watcher.clear(); let _ = events.send(Event::SplitFinished { ok: true }); return Ok(()); } - s.client.split(bytes, &s.layout.revision, &replacing)?; + let op_id = s.client.split_start(bytes, &s.layout.revision, &replacing)?; s.splitting = true; - split_pending = true; + watcher.watch(&udid, op_id); last_poll = Instant::now(); Ok(()) }); if let Err(e) = result { - split_pending = false; + watcher.clear(); eprintln!("companion: split: {e}"); let fresh = session.as_mut().and_then(|s| s.client.snapshot().ok()); let why = fresh.as_ref().and_then(|f| f.operation.as_ref()).and_then(unknown_outcome).unwrap_or_else(|| e.to_string()); @@ -547,27 +764,56 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { Ok(Opened::Ready(mut client, snapshot)) => { save_log(&mut client, &logs, &t.udid); last_log = Instant::now(); + let now = Instant::now(); let running = snapshot.operation.as_ref().filter(|o| o.status == "running"); - let splitting = running.is_some() || split_pending; + let mut splitting = false; if announced { let _ = events.send(Event::CompanionBack); if std::mem::take(&mut layout_pending) { let _ = events.send(Event::IpadosReady { layout: snapshot.layout.flow_layout() }); } + if watcher.is_watching(&t.udid) || running.is_some() { + if !watcher.is_watching(&t.udid) { + watcher.watch(&t.udid, running.and_then(|o| o.id.clone())); + } + match watcher.handle_snapshot(&t.udid, &snapshot, now) { + SplitOutcome::Completed => { + let _ = events.send(Event::SplitFinished { ok: true }); + } + SplitOutcome::Stopped { why } => { + eprintln!("companion: split stopped: {why}"); + let _ = events.send(Event::SplitRefused(why)); + let _ = events.send(Event::IpadosReady { layout: snapshot.layout.flow_layout() }); + } + SplitOutcome::StillRunning { progress } => { + splitting = true; + if let Some(p) = progress { + let _ = events.send(Event::SplitProgress(p)); + } + } + SplitOutcome::None => { + splitting = watcher.is_watching(&t.udid); + } + } + } } else if let Some(op) = running { // A split this run didn't start is running (the - // installer was closed during it): watch it again. - let target = op.plan.as_ref().map_or(0, |p| p.target_bytes); + // installer was closed during it): adopt and watch it. + let target = op.target_bytes().unwrap_or(0); let omarchy_gb = ((snapshot.layout.splittable_bytes() - target).max(0) as f64 / 1e9).round() as u32; + watcher.watch(&t.udid, op.id.clone()); let _ = events.send(Event::SplitRunning { device: t.device.clone(), omarchy_gb }); + if let SplitOutcome::StillRunning { progress: Some(p) } = watcher.handle_snapshot(&t.udid, &snapshot, now) { + let _ = events.send(Event::SplitProgress(p)); + } announced = true; + splitting = true; } else { let _ = events.send(Event::IpadosReady { layout: snapshot.layout.flow_layout() }); announced = true; } session = Some(Session { client, layout: snapshot.layout.clone(), splitting }); - // A split of ours: its state now, not in POLL. - last_poll = if split_pending { Instant::now() - POLL } else { Instant::now() }; + last_poll = if splitting && snapshot.operation.is_none() { Instant::now() - POLL } else { Instant::now() }; last_ping = Instant::now(); last_error.clear(); } @@ -603,18 +849,15 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { if s.splitting && last_poll.elapsed() >= POLL { last_poll = Instant::now(); let snapshot = s.client.snapshot()?; - match snapshot.operation.as_ref().map(|o| o.status.as_str()) { - Some("completed") => { + let udid = target.as_ref().map(|t| t.udid.as_str()).unwrap_or(""); + match watcher.handle_snapshot(udid, &snapshot, Instant::now()) { + SplitOutcome::Completed => { s.splitting = false; - split_pending = false; s.layout = snapshot.layout; let _ = events.send(Event::SplitFinished { ok: true }); } - Some("stopped" | "unknown") => { + SplitOutcome::Stopped { why } => { s.splitting = false; - split_pending = false; - let op = snapshot.operation.as_ref(); - let why = op.and_then(unknown_outcome).or_else(|| op.and_then(|o| o.message.clone())).unwrap_or_else(|| "The split stopped.".into()); eprintln!("companion: split stopped: {why}"); let _ = events.send(Event::SplitRefused(why)); // The split is chosen again from the layout as it is now. @@ -622,7 +865,12 @@ fn run(jobs: Receiver, events: Sender, logs: std::path::PathBuf) { s.layout = fresh.layout; let _ = events.send(Event::IpadosReady { layout: s.layout.flow_layout() }); } - _ => {} + SplitOutcome::StillRunning { progress } => { + if let Some(p) = progress { + let _ = events.send(Event::SplitProgress(p)); + } + } + SplitOutcome::None => {} } } Ok(()) @@ -805,7 +1053,17 @@ mod tests { #[test] fn an_unknown_outcome_keeps_its_reason_and_asks_for_a_restart() { - let op = |status: &str, message: Option<&str>| Operation { status: status.into(), message: message.map(Into::into), plan: None }; + let op = |status: &str, message: Option<&str>| Operation { + id: None, + status: status.into(), + message: message.map(Into::into), + plan: None, + step_index: None, + started_at: None, + observed_at: None, + observed_capacity_bytes: None, + apfs_step: None, + }; assert_eq!( unknown_outcome(&op("unknown", Some("The worker exited."))).as_deref(), Some("The worker exited. Restart your iPad, then try again.") @@ -814,6 +1072,151 @@ mod tests { assert!(unknown_outcome(&op("stopped", Some("Storage changed."))).is_none()); } + #[test] + fn a_running_shrink_reports_step_released_bytes_and_helper_elapsed_time() { + let mut raw = snapshot(); + raw["operation"] = json!({ + "id": "op-1", + "status": "running", + "stepIndex": 2, + "startedAt": 1000.0, + "observedAt": 2500.0, + "observedCapacityBytes": 238_200_000_000i64, + "plan": { + "targetBytes": 131_000_000_000i64, + "before": { "containerBytes": 256_000_000_000i64 }, + "steps": ["checking", "preparing", "shrinkAPFS", "verifyAPFS", "shrinkPartition", "verifyPartition", "verifyLayout"] + }, + "apfsStep": { + "number": 35, + "plannedCount": 487 + } + }); + let s = parse(raw); + let progress = s.operation.as_ref().unwrap().split_progress().unwrap(); + assert_eq!(progress.released_bytes, 17_800_000_000); + assert_eq!(progress.total_bytes, 125_000_000_000); + assert_eq!(progress.target_ipados_gb, Some(131)); + assert_eq!(progress.step, Some(35)); + assert_eq!(progress.planned_steps, Some(487)); + assert_eq!(progress.stage, SplitStage::Shrinking); + assert_eq!(progress.elapsed_secs, Some(1500)); + assert_eq!(progress.rate_elapsed_secs, Some(1500)); + assert_eq!(progress.rate_released_bytes, Some(17_800_000_000)); + assert_eq!(progress.percent(), 14); + assert_eq!(progress.remaining_minutes(), Some(151)); + } + + #[test] + fn a_running_shrink_at_target_capacity_or_verify_step_is_finishing() { + let mut raw = snapshot(); + raw["operation"] = json!({ + "id": "op-1", + "status": "running", + "stepIndex": 3, + "startedAt": 1000.0, + "observedAt": 4600.0, + "observedCapacityBytes": 131_000_000_000i64, + "plan": { + "targetBytes": 131_000_000_000i64, + "before": { "containerBytes": 256_000_000_000i64 }, + "steps": ["checking", "preparing", "shrinkAPFS", "verifyAPFS", "shrinkPartition"] + }, + "apfsStep": { "number": 487, "plannedCount": 487 } + }); + let p = parse(raw).operation.unwrap().split_progress().unwrap(); + assert!(p.is_finishing()); + assert_eq!(p.percent(), 100); + assert_eq!(p.remaining_minutes(), None); + } + + #[test] + fn partial_null_and_extra_optional_telemetry_never_breaks_terminal_status() { + for op in [ + json!({"status": "completed"}), + json!({"status": "completed", "apfsStep": null, "plan": null, "extraField": [1, 2, 3]}), + json!({"status": "completed", "apfsStep": {"number": 2}, "plan": {"before": {}}}), + json!({"status": "stopped", "message": "Stopped.", "apfsStep": "unexpected", "plan": {"targetBytes": -1, "before": {"containerBytes": -5}}}), + json!({"status": "unknown", "message": "Worker exited.", "plan": {"targetBytes": 10, "steps": "not-an-array"}}), + ] { + let mut raw = snapshot(); + raw["operation"] = op.clone(); + let s = parse(raw); + let parsed = s.operation.as_ref().expect("operation parsed"); + assert_eq!(parsed.status, op["status"].as_str().unwrap()); + assert!(parsed.split_progress().is_none()); + } + } + + #[test] + fn adopted_split_delivers_all_terminal_outcomes_after_disconnect() { + let now = Instant::now(); + for (status, expected) in [ + ("completed", SplitOutcome::Completed), + ("stopped", SplitOutcome::Stopped { why: "Stopped by helper.".into() }), + ("unknown", SplitOutcome::Stopped { why: "Worker lost. Restart your iPad, then try again.".into() }), + ] { + let mut watcher = SplitWatcher::default(); + let mut running = snapshot(); + running["operation"] = json!({ + "id": "op-adopt", + "status": "running", + "observedCapacityBytes": 25_000_000_000i64, + "plan": { "targetBytes": 20_000_000_000i64, "before": { "containerBytes": 30_000_000_000i64 } } + }); + let running = parse(running); + watcher.watch("udid-1", running.operation.as_ref().and_then(|o| o.id.clone())); + assert!(matches!(watcher.handle_snapshot("udid-1", &running, now), SplitOutcome::StillRunning { progress: Some(_) })); + assert!(watcher.is_watching("udid-1")); + + // Reconnect after disconnect: terminal status is processed immediately. + let mut ended = snapshot(); + ended["operation"] = json!({ + "id": "op-adopt", + "status": status, + "message": if status == "stopped" { "Stopped by helper." } else { "Worker lost." } + }); + let ended = parse(ended); + assert_eq!(watcher.handle_snapshot("udid-1", &ended, now + Duration::from_secs(60)), expected); + assert!(!watcher.is_watching("udid-1")); + } + } + + #[test] + fn reopened_split_without_helper_timestamps_uses_delta_rate_not_lifetime_bytes() { + let mut watcher = SplitWatcher::default(); + watcher.watch("udid-1", Some("op-no-ts".into())); + let t0 = Instant::now(); + let make = |obs: i64| { + let mut raw = snapshot(); + raw["operation"] = json!({ + "id": "op-no-ts", + "status": "running", + "observedCapacityBytes": obs, + "plan": { "targetBytes": 100_000_000_000i64, "before": { "containerBytes": 200_000_000_000i64 } } + }); + parse(raw) + }; + // First sample on reopen: already 50 GB shrunk -> no ETA yet (avoid dividing 50 GB by 30 s!). + let first = watcher.handle_snapshot("udid-1", &make(150_000_000_000), t0); + match first { + SplitOutcome::StillRunning { progress: Some(p) } => { + assert_eq!(p.percent(), 50); + assert_eq!(p.remaining_minutes(), None); + } + other => panic!("expected StillRunning, got {other:?}"), + } + // Two minutes later, 2 GB more shrunk -> rate is 1 GB/min -> 48 GB left => 48 min left. + let next = watcher.handle_snapshot("udid-1", &make(148_000_000_000), t0 + Duration::from_secs(120)); + match next { + SplitOutcome::StillRunning { progress: Some(p) } => { + assert_eq!(p.percent(), 52); + assert_eq!(p.remaining_minutes(), Some(48)); + } + other => panic!("expected StillRunning, got {other:?}"), + } + } + #[test] fn a_shrunk_apfs_in_its_old_partition_is_not_split_yet() { let mut raw = snapshot(); @@ -822,6 +1225,11 @@ mod tests { let s = parse(raw.clone()); let bytes = s.layout.container_bytes; assert!(!s.layout.split_as(bytes), "the partition still has to shrink"); + // Flow layout preserves exact container bytes so growing back above + // container_bytes is classified as Grow, not Shrink. + let flow = s.layout.flow_layout(); + assert_eq!(flow.ipados_container_bytes, bytes as u64); + assert_eq!(orchard_flow::split_action(&flow, 8), orchard_flow::SplitAction::Grow); // Both shrunk: done. raw["layout"]["partitions"][1]["lastLBA"] = json!(3_999_999); assert!(parse(raw).layout.split_as(bytes)); diff --git a/crates/runtime/src/demo.rs b/crates/runtime/src/demo.rs index 472c014b..f2f534ab 100644 --- a/crates/runtime/src/demo.rs +++ b/crates/runtime/src/demo.rs @@ -80,12 +80,14 @@ fn ipados_layout() -> Layout { }), outside: Vec::new(), outside_bytes: 0, + splittable_bytes: 0, + ipados_container_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, ipados_floor_gb: 0, snapshot: None, 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, splittable_bytes: 0, ipados_container_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 } + Layout { total_gb: 128, ipados_gb: 128, ipados_used_gb: 41, ipados_floor_gb: 0, snapshot: None, outside: Vec::new(), outside_bytes: 0, splittable_bytes: 0, ipados_container_bytes: 0 } } /// What the install system reports: empty space after a split, which asked @@ -100,6 +102,8 @@ fn env_layout(omarchy_gb: u32) -> Layout { snapshot: None, outside: if SPLIT.load(std::sync::atomic::Ordering::Relaxed) { Vec::new() } else { earlier_system(omarchy_gb) }, outside_bytes: 0, + splittable_bytes: 0, + ipados_container_bytes: 0, } } diff --git a/crates/runtime/src/install.rs b/crates/runtime/src/install.rs index 271ee16d..7a8ebba4 100644 --- a/crates/runtime/src/install.rs +++ b/crates/runtime/src/install.rs @@ -116,7 +116,17 @@ 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, ipados_floor_gb: 0, snapshot: None, 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)), + splittable_bytes: 0, + ipados_container_bytes: 0, + } } impl Worker {