diff --git a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java index f509a55bf..4618b5e20 100644 --- a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java +++ b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java @@ -27,15 +27,46 @@ import org.iiab.controller.download.domain.MetalinkSplit; import org.iiab.controller.download.domain.MetalinkFile; import org.iiab.controller.download.domain.DownloadVerifier; +import org.iiab.controller.download.domain.ByteToken; +import org.iiab.controller.download.domain.DownloadEta; +import org.iiab.controller.download.domain.Aria2ProgressLine; public class Aria2Manager { private static final String TAG = "IIAB-Aria2-Native"; - private Process aria2Process; - private boolean isCancelled = false; + /** + * ADFA-4895: volatile for the same reason as the flag below, and it is the more important of + * the two. It is assigned on the download thread and read by {@code stopDownload()} on the + * caller's, so a stale null there means the process is never destroyed and the user's cancel + * does nothing at all. + */ + private volatile Process aria2Process; + /** + * ADFA-4895: volatile. It is written by {@code stopDownload()} on the caller's thread and read + * by the download thread's loop and its catch block, so without this a stop could go unseen and + * a user cancellation would be reported as a fatal error. + */ + private volatile boolean isCancelled = false; public interface DownloadListener { void onProgress(int percentage, String speed, String eta); + + /** + * ADFA-4895: the same tick, with the figures as numbers instead of display text. + * + *
Added rather than replacing the three-argument form so the two content call sites are + * untouched: they keep overriding that one and inherit this default, which forwards. Only a + * caller that needs to *decide* on the transfer — rather than draw it — overrides this. + * + * @param bytesPerSecond current rate, or {@link ByteToken#UNKNOWN} + * @param etaSeconds our own estimate, or {@link DownloadEta#UNKNOWN}. Not aria2's: + * see ADR-4893 for why a figure we cannot explain is a bad one to + * act on. + */ + default void onProgress(int percentage, String speed, String eta, + long bytesPerSecond, long etaSeconds) { + onProgress(percentage, speed, eta); + } void onComplete(String downloadPath); void onError(String error); /** ADFA-4676: post-download integrity gate failed (size/SHA-256 mismatch). */ @@ -179,6 +210,20 @@ public void startDownload(Context context, String url, DownloadListener listener command.add("--summary-interval=1"); command.add("--download-result=hide"); + // ADFA-4895: aria2 already knows how to survive a bad link; we were not asking it + // to. These are set explicitly rather than inherited, so the behaviour is pinned by + // this file and does not change under us when the bundled aria2 is rebuilt. + // + // No --lowest-speed-limit here on purpose. It makes aria2 abort a transfer that + // drops below a floor, which is only safe once a caller retries and resumes: on the + // links this product targets, a slow download is the normal case, and aborting one + // with nothing to catch it would be worse than the stall we are trying to detect. + // It lands with the retry loop, not before it. + command.add("--max-tries=5"); + command.add("--retry-wait=5"); // default is 0 — retries hammer a struggling server + command.add("--timeout=60"); // per-connection read timeout + command.add("--connect-timeout=30"); + // Apply network decision if (forceIpv4) { Log.w(TAG, "Network profiler decided to FORCE IPv4."); @@ -201,6 +246,7 @@ public void startDownload(Context context, String url, DownloadListener listener // Example: [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s] Pattern pattern = Pattern.compile("\\((\\d+)%\\).*?DL:([^\\s]+).*?ETA:([^\\s\\]]+)"); + while ((line = reader.readLine()) != null) { if (isCancelled) { aria2Process.destroy(); @@ -219,7 +265,21 @@ public void startDownload(Context context, String url, DownloadListener listener String speed = matcher.group(2) + context.getString(R.string.k2go_rate_per_second); String eta = matcher.group(3); - mainHandler.post(() -> listener.onProgress(percent, speed, eta)); + // ADFA-4895: keep the figures as numbers alongside the display text. The + // rate was being destroyed one line above — concatenated into a localized + // string — so nothing downstream could compare it to anything or divide a + // remaining size by it. + long bytesPerSecond = ByteToken.parse(matcher.group(2)); + // The Metalink's size is the authority when we have it: it is what the + // integrity gate will check against, so the estimate and the verdict are + // measured against the same number. + long done = Aria2ProgressLine.completedBytes(line); + long total = (mf != null && mf.sizeBytes() > 0) + ? mf.sizeBytes() : Aria2ProgressLine.declaredTotalBytes(line); + long etaSeconds = DownloadEta.secondsRemaining(done, total, bytesPerSecond); + final long rate = bytesPerSecond; + final long secs = etaSeconds; + mainHandler.post(() -> listener.onProgress(percent, speed, eta, rate, secs)); } } @@ -233,7 +293,14 @@ public void startDownload(Context context, String url, DownloadListener listener } if (exitCode != 0) { - mainHandler.post(() -> listener.onError("Aria2c native process failed with code " + exitCode)); + // ADFA-4895: say what aria2 said. Every non-zero exit used to produce the same + // sentence, so a full disk, a missing mirror and a dropped Wi-Fi were one + // event, and nothing downstream could tell which of them was worth retrying. + org.iiab.controller.download.domain.Aria2Exit.Kind kind = + org.iiab.controller.download.domain.Aria2Exit.kindOf(exitCode); + String reason = org.iiab.controller.download.domain.Aria2Exit.label(exitCode); + Log.e(TAG, "aria2 exit " + exitCode + " (" + kind + "): " + reason); + mainHandler.post(() -> listener.onError(reason)); return; } // ADFA-4676: never trust the exit code alone. For a Metalink download, diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java new file mode 100644 index 000000000..08e00ba54 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java @@ -0,0 +1,114 @@ +/* + * ============================================================================ + * Name : Aria2Exit.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: what an aria2 exit code means. + * No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +/** + * What aria2 was telling us when it stopped. + * + *
Until now every non-zero exit produced the same message — "Aria2c native process failed with + * code N" — and the caller failed the whole install on all of them. That throws away the one thing + * aria2 is careful about: it distinguishes a network hiccup from a missing file from a full disk, + * and only one of those is worth trying again. Retry, resume and any honest report to the user all + * need this distinction first, which is why it lands before them. + * + *
Describes, does not decide. This class says what happened; it does not say how many + * times to retry or how long to wait. That policy belongs with the caller that owns the download, + * and keeping it out of here is what lets the rootfs path and the content paths make different + * choices from the same reading. + * + *
Unknown is its own answer, not a synonym for fatal. aria2's own code 1 is literally + * "unknown error" and in practice it covers transient conditions as well as real ones; folding it + * into either bucket would be inventing information we do not have. The caller decides what + * caution means for it. + */ +public final class Aria2Exit { + + /** What kind of stop this was. */ + public enum Kind { + /** Everything downloaded. */ + SUCCESS, + /** A condition that commonly clears by itself: timeouts, resolution, network drops. */ + TRANSIENT, + /** aria2 gave up because the transfer was too slow ({@code --lowest-speed-limit}). */ + STALLED, + /** Trying again with the same inputs cannot help: not found, no disk space, bad auth. */ + PERMANENT, + /** aria2 did not say, or said something this table does not cover. */ + UNKNOWN + } + + private Aria2Exit() { + } + + /** + * Classify an aria2 process exit code. + * + *
The table below is aria2's documented set. Codes outside it are {@link Kind#UNKNOWN} + * rather than assumed, so a future aria2 that adds one does not get silently mislabelled. + */ + public static Kind kindOf(int exitCode) { + switch (exitCode) { + case 0: return Kind.SUCCESS; + + // Worth another attempt: the far side or the link misbehaved. + case 2: // timeout + case 6: // network problem + case 7: // unfinished downloads remained + case 19: // name resolution failed + case 22: // bad HTTP response header + case 29: // server temporarily unavailable + return Kind.TRANSIENT; + + // aria2 aborted the transfer itself for being below the floor we set. + case 5: + return Kind.STALLED; + + // Same inputs, same outcome. Retrying only wastes the user's data. + case 3: // resource not found + case 4: // resource not found too many times + case 8: // remote server does not support resume + case 9: // not enough disk space + case 16: // could not open or create the file + case 24: // HTTP authorization failed + return Kind.PERMANENT; + + case 1: // aria2's own "unknown error" + default: + return Kind.UNKNOWN; + } + } + + /** + * A short, stable English phrase for logs and for the failure text we keep in the install + * state. Not a user-facing string: those are localized resources chosen by the presentation + * layer, which can map {@link Kind} however it needs to. + */ + public static String label(int exitCode) { + switch (exitCode) { + case 0: return "ok"; + case 1: return "unspecified aria2 error"; + case 2: return "connection timed out"; + case 3: return "file not found on the server"; + case 4: return "file not found on any mirror"; + case 5: return "transfer too slow, aborted"; + case 6: return "network problem"; + case 7: return "download left unfinished"; + case 8: return "server does not support resuming"; + case 9: return "not enough disk space"; + case 16: return "could not write the file"; + case 19: return "could not resolve the host"; + case 22: return "bad response from the server"; + case 24: return "server rejected the request"; + case 29: return "server temporarily unavailable"; + default: return "aria2 exit code " + exitCode; + } + } + +} diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java new file mode 100644 index 000000000..b00c8525d --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java @@ -0,0 +1,70 @@ +/* + * ============================================================================ + * Name : Aria2ProgressLine.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: pull the figures out of one line of + * aria2 console output. No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Reads one line of aria2's summary output. + * + *
A real line looks like this: + * + *
[#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]+ * + *
Why this is its own class. It began as a second {@link Pattern} inside + * {@code Aria2Manager}, which is an Android class holding a live process and a Handler — so the + * most breakable part of the change, a regex against a third party's output format, was the one + * part no test could reach. Here it is reachable, and a change to aria2's formatting fails a test + * instead of quietly producing a wrong estimate on a device. + * + *
Deliberately separate from the progress pattern that already worked. The percentage + * and rate the screen has always shown come from a different expression in {@code Aria2Manager}. + * If this one stops matching, the estimate goes unknown and the line the user reads is untouched. + */ +public final class Aria2ProgressLine { + + /** + * The completed/total pair that precedes the percentage. + * + *
Both halves are a number with an optional unit, so {@code 400MiB/1.0GiB(39%)} yields + * {@code 400MiB} and {@code 1.0GiB}. Anchored on the {@code (NN%)} that follows, which is what + * keeps it from matching the {@code CN:4} or a path with a slash in it. + */ + private static final Pattern SIZES = + Pattern.compile("([\\d.]+[A-Za-z]*)/([\\d.]+[A-Za-z]*)\\(\\d+%\\)"); + + private Aria2ProgressLine() { + } + + /** Bytes transferred so far, or {@link ByteToken#UNKNOWN} if the line does not carry them. */ + public static long completedBytes(String line) { + Matcher m = matcher(line); + return m == null ? ByteToken.UNKNOWN : ByteToken.parse(m.group(1)); + } + + /** + * The size aria2 believes it is fetching, or {@link ByteToken#UNKNOWN}. + * + *
Prefer the Metalink's figure over this one where both exist: the Metalink is what the + * integrity gate checks against, so using it keeps the estimate and the verdict measured + * against the same number. + */ + public static long declaredTotalBytes(String line) { + Matcher m = matcher(line); + return m == null ? ByteToken.UNKNOWN : ByteToken.parse(m.group(2)); + } + + private static Matcher matcher(String line) { + if (line == null || line.isEmpty()) return null; + Matcher m = SIZES.matcher(line); + return m.find() ? m : null; + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java b/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java new file mode 100644 index 000000000..20c92330a --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java @@ -0,0 +1,110 @@ +/* + * ============================================================================ + * Name : ByteToken.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: aria2's "400MiB" / "4.5MiB" / "1.0GiB" + * tokens back into bytes. No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +/** + * Reads a size or rate token out of an aria2 progress line and gives back a number. + * + *
Why this exists. aria2 prints everything we need on one line — + * {@code [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]} — and until now the app captured + * the rate only to concatenate a localized "/s" onto it and hand a display string upwards. A + * string cannot be compared to a baseline, cannot be divided into a remaining size, and cannot be + * decided on. The number has to survive the parse. + * + *
Binary and decimal are not the same and the difference is not academic. aria2 emits + * IEC units (KiB, MiB, GiB — powers of 1024) but the same field can carry SI units from other + * tools, and at gigabyte scale treating GiB as GB is a 7% error — which lands directly in an + * estimate the user is asked to make a decision on. Both tables are kept, and the {@code i} is + * what selects between them. + * + *
Mirrors {@code parseRate} in {@code static/dashboard/sockets/kiwix.exec.ts}, deliberately: + * the in-server downloader reads the same tokens from the same program. If one changes, change + * both — the same standing coordination as the aria2 flag sets (ADFA-4832). + */ +public final class ByteToken { + + /** The token could not be read. Distinct from a real zero, which is a legitimate rate. */ + public static final long UNKNOWN = -1L; + + private static final long KI = 1024L; + private static final long MI = KI * 1024L; + private static final long GI = MI * 1024L; + private static final long TI = GI * 1024L; + + private ByteToken() { + } + + /** + * Parse a token such as {@code 400MiB}, {@code 4.5MiB}, {@code 1.0GiB}, {@code 512K}, + * {@code 1.2MB} or a bare {@code 850} into bytes. + * + *
A missing unit means bytes, which is what aria2 does. Anything unreadable is + * {@link #UNKNOWN} rather than zero: a download reporting nothing and a download reporting + * genuinely no throughput are different facts, and only one of them means the transfer is in + * trouble. + */ + public static long parse(String token) { + if (token == null) return UNKNOWN; + String t = token.trim(); + if (t.isEmpty()) return UNKNOWN; + + int i = 0; + while (i < t.length() && (Character.isDigit(t.charAt(i)) || t.charAt(i) == '.')) i++; + if (i == 0) return UNKNOWN; + + double value; + try { + value = Double.parseDouble(t.substring(0, i)); + } catch (NumberFormatException e) { + return UNKNOWN; + } + // No sign check: the scan above never consumes a '-', so a negative token has + // already been rejected before we get here. + if (Double.isNaN(value) || Double.isInfinite(value)) return UNKNOWN; + + String unit = t.substring(i).trim(); + // aria2 writes a trailing "/s" on some fields; the rate and the size share this parser. + int slash = unit.indexOf('/'); + if (slash >= 0) unit = unit.substring(0, slash); + unit = unit.toUpperCase(java.util.Locale.ROOT); + + long multiplier = multiplierFor(unit); + if (multiplier == UNKNOWN) return UNKNOWN; + + double bytes = value * multiplier; + if (bytes > Long.MAX_VALUE) return UNKNOWN; + return Math.round(bytes); + } + + /** {@code UNKNOWN} for a unit this does not recognise, so a typo is never read as bytes. */ + private static long multiplierFor(String unit) { + switch (unit) { + case "": + case "B": return 1L; + case "K": + case "KI": + case "KIB": return KI; + case "M": + case "MI": + case "MIB": return MI; + case "G": + case "GI": + case "GIB": return GI; + case "T": + case "TI": + case "TIB": return TI; + case "KB": return 1000L; + case "MB": return 1000_000L; + case "GB": return 1000_000_000L; + case "TB": return 1000_000_000_000L; + default: return UNKNOWN; + } + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java b/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java new file mode 100644 index 000000000..8bfb56074 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java @@ -0,0 +1,49 @@ +/* + * ============================================================================ + * Name : DownloadEta.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: how long is left, from what is left and + * how fast it is moving. No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +/** + * How much longer a transfer needs, computed here rather than taken from aria2. + * + *
Why not aria2's own ETA. It prints one on every progress line and parsing it would be + * free. It is not used because ADR-4893 makes the estimate a decision input — the figure the app + * weighs before offering the user an action — and a number we cannot explain is a bad thing to + * decide on. With a Metalink across several mirrors, aria2's estimate can jump when one mirror + * drops, and nothing downstream could tell that from the link itself degrading. Ours is arithmetic + * on two figures printed on the same line, so when it moves we know why. + * + *
What it refuses to answer. A rate of zero is not "infinity seconds", it is "no + * estimate": a stalled transfer has no honest completion time, and inventing a very large number + * would be read downstream as a very slow transfer, which is a different situation with a + * different remedy. {@link #UNKNOWN} keeps those apart. + */ +public final class DownloadEta { + + /** No honest estimate. Matches {@code EtaSmoother.UNKNOWN} so the two compose. */ + public static final long UNKNOWN = -1L; + + private DownloadEta() { + } + + /** + * Seconds remaining, or {@link #UNKNOWN}. + * + * @param completedBytes bytes transferred so far, or {@link ByteToken#UNKNOWN} + * @param totalBytes the full size — prefer the Metalink's figure over the progress line's, + * since the Metalink is what the integrity gate will check against + * @param bytesPerSecond current rate, or {@link ByteToken#UNKNOWN} + */ + public static long secondsRemaining(long completedBytes, long totalBytes, long bytesPerSecond) { + if (totalBytes <= 0 || completedBytes < 0 || bytesPerSecond <= 0) return UNKNOWN; + if (completedBytes >= totalBytes) return 0L; + return (totalBytes - completedBytes) / bytesPerSecond; + } + +} diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java index 72ff20405..3d8ea1113 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java @@ -62,6 +62,8 @@ public boolean isRunning() { // All posts are thread-safe (callable from the aria2 / proot worker threads). public void postDownloading(int percent, String speed) { post(InstallState.downloading(percent, speed)); } + /** ADFA-4895: the rate and our own estimate, together. */ + public void postDownloading(int percent, String speed, String eta) { post(InstallState.downloading(percent, speed, eta)); } public void postExtracting(String message) { post(InstallState.extracting(message)); } public void postExtracting(int percent, String message) { post(InstallState.extracting(percent, message)); } // ADFA-5118: unified verify+extract bar — determinate progress with an ETA for both passes. diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java index 1d78e2887..0a551ddbc 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java @@ -328,11 +328,37 @@ private void startRootfsDownload() { aria2Manager.startDownload(this, directUrl, new Aria2Manager.DownloadListener() { @Override public void onProgress(int percentage, String speed, String eta) { + // Still live, and not a leftover: Aria2NetworkProfiler reports through this form + // ("Test IPv4", "Test IPv6", then the winner) before the real transfer begins, so + // an empty override here would blank the status line for the whole probe. It has + // no rate and no estimate to carry — those only exist once aria2 is transferring. if (cancelled) return; InstallProgressRepository.get().postDownloading(percentage, speed); updateNotification(getString(R.string.install_status_os_download, percentage, speed)); } + @Override + public void onProgress(int percentage, String speed, String eta, + long bytesPerSecond, long etaSeconds) { + if (cancelled) return; + // ADFA-4895: no smoothing here, deliberately, and it is not an oversight — a first + // pass used EtaSmoother and the label froze at "about 26 min" for half a download + // that took sixty seconds. Two reasons, and the second is the one that matters: + // the smoother adopts its first reading immediately, which lands while aria2 is + // still ramping and is the worst estimate of the whole run; and its dwell only + // advances while the value holds steady, so a figure that moves every tick resets + // the window forever and nothing ever replaces that first reading. + // + // The deeper reason is that this signal does not need it. Extraction wobbles + // because files decompress at wildly different speeds; a transfer rate over a + // network is comparatively steady — 34 to 40 MiB/s across a whole run, measured. + // Fed a steady rate the estimate moves smoothly on its own, and moving is what an + // estimate is supposed to do. + int bucket = org.iiab.controller.install.domain.EtaSmoother.bucketOf(etaSeconds); + InstallProgressRepository.get().postDownloading(percentage, speed, formatEta(bucket)); + updateNotification(getString(R.string.install_status_os_download, percentage, speed)); + } + @Override public void onComplete(String downloadPath) { if (cancelled) return; diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java index 901520e3b..b0bb5dad5 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java @@ -34,7 +34,24 @@ public enum Op { INSTALL, RESET, REBUILD } public final String message; // resolved status text / current file line / error public final long seq; // assigned by the repository; identifies terminal events + /** + * ADFA-4895: resolved "time left" text, or empty. A field of its own because DOWNLOADING has to + * show a rate AND an estimate at once, so it cannot borrow the speed slot the way ADFA-5118's + * verify/extract states do — those have no rate to display, so the slot was free there. + * + *
The 5118 states are left as they are. When their layout is next touched they should move
+ * onto this field too, so "speed" means a rate everywhere and nothing has to be read twice to
+ * find out what it is carrying.
+ */
+ public final String eta;
+
private InstallState(Phase phase, Op op, int percent, String speed, String message, long seq) {
+ this(phase, op, percent, speed, message, seq, "");
+ }
+
+ private InstallState(Phase phase, Op op, int percent, String speed, String message, long seq,
+ String eta) {
+ this.eta = eta != null ? eta : "";
this.phase = phase;
this.op = op != null ? op : Op.INSTALL;
this.percent = percent;
@@ -54,12 +71,12 @@ public boolean isTerminal() {
/** Returns a copy with the given sequence number (the repository assigns it). */
InstallState withSeq(long seq) {
- return new InstallState(phase, op, percent, speed, message, seq);
+ return new InstallState(phase, op, percent, speed, message, seq, eta);
}
/** Returns a copy tagged with the given operation (the repository stamps it). */
InstallState withOp(Op op) {
- return new InstallState(phase, op, percent, speed, message, seq);
+ return new InstallState(phase, op, percent, speed, message, seq, eta);
}
public static InstallState idle() {
@@ -70,6 +87,15 @@ public static InstallState downloading(int percent, String speed) {
return new InstallState(Phase.DOWNLOADING, Op.INSTALL, percent, speed, "", 0L);
}
+ /**
+ * ADFA-4895: downloading with an estimate beside the rate. The screen shows all three —
+ * "32% · 37MiB/s · about 3 min left" — because on a slow link the percentage barely moves
+ * and the rate alone does not say whether this finishes tonight.
+ */
+ public static InstallState downloading(int percent, String speed, String eta) {
+ return new InstallState(Phase.DOWNLOADING, Op.INSTALL, percent, speed, "", 0L, eta);
+ }
+
public static InstallState extracting(String message) {
return new InstallState(Phase.EXTRACTING, Op.INSTALL, 0, "", message, 0L);
}
diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java
index d78c1677c..e9cf1719d 100644
--- a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java
+++ b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java
@@ -57,6 +57,9 @@ public class LibraryActivity extends AppCompatActivity implements ServerControll
private LottieAnimationView bootGate;
private View installProgress;
private android.widget.TextView installStatus, installDetail, installPercent, installEta;
+ // ADFA-4895: the three-column row, shown only once the transfer is really running.
+ private android.widget.TextView dlPercent, dlRate, dlEta;
+ private View downloadRow;
private View installPercentRow; // ADFA-5118: the %/ETA weighted-column row
private android.widget.ProgressBar installBar;
private boolean gateDismissed = false;
@@ -130,6 +133,10 @@ protected void onCreate(Bundle savedInstanceState) {
installPercentRow = findViewById(R.id.k2go_install_percent_row);
installPercent = findViewById(R.id.k2go_install_percent);
installEta = findViewById(R.id.k2go_install_eta);
+ downloadRow = findViewById(R.id.k2go_download_row); // ADFA-4895
+ dlPercent = findViewById(R.id.k2go_download_percent);
+ dlRate = findViewById(R.id.k2go_download_rate);
+ dlEta = findViewById(R.id.k2go_download_eta);
// ADFA-4947: shared ellipsis animators (fixed-width so the centered lines don't shift).
bootEllipsis = new org.iiab.controller.util.EllipsisAnimator(installStatus, true);
readingEllipsis = new org.iiab.controller.util.EllipsisAnimator(installDetail, true);
@@ -331,12 +338,37 @@ private void showInstallProgress(InstallState st) {
stopBootEllipsis(); // ADFA-4837: an install owns the status line; stop the boot animation
installProgress.setVisibility(View.VISIBLE);
if (installBar != null) installBar.setVisibility(View.VISIBLE); // ADFA-4837: boot/shutdown hide it
- if (installPercentRow != null) installPercentRow.setVisibility(View.GONE); // ADFA-4910/5118: only the determinate verify/extract shows it
+ if (installPercentRow != null) installPercentRow.setVisibility(View.GONE);
+ if (downloadRow != null) downloadRow.setVisibility(View.GONE); // ADFA-4895
if (st.phase == InstallState.Phase.DOWNLOADING) {
installStatus.setText(getString(R.string.k2go_downloading_library));
installBar.setIndeterminate(false);
installBar.setProgress(st.percent);
- installDetail.setText(pct(st.percent) + (st.speed.isEmpty() ? "" : " · " + st.speed));
+ // ADFA-4895: one table per line, sized to the line, rather than one table stretched
+ // over both. Before the transfer starts the line carries two things — "0%" and
+ // "Test IPv4" — and pushing those through a three-column row leaves a visible hole
+ // where the third would be. Once a rate and an estimate are both real there are three,
+ // and they get a row built for three. Either way every figure sits in a fixed column,
+ // so a rate swinging between "412KiB/s" and "37MiB/s" cannot drag the % sideways —
+ // the dance ADFA-4910 and ADFA-5118 already fixed for extract.
+ boolean threeUp = !st.speed.isEmpty() && !st.eta.isEmpty();
+ if (threeUp && downloadRow != null) {
+ downloadRow.setVisibility(View.VISIBLE);
+ dlPercent.setText(pct(st.percent));
+ dlRate.setText(st.speed);
+ dlEta.setText("· " + st.eta);
+ } else if (installPercentRow != null) {
+ installPercentRow.setVisibility(View.VISIBLE);
+ installPercent.setText(pct(st.percent));
+ boolean hasSecond = !st.speed.isEmpty();
+ installEta.setText(hasSecond ? st.speed : "");
+ installEta.setVisibility(hasSecond ? View.VISIBLE : View.GONE);
+ // Alone, the % owns the row and centres — the rule ADFA-5118 already applies
+ // before its own estimate appears.
+ installPercent.setGravity(hasSecond
+ ? android.view.Gravity.END : android.view.Gravity.CENTER_HORIZONTAL);
+ }
+ installDetail.setText("");
} else if (st.phase == InstallState.Phase.VERIFYING || st.phase == InstallState.Phase.EXTRACTING) {
// ADFA-5118: the unified verify+extract bar. Both passes render identically — determinate
// bar + % + ETA + current file — so there is no "first nothing, then detail" asymmetry.
diff --git a/controller/app/src/main/res/layout/activity_library.xml b/controller/app/src/main/res/layout/activity_library.xml
index c61b20ec0..914163f8f 100644
--- a/controller/app/src/main/res/layout/activity_library.xml
+++ b/controller/app/src/main/res/layout/activity_library.xml
@@ -130,6 +130,46 @@
android:textColor="@color/k2go_boot_muted" />
+
+ The distinction under most of these: **no estimate** and **a bad estimate** are different
+ * answers. A stalled transfer has no honest completion time, and a very large number would be read
+ * downstream as a very slow transfer — a different situation with a different remedy.
+ */
+public class DownloadEtaTest {
+
+ private static final long KI = 1024L, MI = KI * 1024L, GI = MI * 1024L;
+
+ // ---- ByteToken: the units aria2 actually prints -------------------------
+
+ @Test
+ public void readsTheTokensFromARealProgressLine() {
+ // [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]
+ assertEquals(400 * MI, ByteToken.parse("400MiB"));
+ assertEquals(GI, ByteToken.parse("1.0GiB"));
+ assertEquals(Math.round(4.5 * MI), ByteToken.parse("4.5MiB"));
+ }
+
+ @Test
+ public void aMissingUnitMeansBytes() {
+ assertEquals(850L, ByteToken.parse("850"));
+ assertEquals(850L, ByteToken.parse("850B"));
+ }
+
+ /**
+ * The one that costs real money if it is wrong. At gigabyte scale, reading GiB as GB is a 7%
+ * error, and it lands straight in an estimate the user is asked to act on.
+ */
+ @Test
+ public void binaryAndDecimalUnitsAreNotConflated() {
+ assertEquals(GI, ByteToken.parse("1GiB"));
+ assertEquals(1_000_000_000L, ByteToken.parse("1GB"));
+ assertTrue(ByteToken.parse("1GiB") > ByteToken.parse("1GB"));
+ assertEquals(KI, ByteToken.parse("1KiB"));
+ assertEquals(1000L, ByteToken.parse("1KB"));
+ }
+
+ @Test
+ public void aTrailingPerSecondIsStripped() {
+ assertEquals(Math.round(4.5 * MI), ByteToken.parse("4.5MiB/s"));
+ }
+
+ @Test
+ public void caseAndSurroundingSpaceDoNotMatter() {
+ assertEquals(MI, ByteToken.parse(" 1mib "));
+ assertEquals(MI, ByteToken.parse("1MIB"));
+ }
+
+ /** An unreadable token is UNKNOWN, never zero — zero is a legitimate rate and means something. */
+ @Test
+ public void unreadableIsUnknownAndNotZero() {
+ for (String s : new String[]{null, "", " ", "--", "MiB", "abc", "1.2XB", "-5MiB"}) {
+ assertEquals(String.valueOf(s), ByteToken.UNKNOWN, ByteToken.parse(s));
+ }
+ assertEquals(0L, ByteToken.parse("0"));
+ assertEquals(0L, ByteToken.parse("0B"));
+ }
+
+ // ---- DownloadEta: the estimate ------------------------------------------
+
+ @Test
+ public void theOrdinaryCase() {
+ // 600 MiB left at 4 MiB/s
+ long left = 400 * MI, total = GI, rate = 4 * MI;
+ assertEquals((total - left) / rate, DownloadEta.secondsRemaining(left, total, rate));
+ }
+
+ @Test
+ public void alreadyCompleteIsZeroSecondsAndNotNegative() {
+ assertEquals(0L, DownloadEta.secondsRemaining(GI, GI, MI));
+ assertEquals(0L, DownloadEta.secondsRemaining(2 * GI, GI, MI));
+ }
+
+ /**
+ * A stalled transfer has no completion time. Returning a huge number instead would be read as
+ * "very slow", which is a different situation and would earn the wrong offer.
+ */
+ @Test
+ public void aStalledTransferHasNoEstimateRatherThanAHugeOne() {
+ assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, GI, 0L));
+ }
+
+ @Test
+ public void missingInputsGiveNoEstimate() {
+ assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, 0L, MI));
+ assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, -1L, MI));
+ assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(-1L, GI, MI));
+ assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, GI, -1L));
+ }
+
+ /** UNKNOWN composes with EtaSmoother, which uses the same sentinel for "no honest estimate". */
+ @Test
+ public void unknownMatchesTheSmootherSentinel() {
+ assertEquals(org.iiab.controller.install.domain.EtaSmoother.UNKNOWN,
+ (int) DownloadEta.UNKNOWN);
+ }
+
+ // ---- reading the figures out of a real line ------------------------------
+
+ private static final String LINE = "[#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]";
+
+ /**
+ * The whole point of extracting this from Aria2Manager: the most breakable part of the change
+ * is a regex against a third party's output format, and there it was unreachable by any test.
+ */
+ @Test
+ public void pullsCompletedAndTotalOutOfARealLine() {
+ assertEquals(400 * MI, Aria2ProgressLine.completedBytes(LINE));
+ assertEquals(GI, Aria2ProgressLine.declaredTotalBytes(LINE));
+ }
+
+ @Test
+ public void theWholeChainFromLineToEstimate() {
+ long done = Aria2ProgressLine.completedBytes(LINE);
+ long total = Aria2ProgressLine.declaredTotalBytes(LINE);
+ long rate = ByteToken.parse("4.5MiB");
+ // 1 GiB - 400 MiB left at 4.5 MiB/s
+ assertEquals((total - done) / rate, DownloadEta.secondsRemaining(done, total, rate));
+ }
+
+ /**
+ * The CN:4 is the trap: a bare "4" beside a slash-free field must not be mistaken for a pair.
+ * The pattern is anchored on the (NN%) that follows the sizes, which is what excludes it.
+ */
+ @Test
+ public void doesNotMatchTheConnectionCountOrAPath() {
+ assertEquals(ByteToken.UNKNOWN, Aria2ProgressLine.completedBytes("[#2089b0 CN:4 DL:4.5MiB]"));
+ assertEquals(ByteToken.UNKNOWN,
+ Aria2ProgressLine.completedBytes("Downloading /data/foo/bar to /data/baz"));
+ }
+
+ @Test
+ public void aLineWithoutTheFiguresGivesUnknownRatherThanZero() {
+ for (String l : new String[]{null, "", "[#2089b0 FileAlloc:0B/0B]", "no numbers here"}) {
+ assertEquals(String.valueOf(l), ByteToken.UNKNOWN, Aria2ProgressLine.completedBytes(l));
+ assertEquals(String.valueOf(l), ByteToken.UNKNOWN, Aria2ProgressLine.declaredTotalBytes(l));
+ }
+ }
+
+ /**
+ * Documented, not endorsed: a --check-integrity line carries the same shape, so this parser
+ * would read verification progress as transfer progress. Harmless today because the estimate is
+ * recomputed on the next real progress line, and noted so it is a known limit rather than a
+ * surprise. If it ever matters, require DL: on the same line.
+ */
+ @Test
+ public void aChecksumLineIsCurrentlyIndistinguishable() {
+ String chk = "[#2089b0 CHK:512MiB/1.0GiB(50%)]";
+ assertEquals(512 * MI, Aria2ProgressLine.completedBytes(chk));
+ }
+
+ @Test
+ public void unitsWithoutTheBinaryMarkerStillParse() {
+ assertEquals(1000_000L, Aria2ProgressLine.completedBytes("[#x 1MB/2MB(50%)]"));
+ }
+}
diff --git a/controller/docs/ADR-4893-download-execution-and-user-control.md b/controller/docs/ADR-4893-download-execution-and-user-control.md
new file mode 100644
index 000000000..5a6104fac
--- /dev/null
+++ b/controller/docs/ADR-4893-download-execution-and-user-control.md
@@ -0,0 +1,257 @@
+# ADR-4893 — Where a download runs, and who decides when it is going badly
+
+Status: Proposed (ADFA-4893; hangs off Epic ADFA-1028). **Scope: the decision and its consequences,
+no refactor.** The area tickets do the work: **ADFA-4895** (rootfs image), **ADFA-4894** (the REST
+runners), **ADFA-4897** (the device's memory of a live run), **ADFA-4898** (maps), **ADFA-4896**
+(FQR controls), **ADFA-4899** (Portal). `operation-model-roadmap.svg`, beside this file, tracks how
+far each has got.
+
+Written after reading all five download paths rather than from the ticket text, because the ticket
+text said the paths were uniformly weak and they are not. Two of them are already where this
+document wants everything to end up, and saying so changes what is left to do.
+
+## Context
+
+K2Go downloads very large things over links it does not control: a 2–4 GB rootfs image, ZIM files
+in the tens to hundreds of GB, map layers in the tens of GB. A slow link, a network change
+mid-transfer, or simply closing the app must not cost the user hours of data.
+
+### The five paths, as they actually are
+
+| What | Class | Tool | Resumes | Verifies | Mirrors |
+|---|---|---|---|---|---|
+| rootfs image | STOPPED, on the device | bundled `libaria2c.so` + `.meta4` | `.aria2` control file, per-piece | size + SHA-256 (`DownloadVerifier`), plus `--check-integrity` per piece | yes, from the Metalink |
+| ZIM / Kiwix | LIVE, in-server | `/usr/bin/aria2c --follow-metalink=mem` | yes | `--check-integrity` | yes |
+| Maps / FQR | LIVE, in-server | `tile-extract.py` under `sudo` | *unverified* — see below | *unverified* | no |
+| Books / Gutenberg | LIVE, in-server | plain `fetch()` | no | no | no |
+| Kolibri | LIVE, in-server | Kolibri's own `importcontent` | *unknown* | *unknown* | no |
+
+**Where this table is a citation and where it is not.** The first two rows and the Books row were
+read in this repository: `Aria2Manager.java` and `MetalinkFile.java` for the rootfs,
+`sockets/kiwix.exec.ts` for ZIM, `sockets/books.exec.ts` for Books — five `fetch()` calls with no
+`AbortController`, no timeout and no `Range` anywhere in the file.
+
+The Maps row is **not** verified here. `maps.exec.ts` spawns `tile-extract.py` and parses its output;
+whether a failed run resumes is a property of that script, which does not live in this repository.
+"Restarts all three layers from zero" is ADFA-4894's claim, repeated here without confirmation.
+Read the script before acting on it.
+
+The Kolibri row is an **assumption**. `kolibri.exec.ts` spawns no binary and delegates to
+`importcontent`; what that does on a failed transfer was not investigated.
+
+The first two are the two largest transfers and they are already at the target: Metalink gives them
+several servers, per-piece hashes, resume across a kill, and an integrity gate that runs before the
+artifact is ever extracted or executed. **Nothing needs inventing for them.** The gap is entirely in
+Books, Maps and Kolibri.
+
+### The class distinction is the one we already have
+
+These are not "two stages of downloading". They are the two **execution classes** ADR-5061 already
+declared, and the download story falls exactly onto them:
+
+- **STOPPED** — no rootfs yet, or the box is down. The app itself is the downloader, spawning the
+ bundled binary. This is the rootfs image, and only this.
+- **LIVE** — the rootfs exists and the services answer. The dashboard's job engine owns the work
+ inside the container; the app only asks and observes.
+
+In the LIVE class the work is owned by the dashboard inside the container, and `jobs.ts` gives it a
+real substrate: SQLite, a `canceled` phase distinct from `error`, a `cancel()` that kills the
+tracked children, and `reconcileOnBoot()` — all verified in the file.
+
+**But the container is not independent of the app**, and an earlier draft of this document claimed
+it was. The environment proot is a child of this app's process (`EnvironmentProcessMatcher`, and
+`ServerController` reaches for `killall -9 proot`). So:
+
+- The app **backgrounded**, or its Activity gone: the proot survives. Nothing kills it —
+ ADFA-5103 documents that as a defect in the other direction.
+- The app's **process killed**: its children go with it. Android 12's phantom-process killer does
+ this deliberately, and `InstallService` already handles the resulting exit 137.
+
+So a LIVE download survives being left alone and probably does not survive a process kill.
+`reconcileOnBoot()` exists precisely because whoever wrote it expected interruption. **ADFA-4897 is
+therefore not the small ticket a previous draft here said it was** — the device's memory of what it
+asked for is one half, and the transfer's own survival is still the other. Which half dominates is
+a device question, not a reading question: kill the app mid-ZIM and see whether aria2 is still
+running.
+
+In the STOPPED class the app *is* the downloader, so process death is unambiguously fatal, and that
+is where Android's background-execution rules bite hardest.
+
+### What is measured today and thrown away
+
+Two figures already exist and neither survives its own function:
+
+- `Aria2NetworkProfiler.runTimeBoxedTest` measures six seconds of real transfer, twice (IPv4 and
+ default), in KB/s — and the result is used only to pick a flag, then discarded.
+- `Aria2Manager` parses aria2's `DL:` field on every progress line and immediately concatenates a
+ localized unit onto it, so what reaches the listener is a display string, not a number.
+
+And a third, which is the one that matters most: **aria2 prints an `ETA:` on every progress line,
+`Aria2Manager` parses it into the third argument of `onProgress(percentage, speed, eta)`, and all
+three call sites in `InstallService` drop it on the floor** (`:330`, `:488`, `:655`).
+
+ADFA-5118 (merged 12 Aug) built an estimate for the **write** side — verify and extract — with
+`EtaSmoother` to stop the label flickering across a bucket boundary, a state that carries it
+(`postVerifying(percent, message, eta)`), the layout, and the strings in all 34 locales. The
+download leg has none of that, and it is the longest of the three and the one on the worst link.
+
+**That machinery is not reused, and trying to was instructive.** The two signals are not alike: the
+extract estimate wobbles because files decompress at wildly different speeds, while a transfer rate
+over a network is comparatively steady — 34 to 40 MiB/s across a whole measured run.
+
+A first attempt did put the download through `EtaSmoother`, and the label froze at "about 26 min"
+for the first half of a download that took sixty seconds, then at "almost done" for the rest. Two
+causes, and the second is the general one: the smoother adopts its first reading immediately, and
+that reading lands while aria2 is still ramping at around 1 MB/s; and its dwell only advances while
+the bucket holds steady, so a figure that moves every tick resets the window on every tick and
+nothing ever replaces that first reading.
+
+So the download does not smooth. A steady rate produces an estimate that moves smoothly on its own,
+and moving is what an estimate is for. Verify and extract keep their smoother, because there the
+wobble is real.
+
+**We compute our own estimate rather than adopt aria2's.** aria2 prints one and we parse it, so
+taking it would be free; it is rejected because this document makes the estimate a *decision input*
+— the trigger for offering the user an action — and a black box is not a thing to decide on. With
+Metalink across several mirrors, aria2's figure can jump when a mirror drops, and we would have no
+way to tell that from the network degrading. Ours is `(total − completed) / rate`, from the figures
+aria2 already prints on the same line, with the Metalink size as the authority for the total.
+
+### What the industry does
+
+Android now has an API for precisely this shape of work: **user-initiated data transfer** (UIDT),
+API 34+, via `JobScheduler`, outside the standby-bucket job quotas. Google Maps reported a 10%
+improvement in download reliability after adopting it, together with resumable downloads. There is
+no Jetpack wrapper, so the documented approach is to gate on Android 14+ and fall back to a
+WorkManager foreground service below it.
+
+There is a deadline hiding in that: **from Android 16, long-running workers backed by foreground
+services can exhaust the app's job quota.** `InstallService` is a foreground service running for
+hours. This is not a theoretical concern for us.
+
+The wider pattern across Play Store, Steam and torrent clients is consistent, and it is the
+opposite of what a command-line downloader does: a slow transfer is never aborted. It is shown, and
+the user is offered something — Steam offers a different download region, Play Store offers
+"waiting for Wi-Fi" as a *state* rather than an error.
+
+## Decision
+
+### 1. Slowness is a condition, not an error
+
+Errors are retried. Conditions are reported, and the user is offered an action. A transfer below
+any speed we care to name is still a transfer, and on the links this product exists for, slow is
+the normal case. Nothing in the app aborts a download for being slow.
+
+Concretely: `--lowest-speed-limit` is **not** set on either aria2 invocation. It is the correct flag
+for a script and the wrong one for a person.
+
+### 2. Resume on an event, never on a timer
+
+Retrying because a precondition changed — the network came back, the user joined a different
+Wi-Fi — is correct and expected. Retrying on a clock against unchanged conditions is the loop that
+burns a metered connection while achieving nothing.
+
+This is a boundary, not a ban on all retries: aria2's own `--max-tries` / `--retry-wait`, bounded,
+operate on a single connection inside one transfer and are kept. What is excluded is the
+application relaunching a failed transfer by itself.
+
+### 3. The trigger is estimated time, not speed
+
+A rate is not actionable. "180 KiB/s" tells a user nothing; "at this rate this finishes in fourteen
+hours" tells them everything, and it already folds in the size of what they asked for.
+
+The estimate is read against the baseline the profiler measured at the start of this same transfer,
+not against an absolute floor. Twenty KiB/s means nothing on its own; twenty KiB/s where we measured
+three MiB/s ten minutes ago means the network changed under us, which is a different statement and
+a different offer.
+
+An absolute floor is kept only to avoid dividing by zero.
+
+### 4. The user decides; the app offers
+
+When the estimate crosses the threshold and stays there, the app offers — pause and switch network,
+pause and continue later, carry on. It does not act. When a new validated network appears, a paused
+transfer resumes by itself, because that is a changed precondition and the `.aria2` control file
+makes resuming nearly free.
+
+### 5. UIDT applies to the STOPPED class only
+
+The LIVE downloads already survive the app; wrapping them in a device-side job would add a second
+owner for work the dashboard already owns. The rootfs image download is the one that needs UIDT on
+API 34+, a foreground-service fallback below it, and it is the one exposed to the Android 16 quota
+change.
+
+## Options considered
+
+**A — Measure, advise, let the user act (chosen).** Matches how every consumer download product
+behaves, keeps control where the person with the context is, and costs nothing to build because the
+inputs are already computed.
+
+**B — Abort and auto-retry on a speed floor.** One flag on aria2 and a loop in the app. Rejected:
+on a genuinely slow link it turns a long download into an infinite sequence of short ones, and the
+user is never told why.
+
+**C — Do nothing; slowness is the user's problem.** The current behaviour. Rejected because the user
+cannot even see the problem: the rate is a display string, there is no estimate, and the boot gate
+gives them nothing to press.
+
+## Consequences
+
+- The boot gate stops needing to hold. A download that is pausable, has a visible estimate and
+ survives being left alone is a background job with a surface, not a modal event — which dissolves
+ state-spine findings 1 and 6 and half of 3 without touching any of them directly.
+- Two downloaders reach the target by doing nothing, and it should be said out loud on the board so
+ nobody "improves" them.
+- Books is confirmed work and it is server-side, in ADFA-4894 — currently ranked below tickets that
+ matter less. Maps probably belongs with it, pending someone reading `tile-extract.py`.
+- Kolibri delegates to `importcontent` and we do not control its transfer. Whether we wrap it or
+ accept it as opaque is an open decision with no ticket — and it cannot be taken before someone
+ establishes what `importcontent` does on a failed transfer.
+- A user who is offered "switch network" and does so must find the transfer where they left it.
+ That requires the device-side memory of ADFA-4897 even in the STOPPED class.
+
+## Action items
+
+1. Stop destroying the numeric rate, and show an estimate on the download leg. **ADFA-4895 — done.**
+ `ByteToken` reads aria2's tokens back into bytes, `Aria2ProgressLine` pulls completed and total
+ off the same line, and `DownloadEta` divides. Not aria2's own `ETA:` — see decision 3. Not
+ smoothed either, for the reason above. The display is a three-column row of its own; ADFA-5118's
+ two-column row is unchanged and still serves the two-figure lines, including the IPv4 probe.
+2. Keep the profiler's baseline instead of discarding it after the IPv4 decision, and read the rate
+ against it. **Not started**, and deliberately not carried in ADFA-4895's first PR: the comparison
+ only means something once something acts on it, and an unused helper is dead code. It arrives
+ with the offer in item 3.
+3. The control surface — pause, switch network, resume — and a `ConnectivityManager.NetworkCallback`
+ that resumes on a new validated network. **ADFA-4895**, after 1.
+4. Bring Books to a timeout, an abort wired to cancel, and a ranged resume; give Maps a per-layer
+ checkpoint. **ADFA-4894.**
+5. Device-side memory of a live run, and re-attachment on relaunch. **ADFA-4897**. Size it after the
+ device test below, not before.
+6. UIDT on API 34+ with a foreground-service fallback, for the rootfs download only. Not yet
+ ticketed; carries the Android 16 quota exposure.
+7. Decide Kolibri: wrap `importcontent` or accept it as opaque. Not yet ticketed.
+
+### Open before any of this is acted on
+
+Three claims above are not verified, and each one changes what its area ticket is worth:
+
+- **Does a LIVE download survive the app's process being killed?** Kill the app mid-ZIM and check
+ whether aria2 is still running inside the container. This sizes ADFA-4897 and nothing else can.
+- **Does `tile-extract.py` resume?** It is not in this repository. This decides whether Maps is a
+ checkpoint problem or already fine.
+- **What does Kolibri's `importcontent` do on a failed transfer?** This decides whether there is
+ anything to wrap.
+
+None needs a large investigation. All three are cheap, and all three are load-bearing.
+
+## References
+
+- `controller/docs/ADR-5061-rest-vs-proot-operation-model.md` — the execution classes this reuses.
+- `controller/docs/ADR-4832-live-content-channel.md` — the three aria2 flag sets that must stay
+ aligned.
+- `controller/docs/state-spine.svg` — findings 1, 3 and 6.
+- `controller/docs/operation-model-roadmap.svg` — where each area ticket has got to.
+- [User-initiated data transfer](https://developer.android.com/develop/background-work/background-tasks/uidt)
+- [Google Maps improved download reliability by 10% using the UIDT API](https://android-developers.googleblog.com/2024/09/google-maps-improved-download-reliability-user-initiated-data-transfer-api.html)
+- [Changes to foreground services](https://developer.android.com/develop/background-work/services/fgs/changes)
+- [Data transfer background task options](https://developer.android.com/about/versions/15/changes/datasync-migration)
diff --git a/controller/docs/operation-model-roadmap.svg b/controller/docs/operation-model-roadmap.svg
index 0ddb13132..86f4463da 100644
--- a/controller/docs/operation-model-roadmap.svg
+++ b/controller/docs/operation-model-roadmap.svg
@@ -1,4 +1,4 @@
-