diff --git a/CLAUDE.md b/CLAUDE.md
index 7bbb540fb..0b1e7dd60 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -334,6 +334,24 @@ One source per fact: the app ABI and the installed library's ABI (ADR-K2GO-571).
(`DeepOpService`), backup identity + name (`BackupEngine`), 64-bit-only module gate
(`ModuleCards.runsOn`), fresh-install arch (`SystemStateEvaluator.termuxArch`).
+**Standard flow (K2GO-593): proot module install progress and download**
+Maps (K2GO-394) and Forgejo use it; a new proot module follows it.
+
+- `install/domain/`: `ModuleDownloadProgress` (the download bar state), `DownloadHold` (hold a box
+ download on mobile data with no consent or with Keep offline; reuses `NetworkPolicy`),
+ `ForgejoBinaryPin` (the version pin of one run). Pure JVM, unit-tested.
+- `install/presentation/`: `ModuleDownload` owns one dash-node download job (start, pause, resume,
+ cancel, hold; "who stopped it" lives only here). `ModuleDownloadRepository` is the one source of
+ the download bar; `ModuleQueueRepository` stays the one source of the install bar.
+ `InstallService.postModuleStart` is the one rule: a role with a task table starts at 0% before its
+ download, so both bars show.
+- `redesign/ModuleProgressPanel` + `view_k2go_module_progress`: install bar over download card, the
+ same on every install screen; it keeps no state.
+- dash-node: the download runs before `pdsm stop` (the stop also stops dash-node); the box resolves
+ the URL and checks the file (`sockets/forgejo-bin.exec.ts`).
+- A new module with a download: a dash-node job type, a pre-download step in `InstallService`, a
+ task table in `assets/runrole/`, and the panel in its screen.
+
**Legacy (NOT yet layered)**: the redesign retired the original god classes
`MainActivity` and `DeployFragment` (they no longer exist; DONE-slice seams above
that still name them are pre-redesign records). The current god-tier classes,
diff --git a/controller/app/src/main/assets/runrole/forgejo.txt b/controller/app/src/main/assets/runrole/forgejo.txt
new file mode 100644
index 000000000..fa7d1e591
--- /dev/null
+++ b/controller/app/src/main/assets/runrole/forgejo.txt
@@ -0,0 +1,47 @@
+Assert that "forgejo_install is sameas true" (boolean not string etc)
+Assert that "forgejo_enabled | type_debug == 'bool'" (boolean not string etc)
+Install Forgejo if 'forgejo_installed' not defined, e.g. in /etc/iiab/iiab_state.yml
+Assert forgejo_db_engine is a supported value ('sqlite' or 'mariadb')
+Query Codeberg for the latest Forgejo release
+Set forgejo_version from the latest release tag
+Assert forgejo_version is a valid X.Y.Z release
+Record (initial) disk space used
+Stop existing Forgejo systemd service (if reinstalling, not proot)
+Stop existing Forgejo via pdsm (if reinstalling, proot)
+Ensure group 'forgejo' exists
+Create user 'forgejo'
+Create /library/forgejo directory structure
+Make directories data, log, backups writable (0750)
+Check whether Forgejo is already installed (app.ini present)
+Detect the existing install's DB engine (engine-change guard)
+Refuse an unsupported DB engine change on an existing install
+Compute a backup timestamp (proot-safe, no fact dependency)
+Back up Forgejo (forgejo dump) to /library/forgejo/backups before swapping the binary
+Fail if we detect an unsupported CPU architecture
+Verify the downloaded Forgejo binary against its GPG signature (fail closed)
+Find installed Forgejo binaries in /library/forgejo/bin
+mkdir /etc/forgejo (0770 root:forgejo)
+Generate Forgejo secrets once (guarded by 'creates'), referenced by *_URI in app.ini
+Secure the generated secret files (0640 root:forgejo)
+Set 'mysql_install: True' and 'mysql_enabled: True'
+MYSQL - run 'mysql' role
+FAIL (STOP THE INSTALL) IF 'mysql_installed is undefined'
+Create MySQL database for Forgejo: forgejo
+Create MySQL username (forgejo) with password, for above database
+Install /etc/forgejo/app.ini from template (0664 root:forgejo)
+Install systemd unit /etc/systemd/system/forgejo.service (not proot)
+Record (final) disk space used
+Set 'forgejo_installed: True'
+Add 'forgejo_installed: True' to /etc/iiab/iiab_state.yml
+Enable/Disable Forgejo (systemd or pdsm) and NGINX
+Enable & Restart 'forgejo' systemd service, if forgejo_enabled (not proot)
+Disable & Stop 'forgejo' systemd service, if not forgejo_enabled (not proot)
+Enable 'forgejo' via pdsm (proot)
+Restart 'forgejo' via pdsm (proot)
+Stop 'forgejo' via pdsm (proot)
+Disable 'forgejo' via pdsm (proot)
+Enable http://box/forgejo via NGINX, by installing /etc/nginx/conf.d/forgejo-nginx.conf from template
+Disable http://box/forgejo via NGINX, by removing /etc/nginx/conf.d/forgejo-nginx.conf
+Reload 'nginx' systemd service (not proot)
+Restart 'nginx' via pdsm (proot)
+Add 'forgejo' variable values to /etc/iiab/iiab.ini
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java b/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java
index e7ac18dfb..fca3598db 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirement.java
@@ -7,9 +7,9 @@
* and the box read live elsewhere (redesign.DashboardVersion), so this stays a plain,
* unit-testable registry with no Android or network dependency.
*
- * Forgejo needs the dashboard build that ships its repo status/refresh endpoints (1.3.7):
- * an older dash-node makes "Install repos"/"Update repos" and the seed break silently, so
- * installing Forgejo is HARD-blocked below that version. Code on the Go add-ons (K2GO-99)
+ * Forgejo needs the dashboard build that ships its repo status/refresh endpoints (1.3.7)
+ * and the forgejo-bin download job (1.6.5, K2GO-593): an older dash-node breaks the
+ * install, so installing Forgejo is HARD-blocked below that version. Code on the Go add-ons (K2GO-99)
* needs the dashboard build that ships the /addons/refresh endpoints (1.3.8), so the gallery
* can update, so it is HARD-blocked below that version too. Other modules have no hard minimum
* (a soft "update the dashboard" suggestion applies to all installs, handled in the gate).
@@ -25,7 +25,8 @@ private DashNodeRequirement() {}
/** {major, minor, patch} minimum dash-node for {@code moduleKey}, or null when it has no hard minimum. */
@Nullable
public static int[] minFor(@Nullable String moduleKey) {
- if ("forgejo".equals(moduleKey)) return new int[]{1, 3, 7};
+ // K2GO-593: 1.6.5 has the forgejo-bin job, which downloads the binary before the install.
+ if ("forgejo".equals(moduleKey)) return new int[]{1, 6, 5};
if ("code_addons".equals(moduleKey)) return new int[]{1, 3, 8}; // K2GO-99: needs /addons/refresh
// K2GO-437: code_assets install (runrole) and browsing (WebView) do NOT use the dash-node
// refresh endpoints; only the "Update build assets" action does, and it degrades gracefully
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java
new file mode 100644
index 000000000..96c5312e8
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/DownloadHold.java
@@ -0,0 +1,66 @@
+/*
+ * ============================================================================
+ * Name : DownloadHold.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-593. When the app must stop a module download on the box
+ * because of the network, and when it may continue it. Pure JVM.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.domain;
+
+import org.appdevforall.k2go.networkpolicy.domain.NetworkClass;
+import org.appdevforall.k2go.networkpolicy.domain.NetworkPolicy;
+import org.appdevforall.k2go.networkpolicy.domain.NetworkPolicyDecision;
+
+/**
+ * The box downloads on the phone's default network, and its aria2 retry loop continues on mobile
+ * data after a Wi-Fi drop, with no question (seen on a Samsung A16 with 4G). The start gate
+ * (NetworkPolicyGate) asks only at the start. This rule is the in-flight half: hold the download while
+ * the network may not be used, and continue it when it may.
+ *
+ *
A pause by the user is the user's decision: a network event never continues it, and this rule
+ * never holds it again. No network at all is not a hold: the box reconnects on its own, and there is
+ * no traffic to stop.
+ */
+public final class DownloadHold {
+
+ private DownloadHold() {}
+
+ /** Who stopped the download, if somebody did. */
+ public enum StoppedBy { NOBODY, USER, NETWORK }
+
+ /** Why the download is held. */
+ public enum Reason { METERED_NO_CONSENT, KEPT_OFFLINE }
+
+ /** What the caller does now. */
+ public enum Action { NONE, HOLD, CONTINUE }
+
+ /**
+ * @param net cost class of the default network now
+ * @param meteredConsent the user allowed mobile data for this session
+ * @param onlineAllowed the user allows module installs to connect (online, or allowed this time)
+ * @param stoppedBy who stopped the download, if somebody did
+ */
+ public static Action decide(NetworkClass net, boolean meteredConsent, boolean onlineAllowed,
+ StoppedBy stoppedBy) {
+ if (stoppedBy == StoppedBy.USER || net == NetworkClass.NONE) return Action.NONE;
+ boolean mayRun = reason(net, meteredConsent, onlineAllowed) == null;
+ if (stoppedBy == StoppedBy.NOBODY) return mayRun ? Action.NONE : Action.HOLD;
+ return mayRun ? Action.CONTINUE : Action.NONE;
+ }
+
+ /**
+ * Why the network may not be used now, or null when it may. The mobile data rule is the start
+ * gate's own rule (NetworkPolicy), so the start and the in-flight check cannot disagree.
+ */
+ public static Reason reason(NetworkClass net, boolean meteredConsent, boolean onlineAllowed) {
+ if (!onlineAllowed) return Reason.KEPT_OFFLINE;
+ if (POLICY.decideHeavyStart(net, meteredConsent) == NetworkPolicyDecision.NEEDS_CONSENT) {
+ return Reason.METERED_NO_CONSENT;
+ }
+ return null;
+ }
+
+ private static final NetworkPolicy POLICY = new NetworkPolicy();
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java
new file mode 100644
index 000000000..0e8a6ad61
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPin.java
@@ -0,0 +1,81 @@
+/*
+ * ============================================================================
+ * Name : ForgejoBinaryPin.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-593. The local_vars line that makes the forgejo role use
+ * the binary that dash-node downloaded. Pure JVM.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.domain;
+
+/**
+ * dash-node downloads the Forgejo binary to {@code /library/forgejo/bin/forgejo-} (job type
+ * {@code forgejo-bin}). The role resolves {@code forgejo_version: latest} on its own, so the app pins
+ * the version that dash-node got, and the role's get_url finds the file and skips its download. The
+ * role then still checks the GPG signature of the file.
+ *
+ *
The pin is for this one run: a later update must resolve the newest release again. So the line
+ * carries a marker, and {@link #UNPIN} removes only the marked line, never a pin the owner wrote.
+ * The version comes from the box, and it goes into a root shell command, so it is checked here first.
+ */
+public final class ForgejoBinaryPin {
+
+ private ForgejoBinaryPin() {}
+
+ /** The module that owns this download. */
+ public static final String MODULE = "forgejo";
+ /** The dash-node job type. */
+ public static final String JOB_TYPE = "forgejo-bin";
+
+ private static final String MARKER = "# k2go-forgejo-bin";
+ private static final String LOCAL_VARS = "/etc/iiab/local_vars.yml";
+
+ /** Removes the marked pin. Safe to run when there is none. */
+ public static final String UNPIN = "sed -i '/" + MARKER + "$/d' " + LOCAL_VARS;
+
+ /** The role's assert: X.Y.Z. */
+ public static boolean isVersion(String v) {
+ return v != null && v.matches("[0-9]+\\.[0-9]+\\.[0-9]+");
+ }
+
+ /**
+ * The forgejo_version that the owner wrote in local_vars (a line without the marker), or null when
+ * there is none or it is "latest". With an owner pin the app does not download: the role
+ * downloads the version the owner chose, as before.
+ */
+ public static String ownerPin(java.util.List localVarsLines) {
+ if (localVarsLines == null) return null;
+ String pin = null;
+ for (String raw : localVarsLines) {
+ if (raw == null || raw.trim().endsWith(MARKER)) continue;
+ java.util.regex.Matcher m = OWNER_LINE.matcher(raw);
+ if (m.matches()) pin = m.group(1); // the last one wins, as in YAML
+ }
+ return pin == null || "latest".equals(pin) ? null : pin;
+ }
+
+ private static final java.util.regex.Pattern OWNER_LINE = java.util.regex.Pattern.compile(
+ "^forgejo_version[ \\t]*:[ \\t]*[\"']?([^\"'#\\s]+)[\"']?[ \\t]*(#.*)?$");
+
+ /**
+ * The batch order with Forgejo first. Its download runs before the server stop, while its row
+ * already runs, so a module before it in the list would look done. The others keep their order.
+ */
+ public static String[] downloadFirst(String[] modules) {
+ if (modules == null) return null;
+ java.util.List out = new java.util.ArrayList<>(modules.length);
+ for (String m : modules) if (MODULE.equals(m)) out.add(m);
+ for (String m : modules) if (!MODULE.equals(m)) out.add(m);
+ return out.toArray(new String[0]);
+ }
+
+ /**
+ * The shell command that pins {@code version}, or null when the version is not X.Y.Z. A pin that a
+ * killed run left is removed first, so there is never more than one marked line.
+ */
+ public static String pinCommand(String version) {
+ if (!isVersion(version)) return null;
+ return UNPIN + " && echo 'forgejo_version: \"" + version + "\" " + MARKER + "' >> " + LOCAL_VARS;
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java
new file mode 100644
index 000000000..11668d456
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgress.java
@@ -0,0 +1,115 @@
+/*
+ * ============================================================================
+ * Name : ModuleDownloadProgress.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-394, K2GO-593. The download that a module install does
+ * through dash-node before its role (maps base maps, the Forgejo
+ * binary), as the download bar needs it. Pure JVM.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.domain;
+
+/**
+ * A snapshot of a module's download for the download bar. The download runs as a dash-node job, so
+ * this is built from the REST poll fields ({@code RestContentClient.Listener}): a phase, a percent, a
+ * speed token, the time left and the reconnect counter. The rule for "which phase" lives here, not in
+ * the UI.
+ */
+public final class ModuleDownloadProgress {
+
+ /**
+ * The states the download bar shows. RECONNECTING is a network drop that the box rides out. HELD
+ * is a stop that the app made because the network may not be used now (mobile data with no
+ * consent, or Keep offline); it continues on Wi-Fi or after the user allows it.
+ */
+ public enum Phase { NONE, ACTIVE, PAUSED, HELD, RECONNECTING, COMPLETE }
+
+ public final Phase phase;
+ /** The module key that owns the download ("maps", "forgejo"), or null for NONE. */
+ public final String module;
+ /** 0..100, or -1 when not known yet. */
+ public final int percent;
+ /** Display token for the rate WITHOUT the per-second suffix (e.g. "3.4 MB"); the UI appends "/s". */
+ public final String speed;
+ /** Seconds left, or -1 when not known. */
+ public final long etaSeconds;
+ /** Reconnect counter for "Reconnecting n of N"; both 0 when not reconnecting. */
+ public final int reconnectAttempt;
+ public final int reconnectTotal;
+ /** Why the download is HELD; null in the other phases. */
+ public final DownloadHold.Reason holdReason;
+
+ private ModuleDownloadProgress(Phase phase, String module, int percent, String speed, long eta,
+ int attempt, int total, DownloadHold.Reason holdReason) {
+ this.phase = phase;
+ this.module = module;
+ this.percent = percent < 0 ? -1 : Math.min(100, percent);
+ this.speed = speed != null ? speed : "";
+ this.etaSeconds = eta < 0 ? -1 : eta;
+ this.reconnectAttempt = Math.max(0, attempt);
+ this.reconnectTotal = Math.max(0, total);
+ this.holdReason = holdReason;
+ }
+
+ /** Nothing is downloading: before the job starts, or after it ends. */
+ public static ModuleDownloadProgress none() {
+ return new ModuleDownloadProgress(Phase.NONE, null, -1, "", -1, 0, 0, null);
+ }
+
+ /** A live download at {@code percent} moving at {@code speed} (a display token, no "/s"). */
+ public static ModuleDownloadProgress active(String module, int percent, String speed, long etaSeconds) {
+ return new ModuleDownloadProgress(Phase.ACTIVE, module, percent, speed, etaSeconds, 0, 0, null);
+ }
+
+ /** The user paused the download; the partial is kept and Resume continues from it. */
+ public static ModuleDownloadProgress paused(String module, int percent) {
+ return new ModuleDownloadProgress(Phase.PAUSED, module, percent, "", -1, 0, 0, null);
+ }
+
+ /** The app stopped the download for {@code reason}; the partial is kept. */
+ public static ModuleDownloadProgress held(String module, int percent, DownloadHold.Reason reason) {
+ return new ModuleDownloadProgress(Phase.HELD, module, percent, "", -1, 0, 0, reason);
+ }
+
+ /** The box lost the network and reconnects (attempt n of total), keeping the partial. */
+ public static ModuleDownloadProgress reconnecting(String module, int attempt, int total) {
+ return new ModuleDownloadProgress(Phase.RECONNECTING, module, -1, "", -1, attempt, total, null);
+ }
+
+ /** The download finished. */
+ public static ModuleDownloadProgress complete(String module) {
+ return new ModuleDownloadProgress(Phase.COMPLETE, module, 100, "", 0, 0, 0, null);
+ }
+
+ public boolean isActive() {
+ return phase == Phase.ACTIVE;
+ }
+
+ public boolean isPaused() {
+ return phase == Phase.PAUSED;
+ }
+
+ public boolean isHeld() {
+ return phase == Phase.HELD;
+ }
+
+ public boolean isReconnecting() {
+ return phase == Phase.RECONNECTING;
+ }
+
+ public boolean isComplete() {
+ return phase == Phase.COMPLETE;
+ }
+
+ /** Whether there is a download to show a bar for (active, paused, held or reconnecting). */
+ public boolean isRunning() {
+ return phase == Phase.ACTIVE || phase == Phase.PAUSED || phase == Phase.HELD
+ || phase == Phase.RECONNECTING;
+ }
+
+ /** Whether this snapshot is the download of {@code moduleKey}. */
+ public boolean isFor(String moduleKey) {
+ return module != null && module.equals(moduleKey);
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java
index a459d7177..89320f473 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/InstallService.java
@@ -47,6 +47,7 @@
import org.appdevforall.k2go.download.domain.DownloadRetryPolicy;
import org.appdevforall.k2go.install.data.InstallStateStore;
import org.appdevforall.k2go.install.domain.AnsibleRunOutcome;
+import org.appdevforall.k2go.install.domain.ForgejoBinaryPin;
import org.appdevforall.k2go.sync.transport.NetworkStateLiveData;
import java.io.BufferedReader;
@@ -206,9 +207,12 @@ public final class InstallService extends Service {
private static String sRetryMapsVector, sRetryMapsSat, sRetryMapsTerrain;
private static boolean sRetryMapsSearch;
private boolean mapsSearchOn;
- // K2GO-394: the base-map download client for the maps module (dash-node "basemaps" job). Held so
- // the UI's Pause/Resume/Cancel reach the in-flight download; null when nothing is downloading.
- private volatile org.appdevforall.k2go.content.RestContentClient mapsClient;
+ // K2GO-394, K2GO-593: the module download through dash-node (maps base maps, the Forgejo binary).
+ // Held so the UI's Pause/Resume/Cancel reach it; null when nothing downloads.
+ private volatile ModuleDownload moduleDownload;
+ // K2GO-593: the Forgejo version that dash-node downloaded, which the forgejo runrole pins. "" when
+ // the download did not give one (the role then downloads by itself); null before the download.
+ private volatile String forgejoPinVersion;
private File iiabRootDir; // filesDir/rootfs
private File debianRootfs; // filesDir/rootfs/installed-rootfs/iiab
@@ -238,6 +242,9 @@ public void onCreate() {
*/
private void onValidatedNetworkReturned() {
if (finished || cancelled) return;
+ // K2GO-593: a module download holds on mobile data with no consent and continues on Wi-Fi.
+ ModuleDownload md = moduleDownload;
+ if (md != null) md.evaluate();
// K2GO-394: the maps base-map download is NOT driven from here -- dash-node owns its transport
// resilience (its "basemaps" job re-runs aria2 with --continue and reports "Reconnecting n/5"),
// the same self-healing path as ZIMs. The app just polls it. The manual Pause/Resume button
@@ -332,6 +339,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
// recreation (theme toggle / rotation) and can never launch two concurrent runroles.
String[] mods = intent.getStringArrayExtra(EXTRA_MODULES);
moduleQueue = new java.util.ArrayDeque<>();
+ forgejoPinVersion = null; // K2GO-593: each batch downloads (or finds) the binary again
if (mods != null) {
for (String m : mods) if (m != null && !m.isEmpty()) moduleQueue.add(m);
}
@@ -865,6 +873,18 @@ private void runModuleQueue() {
boolean anyRealModule = false;
for (String m : moduleQueue) if (!"maps".equals(m)) { anyRealModule = true; break; }
if (!anyRealModule) { installNextModule(); return; }
+ // K2GO-593: pdsm stop also stops dash-node, so its download must end before the stop.
+ if (moduleQueue.contains(ForgejoBinaryPin.MODULE) && forgejoPinVersion == null) {
+ String ownerPin = ForgejoBinaryPin.ownerPin(readLocalVars());
+ if (ownerPin != null) {
+ // The owner chose a version: the role downloads that one, as before.
+ log("[forgejo] local_vars pins forgejo_version " + ownerPin + "; the role downloads the binary");
+ forgejoPinVersion = "";
+ } else {
+ downloadForgejoBinaryThen(this::runModuleQueue);
+ return;
+ }
+ }
updateNotification(getString(R.string.server_shutting_down));
log("[Modules] Stopping server services before runroles (exclusive rootfs)...");
if (prootEngine == null) prootEngine = new PRootEngine();
@@ -939,18 +959,22 @@ private void installNextModule() {
final long startMs = System.currentTimeMillis();
final int remainingSnapshot = moduleQueue.size();
final int[] lastPct = { Integer.MIN_VALUE };
- if (progress.hasTable()) {
- ModuleQueueRepository.get().postRunning(nextModule, remainingSnapshot, 0);
- }
+ if (progress.hasTable()) postModuleStart(nextModule, remainingSnapshot, true);
// ADFA-4900: for the wizard maps flow, write the full per-layer maps_* var set before
// runrole (the generic _install/_enabled echo can't express quality/off/search).
- final String runroleCmd = ("maps".equals(nextModule) && hasMapsConfig)
+ final String plainCmd = ("maps".equals(nextModule) && hasMapsConfig)
? mapsInstallCmd()
: "sed -i -E '/^[[:space:]]*" + nextModule + "_(install|enabled)[[:space:]]*:/d' /etc/iiab/local_vars.yml && " +
"echo '" + nextModule + "_install: True' >> /etc/iiab/local_vars.yml && " +
"echo '" + nextModule + "_enabled: True' >> /etc/iiab/local_vars.yml && " +
"cd /opt/iiab/iiab && ./runrole " + roleName;
+ // K2GO-593: pin the version that dash-node downloaded, for this run only, so the role uses that
+ // file. pinCommand is null for a version that is not X.Y.Z: then the role downloads by itself.
+ final String pin = ForgejoBinaryPin.MODULE.equals(nextModule)
+ ? ForgejoBinaryPin.pinCommand(forgejoPinVersion) : null;
+ final String runroleCmd = pin == null ? plainCmd
+ : pin + " && " + plainCmd + " ; rc=$? ; " + ForgejoBinaryPin.UNPIN + " ; exit $rc";
// K2GO-464: refresh the stale rootfs apt index before the runrole, or a pinned dep 404s as the
// box ages. Best-effort (short timeout, || true) so an offline/local-only install still runs.
// K2GO-593: a Cancel SIGKILLs the runrole, also during dpkg; finish any interrupted dpkg first.
@@ -1077,8 +1101,9 @@ private void revertModuleInLocalVars(String module, Runnable then) {
String revertCmd = "sed -i -E '/^[[:space:]]*" + module + "_(install|enabled)[[:space:]]*:/d' /etc/iiab/local_vars.yml && " +
"echo '" + module + "_install: False' >> /etc/iiab/local_vars.yml && " +
"echo '" + module + "_enabled: False' >> /etc/iiab/local_vars.yml ; " +
- // K2GO-593: a killed runrole leaves its task dirs (a partial download) behind.
- "rm -rf /root/.ansible/tmp/ansible-tmp-*";
+ // K2GO-593: a killed runrole leaves its task dirs (a partial download) behind, and
+ // the forgejo version pin of that run.
+ "rm -rf /root/.ansible/tmp/ansible-tmp-* ; " + ForgejoBinaryPin.UNPIN;
prootEngine.executeInContainer(this, debianRootfs.getAbsolutePath(), revertCmd, new PRootEngine.OutputListener() {
@Override public void onOutputLine(String line) { }
@Override public void onProcessExit(int exitCode) { then.run(); }
@@ -1274,35 +1299,16 @@ private void downloadMapsBasemapsThenRun(String module, Runnable onReady) {
}
log("[maps] downloading " + ids.size() + " base-map file(s) via dash-node: "
+ android.text.TextUtils.join(", ", ids));
- final org.appdevforall.k2go.content.RestContentClient client =
- new org.appdevforall.k2go.content.RestContentClient("basemaps");
- mapsClient = client;
- client.start(body, new org.appdevforall.k2go.content.RestContentClient.Listener() {
- @Override public void onProgress(int percent, String speed) {
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().post(
- org.appdevforall.k2go.maps.domain.MapsDownloadProgress.active(percent, speed));
- }
- @Override public void onReconnecting(int attempt, int total) {
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().post(
- org.appdevforall.k2go.maps.domain.MapsDownloadProgress.reconnecting(attempt, total));
- }
- @Override public void onPaused(int percent) {
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().post(
- org.appdevforall.k2go.maps.domain.MapsDownloadProgress.paused(percent));
- }
- @Override public void onIndexing() { /* base maps have no index phase */ }
- @Override public void onLog(String line) { log("[maps-dl] " + line); }
- @Override public void onDone() {
- mapsClient = null;
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().clear();
+ moduleDownload = new ModuleDownload(this, module, "basemaps", body, new ModuleDownload.Callback() {
+ @Override public void onDone(org.json.JSONObject result) {
+ moduleDownload = null;
if (cancelled) return;
log("[maps] base-map download complete; running the role");
// Keep the runrole off the poll's main-thread callback (it reads assets / prefs).
org.appdevforall.k2go.util.AppExecutors.get().io().execute(onReady);
}
@Override public void onError(String message) {
- mapsClient = null;
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().clear();
+ moduleDownload = null;
if (cancelled) return;
failedModules.add(module);
log("[Install] FAILED: " + module + " base-map download (" + message + ")");
@@ -1312,7 +1318,81 @@ private void downloadMapsBasemapsThenRun(String module, Runnable onReady) {
org.appdevforall.k2go.util.AppExecutors.get().io().execute(
() -> revertModuleInLocalVars(module, InstallService.this::finishModuleQueue));
}
- });
+ }, this::log);
+ moduleDownload.start();
+ }
+
+ /**
+ * K2GO-593: the one rule for the install bar when a module starts, before its download (if it has
+ * one) and before its role. A role with a task table starts the bar at 0%, so the install bar and
+ * the download card show together (the maps pattern, K2GO-394); with no table the module runs with
+ * no percent. The bar then moves only from the role's task stream.
+ */
+ private void postModuleStart(String module, int remaining, boolean hasTaskTable) {
+ if (hasTaskTable) ModuleQueueRepository.get().postRunning(module, remaining, 0);
+ else ModuleQueueRepository.get().postRunning(module, remaining);
+ }
+
+ /** The lines of the box's local_vars.yml, or an empty list when it cannot be read. */
+ private java.util.List readLocalVars() {
+ // Not java.nio.file: it is API 26, and minSdk is 24.
+ java.util.List lines = new java.util.ArrayList<>();
+ try (BufferedReader r = new BufferedReader(new InputStreamReader(new java.io.FileInputStream(
+ new File(debianRootfs, "etc/iiab/local_vars.yml")), java.nio.charset.StandardCharsets.UTF_8))) {
+ String line;
+ while ((line = r.readLine()) != null) lines.add(line);
+ } catch (Exception e) {
+ return java.util.Collections.emptyList();
+ }
+ return lines;
+ }
+
+ /**
+ * K2GO-593: download the Forgejo binary through dash-node (job "forgejo-bin") while the server is
+ * still up, then run {@code then}. The box resolves the version and writes the file where the role
+ * looks for it; the forgejo runrole pins that version, so its get_url skips the download and its GPG
+ * check verifies the file. A failed download fails only Forgejo (Retry is offered) and the other
+ * modules of the batch still install. No local_vars edit was made yet, so nothing is reverted.
+ */
+ private void downloadForgejoBinaryThen(Runnable then) {
+ final String module = ForgejoBinaryPin.MODULE;
+ org.json.JSONObject body;
+ try {
+ body = new org.json.JSONObject().put("ids", new org.json.JSONArray().put(module));
+ } catch (org.json.JSONException e) {
+ throw new IllegalStateException(e); // a literal body cannot fail
+ }
+ log("[forgejo] downloading the Forgejo binary via dash-node before the install");
+ // The download is part of the Forgejo install: its row runs, opens the card, and can cancel.
+ postModuleStart(module, Math.max(0, moduleQueue.size() - 1),
+ !RunroleTables.tasksFor(this, org.appdevforall.k2go.deploy.domain.RoleNames.roleFor(module)).isEmpty());
+ moduleDownload = new ModuleDownload(this, module, ForgejoBinaryPin.JOB_TYPE, body, new ModuleDownload.Callback() {
+ @Override public void onDone(org.json.JSONObject result) {
+ moduleDownload = null;
+ if (cancelled) return;
+ String version = result != null ? result.optString("version", "") : "";
+ if (ForgejoBinaryPin.isVersion(version)) {
+ log("[forgejo] binary " + version + " is ready; the role uses it");
+ } else {
+ log("[forgejo] WARNING: no valid version from the box; the role downloads the binary");
+ version = "";
+ }
+ forgejoPinVersion = version;
+ org.appdevforall.k2go.util.AppExecutors.get().io().execute(then);
+ }
+ @Override public void onError(String message) {
+ moduleDownload = null;
+ if (cancelled) return;
+ log("[Install] FAILED: " + module + " download (" + message + ")");
+ failedModules.add(module);
+ org.appdevforall.k2go.analytics.AnalyticsClient.with(InstallService.this).logModuleInstall(module, false);
+ moduleQueue.remove(module);
+ persistQueue();
+ forgejoPinVersion = "";
+ org.appdevforall.k2go.util.AppExecutors.get().io().execute(then);
+ }
+ }, this::log);
+ moduleDownload.start();
}
/**
@@ -1466,12 +1546,11 @@ private String formatEta(int bucket) {
*/
private void doPause() {
if (finished || cancelled) return;
- // K2GO-394: a maps base-map download pauses through dash-node (the "basemaps" job), not the
- // rootfs aria2 the checks below govern. The poll reflects the paused state on the download bar.
- org.appdevforall.k2go.content.RestContentClient pauseClient = mapsClient;
- if (pauseClient != null) {
- log("[maps] pause requested");
- pauseClient.pause();
+ // K2GO-394, K2GO-593: a module download pauses through dash-node, not the rootfs aria2 that the
+ // checks below govern.
+ ModuleDownload pauseDownload = moduleDownload;
+ if (pauseDownload != null) {
+ pauseDownload.pause();
return;
}
if (!InstallProgressRepository.get().current().isRunning()) return;
@@ -1645,11 +1724,10 @@ private static int softFailLine(org.appdevforall.k2go.download.domain.Aria2Exit.
*/
private void doResume() {
if (finished || cancelled) return;
- // K2GO-394: resume a maps download through dash-node (aria2 --continue picks up the partial).
- org.appdevforall.k2go.content.RestContentClient resumeClient = mapsClient;
- if (resumeClient != null) {
- log("[maps] resume requested");
- resumeClient.resume();
+ // K2GO-394, K2GO-593: resume a module download through dash-node (aria2 --continue).
+ ModuleDownload resumeDownload = moduleDownload;
+ if (resumeDownload != null) {
+ resumeDownload.resume();
return;
}
if (!InstallProgressRepository.get().current().isHeld()) return;
@@ -1711,7 +1789,11 @@ private void doCancel() {
// server was pdsm-stopped for the runroles) is not raced by teardown's later clear.
// K2GO-593: during pdsm stop no module is current yet; the cancel stops the first one.
final String running = ModuleQueueRepository.get().current().currentModule;
- final String cur = running != null ? running : (moduleQueue != null ? moduleQueue.peek() : null);
+ // K2GO-593: a cancel during the download before the stop cancels the module that downloads.
+ final ModuleDownload downloading = moduleDownload;
+ final String cur = running != null ? running
+ : downloading != null ? downloading.module()
+ : (moduleQueue != null ? moduleQueue.peek() : null);
stopModuleStallWatch(); // ADFA-4898 P4
// K2GO-593: SIGKILL, not SIGTERM. On SIGTERM proot stayed up and the runrole kept downloading.
if (prootEngine != null) prootEngine.forceKill();
@@ -1842,10 +1924,10 @@ private void teardown(boolean clearMarker) {
// ADFA-5119: nothing to wait for once this is over — neither the window nor a queued attempt.
cancelHeldWindow();
cancelPendingRetry();
- // K2GO-394: cancel an in-flight base-map download and clear its bar.
- org.appdevforall.k2go.content.RestContentClient mc = mapsClient;
- if (mc != null) { mc.cancel(); mapsClient = null; }
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().clear();
+ // K2GO-394, K2GO-593: cancel an in-flight module download (the box removes its partial).
+ ModuleDownload md = moduleDownload;
+ if (md != null) { md.cancel(); moduleDownload = null; }
+ ModuleDownloadRepository.get().clear();
if (clearMarker) {
org.appdevforall.k2go.InstallGuard.end(this);
} else {
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java
new file mode 100644
index 000000000..df7b14c41
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownload.java
@@ -0,0 +1,248 @@
+/*
+ * ============================================================================
+ * Name : ModuleDownload.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-394, K2GO-593. One module download through a dash-node job
+ * (maps base maps, the Forgejo binary): start, pause, resume,
+ * cancel, the hold on mobile data, and the download bar state.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.presentation;
+
+import android.content.Context;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import org.appdevforall.k2go.content.RestContentClient;
+import org.appdevforall.k2go.install.domain.DownloadHold;
+import org.appdevforall.k2go.install.domain.ModuleDownloadProgress;
+import org.appdevforall.k2go.networkpolicy.data.AndroidNetworkClassifier;
+import org.appdevforall.k2go.networkpolicy.data.OnlineAllowance;
+import org.appdevforall.k2go.networkpolicy.data.SessionMeteredConsentStore;
+import org.json.JSONObject;
+
+/**
+ * Owns one dash-node download job for {@link InstallService}: the REST client, who stopped it, and the
+ * download bar ({@link ModuleDownloadRepository}). The box owns the transfer (aria2, resume,
+ * "Reconnecting n/5"); this class only adds what the box cannot know: whether the phone's network may
+ * be used now ({@link DownloadHold}).
+ *
+ *
"Who stopped it" is the one fact that only the app has: dash-node shows a user pause and a hold
+ * the same way ('paused'). It lives here, for the life of this download, and nowhere else. The process
+ * dies with the service that owns this object, and the next run re-attaches to the job
+ * (RestContentClient) and resumes a paused job that nobody here stopped.
+ *
+ *
All methods are synchronized: the poll and the network callback run on the main thread, the
+ * start runs on the queue thread.
+ */
+public final class ModuleDownload {
+
+ interface Callback {
+ /** The job finished. {@code result} is the job's result, or null. Runs on the main thread. */
+ void onDone(@Nullable JSONObject result);
+
+ /** The job failed or was canceled on the box. Runs on the main thread. */
+ void onError(@NonNull String message);
+ }
+
+ private final Context app;
+ private final String module;
+ private final String jobType;
+ private final JSONObject body;
+ private final Callback callback;
+ private final LogSink logSink;
+
+ interface LogSink { void log(String line); }
+
+ private RestContentClient client; // null until the job starts
+ private DownloadHold.StoppedBy stoppedBy = DownloadHold.StoppedBy.NOBODY;
+ private boolean ended;
+ private int lastPercent = -1;
+ private String lastDetail;
+
+ ModuleDownload(@NonNull Context ctx, @NonNull String module, @NonNull String jobType,
+ @NonNull JSONObject body, @NonNull Callback callback, @NonNull LogSink logSink) {
+ this.app = ctx.getApplicationContext();
+ this.module = module;
+ this.jobType = jobType;
+ this.body = body;
+ this.callback = callback;
+ this.logSink = logSink;
+ }
+
+ /** The OnlineAllowance kind of a module: maps is a content kind (K2GO-588), the rest are modules. */
+ public static String allowanceKind(String module) {
+ return "maps".equals(module)
+ ? org.appdevforall.k2go.system.domain.ContentType.MAPS.key()
+ : OnlineAllowance.MODULES;
+ }
+
+ String module() {
+ return module;
+ }
+
+ /** Start the job, or hold it before the start when the network may not be used now. */
+ synchronized void start() {
+ if (ended) return;
+ DownloadHold.Reason why = holdReason();
+ if (why != null && AndroidNetworkClassifier.classify(app)
+ != org.appdevforall.k2go.networkpolicy.domain.NetworkClass.NONE) {
+ hold(why);
+ return;
+ }
+ begin();
+ }
+
+ /** The user paused. */
+ synchronized void pause() {
+ if (ended) return;
+ stoppedBy = DownloadHold.StoppedBy.USER;
+ if (client != null) client.pause();
+ ModuleDownloadRepository.get().post(ModuleDownloadProgress.paused(module, lastPercent));
+ logSink.log("[" + module + "-dl] paused by the user");
+ }
+
+ /**
+ * The user resumed, or allowed the network on a hold. A hold that is still true stays held: the
+ * card shows why, and its button gives the consent.
+ */
+ synchronized void resume() {
+ if (ended) return;
+ DownloadHold.Reason why = holdReason();
+ if (why != null) {
+ stoppedBy = DownloadHold.StoppedBy.NETWORK;
+ ModuleDownloadProgress cur = ModuleDownloadRepository.get().current();
+ if (!(cur.isHeld() && cur.holdReason == why)) hold(why);
+ return;
+ }
+ stoppedBy = DownloadHold.StoppedBy.NOBODY;
+ logSink.log("[" + module + "-dl] resumed");
+ if (client == null) {
+ begin();
+ } else {
+ client.resume();
+ ModuleDownloadRepository.get().post(ModuleDownloadProgress.active(module, lastPercent, "", -1));
+ }
+ }
+
+ /** The network or the privacy choice changed: hold or continue as {@link DownloadHold} says. */
+ synchronized void evaluate() {
+ if (ended) return;
+ DownloadHold.Action a = DownloadHold.decide(AndroidNetworkClassifier.classify(app),
+ SessionMeteredConsentStore.get().isGranted(), onlineAllowed(), stoppedBy);
+ if (a == DownloadHold.Action.HOLD) {
+ DownloadHold.Reason why = holdReason();
+ if (why != null) hold(why);
+ } else if (a == DownloadHold.Action.CONTINUE) {
+ stoppedBy = DownloadHold.StoppedBy.NOBODY;
+ logSink.log("[" + module + "-dl] the network may be used again; continuing");
+ if (client == null) begin(); else client.resume();
+ }
+ }
+
+ /** Stop the job and remove its partial (the box does that on a cancel). */
+ synchronized void cancel() {
+ if (ended) return;
+ ended = true;
+ if (client != null) client.cancel();
+ ModuleDownloadRepository.get().clear();
+ }
+
+ private void hold(DownloadHold.Reason why) {
+ stoppedBy = DownloadHold.StoppedBy.NETWORK;
+ if (client != null) client.pause();
+ ModuleDownloadRepository.get().post(ModuleDownloadProgress.held(module, lastPercent, why));
+ logSink.log("[" + module + "-dl] held: " + why);
+ }
+
+ @Nullable
+ private DownloadHold.Reason holdReason() {
+ return DownloadHold.reason(AndroidNetworkClassifier.classify(app),
+ SessionMeteredConsentStore.get().isGranted(), onlineAllowed());
+ }
+
+ private boolean onlineAllowed() {
+ return OnlineAllowance.allows(app, allowanceKind(module));
+ }
+
+ private void begin() {
+ ModuleDownloadRepository.get().post(ModuleDownloadProgress.active(module, -1, "", -1));
+ client = new RestContentClient(jobType);
+ client.start(body, new RestContentClient.Listener() {
+ @Override public void onProgress(int percent, String speed) { onProgress(percent, speed, -1L); }
+
+ @Override public void onProgress(int percent, String speed, long etaSeconds) {
+ synchronized (ModuleDownload.this) {
+ if (ended) return;
+ lastPercent = percent;
+ if (stoppedBy == DownloadHold.StoppedBy.NOBODY) {
+ ModuleDownloadRepository.get().post(
+ ModuleDownloadProgress.active(module, percent, speed, etaSeconds));
+ }
+ }
+ evaluate();
+ }
+
+ @Override public void onReconnecting(int attempt, int total) {
+ synchronized (ModuleDownload.this) {
+ if (ended) return;
+ if (stoppedBy == DownloadHold.StoppedBy.NOBODY) {
+ ModuleDownloadRepository.get().post(
+ ModuleDownloadProgress.reconnecting(module, attempt, total));
+ }
+ }
+ evaluate();
+ }
+
+ @Override public void onPaused(int percent) {
+ synchronized (ModuleDownload.this) {
+ if (ended) return;
+ // The box's percent at the stop: the bar showed the last poll before it.
+ int before = lastPercent;
+ if (percent >= 0) lastPercent = percent;
+ ModuleDownloadProgress cur = ModuleDownloadRepository.get().current();
+ if (stoppedBy == DownloadHold.StoppedBy.NOBODY) {
+ // A paused job that nobody here stopped: a job from an earlier run that this
+ // run re-attached to, or the poll before a resume took effect: continue.
+ if (holdReason() == null) client.resume(); else hold(holdReason());
+ } else if (lastPercent != before && (cur.isPaused() || cur.isHeld())) {
+ ModuleDownloadRepository.get().post(cur.isPaused()
+ ? ModuleDownloadProgress.paused(module, lastPercent)
+ : ModuleDownloadProgress.held(module, lastPercent, cur.holdReason));
+ }
+ }
+ }
+
+ @Override public void onIndexing() { }
+
+ @Override public void onLog(String line) {
+ // The poll repeats the job detail every second: log it only when it changes.
+ if (line.equals(lastDetail)) return;
+ lastDetail = line;
+ logSink.log("[" + module + "-dl] " + line);
+ }
+
+ @Override public void onDone() { onDone(null); }
+
+ @Override public void onDone(JSONObject result) {
+ synchronized (ModuleDownload.this) {
+ if (ended) return;
+ ended = true;
+ }
+ ModuleDownloadRepository.get().clear();
+ callback.onDone(result);
+ }
+
+ @Override public void onError(String message) {
+ synchronized (ModuleDownload.this) {
+ if (ended) return;
+ ended = true;
+ }
+ ModuleDownloadRepository.get().clear();
+ callback.onError(message);
+ }
+ });
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java
new file mode 100644
index 000000000..89e96ddc4
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/install/presentation/ModuleDownloadRepository.java
@@ -0,0 +1,63 @@
+/*
+ * ============================================================================
+ * Name : ModuleDownloadRepository.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-394, K2GO-593. The one place where the progress of a
+ * module's download lives, so the install screens observe it.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.presentation;
+
+import androidx.lifecycle.LiveData;
+import androidx.lifecycle.MutableLiveData;
+
+import org.appdevforall.k2go.install.domain.ModuleDownloadProgress;
+
+/**
+ * The download bar's single source. {@link ModuleDownload} writes it from the dash-node poll; the
+ * install screens observe it beside {@code ModuleQueueRepository} (the phase spine). One writer, so no
+ * second place makes up a download percent. It is {@link ModuleDownloadProgress#none()} when no
+ * module downloads, so a module with no download shows only its phase.
+ */
+public final class ModuleDownloadRepository {
+
+ private static final ModuleDownloadRepository INSTANCE = new ModuleDownloadRepository();
+
+ private final MutableLiveData state =
+ new MutableLiveData<>(ModuleDownloadProgress.none());
+ // postValue is applied later on the main thread; current() must see the last write at once.
+ private volatile ModuleDownloadProgress last = ModuleDownloadProgress.none();
+
+ private ModuleDownloadRepository() {
+ }
+
+ public static ModuleDownloadRepository get() {
+ return INSTANCE;
+ }
+
+ public LiveData state() {
+ return state;
+ }
+
+ public ModuleDownloadProgress current() {
+ return last;
+ }
+
+ /** Whether {@code module} has a download in progress now (active, paused, held or reconnecting). */
+ public boolean isDownloading(String module) {
+ ModuleDownloadProgress p = last;
+ return p.isRunning() && p.isFor(module);
+ }
+
+ /** Post a new snapshot. postValue, because the writers run on the main and on worker threads. */
+ public void post(ModuleDownloadProgress p) {
+ last = p != null ? p : ModuleDownloadProgress.none();
+ state.postValue(last);
+ }
+
+ /** Back to "nothing downloads": when the download ends, and on teardown. */
+ public void clear() {
+ post(ModuleDownloadProgress.none());
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgress.java b/controller/app/src/main/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgress.java
deleted file mode 100644
index ab9444775..000000000
--- a/controller/app/src/main/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgress.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * ============================================================================
- * Name : MapsDownloadProgress.java
- * Author : AppDevForAll
- * Copyright : Copyright (c) 2026 AppDevForAll
- * Description : K2GO-394. One base-map download's progress, as the subordinate
- * download bar needs it, built from the dash-node REST poll
- * (RestContentClient). Pure JVM, no Android, no JSON framework.
- * ============================================================================
- */
-package org.appdevforall.k2go.maps.domain;
-
-/**
- * A snapshot of the base-map download for the subordinate bar. The base maps are downloaded through
- * dash-node's durable job engine (the same path as ZIMs), so this is built from the REST poll fields
- * ({@code RestContentClient.Listener}) -- a phase, a percent, a speed token, and the reconnect counter
- * -- not from aria2's raw RPC. The rule for "which phase" lives in one testable place, not in the UI.
- */
-public final class MapsDownloadProgress {
-
- /** The states the download bar distinguishes. RECONNECTING is a network drop the server rides out. */
- public enum Phase { NONE, ACTIVE, PAUSED, RECONNECTING, COMPLETE }
-
- public final Phase phase;
- /** 0..100, or -1 when not known yet (queued / no percent reported). */
- public final int percent;
- /** Display token for the rate WITHOUT the per-second suffix (e.g. "3.4 MB"); the UI appends "/s". */
- public final String speed;
- /** Reconnect counter for "Reconnecting n of N"; both 0 when not reconnecting. */
- public final int reconnectAttempt;
- public final int reconnectTotal;
-
- private MapsDownloadProgress(Phase phase, int percent, String speed, int attempt, int total) {
- this.phase = phase;
- this.percent = percent < 0 ? -1 : Math.min(100, percent);
- this.speed = speed != null ? speed : "";
- this.reconnectAttempt = Math.max(0, attempt);
- this.reconnectTotal = Math.max(0, total);
- }
-
- /** Nothing is downloading right now -- before the job starts, or after it finishes/clears. */
- public static MapsDownloadProgress none() {
- return new MapsDownloadProgress(Phase.NONE, -1, "", 0, 0);
- }
-
- /** A live download at {@code percent} moving at {@code speed} (a display token, no "/s"). */
- public static MapsDownloadProgress active(int percent, String speed) {
- return new MapsDownloadProgress(Phase.ACTIVE, percent, speed, 0, 0);
- }
-
- /** The user paused the download; the partial is kept and resume continues from it. */
- public static MapsDownloadProgress paused(int percent) {
- return new MapsDownloadProgress(Phase.PAUSED, percent, "", 0, 0);
- }
-
- /** The server lost the network and is reconnecting (attempt n of total), keeping the partial. */
- public static MapsDownloadProgress reconnecting(int attempt, int total) {
- return new MapsDownloadProgress(Phase.RECONNECTING, -1, "", attempt, total);
- }
-
- /** The download finished. */
- public static MapsDownloadProgress complete() {
- return new MapsDownloadProgress(Phase.COMPLETE, 100, "", 0, 0);
- }
-
- public boolean isActive() {
- return phase == Phase.ACTIVE;
- }
-
- public boolean isPaused() {
- return phase == Phase.PAUSED;
- }
-
- public boolean isReconnecting() {
- return phase == Phase.RECONNECTING;
- }
-
- public boolean isComplete() {
- return phase == Phase.COMPLETE;
- }
-
- /** Whether there is a live download to show a bar for (active, paused, or reconnecting). */
- public boolean isRunning() {
- return phase == Phase.ACTIVE || phase == Phase.PAUSED || phase == Phase.RECONNECTING;
- }
-}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/maps/presentation/MapsDownloadRepository.java b/controller/app/src/main/java/org/appdevforall/k2go/maps/presentation/MapsDownloadRepository.java
deleted file mode 100644
index 2fe764dc9..000000000
--- a/controller/app/src/main/java/org/appdevforall/k2go/maps/presentation/MapsDownloadRepository.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * ============================================================================
- * Name : MapsDownloadRepository.java
- * Author : AppDevForAll
- * Copyright : Copyright (c) 2026 AppDevForAll
- * Description : K2GO-394. The one place the maps download progress lives, so the
- * install-progress UI observes it instead of polling aria2 itself.
- * ============================================================================
- */
-package org.appdevforall.k2go.maps.presentation;
-
-import androidx.lifecycle.LiveData;
-import androidx.lifecycle.MutableLiveData;
-
-import org.appdevforall.k2go.maps.domain.MapsDownloadProgress;
-
-/**
- * The subordinate download bar's single source (K2GO-394). {@code InstallService} writes it from the
- * dash-node poll ({@code RestContentClient.Listener} for the "basemaps" job); the progress screen
- * observes it beside {@code ModuleQueueRepository} (the phase spine). One writer, so there is no
- * second place inventing a download percent.
- *
- *
Starts and resets to {@link MapsDownloadProgress#none()} -- the honest "nothing to show", which
- * is also what a non-maps module leaves it at, so the UI simply shows the phase-only Variant 3.
- */
-public final class MapsDownloadRepository {
-
- private static final MapsDownloadRepository INSTANCE = new MapsDownloadRepository();
-
- private final MutableLiveData state =
- new MutableLiveData<>(MapsDownloadProgress.none());
-
- private MapsDownloadRepository() {
- }
-
- public static MapsDownloadRepository get() {
- return INSTANCE;
- }
-
- public LiveData state() {
- return state;
- }
-
- public MapsDownloadProgress current() {
- MapsDownloadProgress v = state.getValue();
- return v != null ? v : MapsDownloadProgress.none();
- }
-
- /**
- * Post a new snapshot. {@code postValue} on purpose: the poll listener delivers on the main thread
- * but InstallService clears from its background install thread, so the write must be thread-safe.
- */
- public void post(MapsDownloadProgress p) {
- state.postValue(p != null ? p : MapsDownloadProgress.none());
- }
-
- /** Clear back to "nothing downloading" -- on teardown, or when the download finishes. */
- public void clear() {
- state.postValue(MapsDownloadProgress.none());
- }
-}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java
new file mode 100644
index 000000000..448377a67
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/DownloadCard.java
@@ -0,0 +1,145 @@
+/*
+ * ============================================================================
+ * Name : DownloadCard.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-394, K2GO-593. Binds the shared download card
+ * (view_k2go_download_card) of a module install to
+ * ModuleDownloadRepository: percent, speed, time left,
+ * Pause/Resume, "Reconnecting n of 5", and the hold on mobile data.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.redesign;
+
+import android.content.Context;
+import android.content.Intent;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.StringRes;
+import androidx.lifecycle.LifecycleOwner;
+
+import com.google.android.material.progressindicator.LinearProgressIndicator;
+
+import org.appdevforall.k2go.R;
+import org.appdevforall.k2go.install.domain.DownloadHold;
+import org.appdevforall.k2go.install.domain.ModuleDownloadProgress;
+import org.appdevforall.k2go.install.presentation.EtaText;
+import org.appdevforall.k2go.install.presentation.InstallService;
+import org.appdevforall.k2go.install.presentation.ModuleDownload;
+import org.appdevforall.k2go.install.presentation.ModuleDownloadRepository;
+import org.appdevforall.k2go.networkpolicy.data.OnlineAllowance;
+import org.appdevforall.k2go.networkpolicy.data.SessionMeteredConsentStore;
+
+/**
+ * The download half of {@link ModuleProgressPanel}. It only renders {@link ModuleDownloadRepository} for
+ * one module and sends the user's taps to {@link InstallService}; it keeps no download state of its own.
+ */
+final class DownloadCard {
+
+ private final Context ctx;
+ private final String module;
+ private final View card;
+ private final LinearProgressIndicator bar;
+ private final TextView pct, rate, note;
+ private final Button pause, allow;
+
+ /**
+ * @param root a view that contains view_k2go_download_card
+ * @param module the module key whose download this card shows
+ * @param titleRes the card title
+ */
+ DownloadCard(@NonNull View root, @NonNull String module, @StringRes int titleRes) {
+ this.ctx = root.getContext();
+ this.module = module;
+ card = root.findViewById(R.id.k2go_dl_card);
+ ((TextView) root.findViewById(R.id.k2go_dl_title)).setText(titleRes);
+ bar = root.findViewById(R.id.k2go_dl_bar);
+ pct = root.findViewById(R.id.k2go_dl_pct);
+ rate = root.findViewById(R.id.k2go_dl_rate);
+ note = root.findViewById(R.id.k2go_dl_note);
+ pause = root.findViewById(R.id.k2go_dl_pause);
+ allow = root.findViewById(R.id.k2go_dl_allow);
+ pause.setOnClickListener(v -> send(isStopped(current())
+ ? InstallService.ACTION_RESUME : InstallService.ACTION_PAUSE));
+ allow.setOnClickListener(v -> allowNetwork());
+ }
+
+ /** Observe the download for the life of {@code owner}. */
+ void observe(@NonNull LifecycleOwner owner) {
+ ModuleDownloadRepository.get().state().observe(owner, this::render);
+ }
+
+ private ModuleDownloadProgress current() {
+ return ModuleDownloadRepository.get().current();
+ }
+
+ private static boolean isStopped(ModuleDownloadProgress p) {
+ return p.isPaused() || p.isHeld();
+ }
+
+ private void render(ModuleDownloadProgress p) {
+ boolean shown = p != null && p.isRunning() && p.isFor(module);
+ card.setVisibility(shown ? View.VISIBLE : View.GONE);
+ if (!shown) return;
+
+ note.setVisibility(p.isHeld() ? View.VISIBLE : View.GONE);
+ allow.setVisibility(p.isHeld() ? View.VISIBLE : View.GONE);
+ pause.setVisibility(p.isHeld() ? View.GONE : View.VISIBLE);
+ if (p.isReconnecting()) {
+ // The box reconnects (aria2 --continue keeps the partial); the percent comes back after.
+ bar.setIndeterminate(true);
+ pct.setText("");
+ rate.setText(ctx.getString(R.string.k2go_dl_attempt, p.reconnectAttempt, p.reconnectTotal));
+ pause.setText(R.string.k2go_dl_pause);
+ return;
+ }
+ bar.setIndeterminate(p.percent < 0);
+ if (p.percent >= 0) bar.setProgressCompat(p.percent, true);
+ pct.setText(p.percent >= 0 ? ctx.getString(R.string.dash_format_pct, p.percent) : "");
+ if (p.isHeld()) {
+ boolean metered = p.holdReason == DownloadHold.Reason.METERED_NO_CONSENT;
+ rate.setText(R.string.k2go_mod_phase_queued);
+ note.setText(metered ? R.string.k2go_dl_held_metered : R.string.k2go_dl_held_offline);
+ allow.setText(metered ? R.string.k2go_netpolicy_continue : R.string.k2go_offline_action_allow_once);
+ return;
+ }
+ if (p.isPaused()) {
+ rate.setText(R.string.k2go_dl_paused);
+ pause.setText(R.string.k2go_dl_resume);
+ return;
+ }
+ pause.setText(R.string.k2go_dl_pause);
+ if (p.speed.isEmpty()) {
+ rate.setText("");
+ } else if (p.etaSeconds >= 0) {
+ rate.setText(ctx.getString(R.string.k2go_dl_speed_eta, p.speed, EtaText.of(ctx, p.etaSeconds)));
+ } else {
+ rate.setText(ctx.getString(R.string.k2go_dl_speed, p.speed));
+ }
+ }
+
+ /**
+ * The tap is the user's consent, for this session only, the same as the start gate gives: mobile
+ * data (SessionMeteredConsentStore) or, with Keep offline, this kind of install
+ * (OnlineAllowance). Then the service continues; if a second reason remains, the card shows it.
+ */
+ private void allowNetwork() {
+ ModuleDownloadProgress p = current();
+ if (!p.isHeld()) return;
+ if (p.holdReason == DownloadHold.Reason.METERED_NO_CONSENT) {
+ SessionMeteredConsentStore.get().grant();
+ } else {
+ OnlineAllowance.allow(ModuleDownload.allowanceKind(module));
+ }
+ send(InstallService.ACTION_RESUME);
+ }
+
+ private void send(String action) {
+ Intent i = new Intent(ctx, InstallService.class);
+ i.setAction(action);
+ ctx.startService(i);
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java
index 323aa5790..76f71c7ad 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/MapsPreparingFragment.java
@@ -58,14 +58,6 @@ public static MapsPreparingFragment newInstance(boolean fromIndex) {
}
private TextView status;
- private View progressRow; // ADFA-5228
- private com.google.android.material.progressindicator.LinearProgressIndicator progress;
- private TextView progressPct, progressEta;
- // K2GO-394: subordinate download card (the in-proot aria2c's live progress + Pause/Resume).
- private View downloadCard;
- private com.google.android.material.progressindicator.LinearProgressIndicator dlBar;
- private TextView dlBytes, dlRate;
- private android.widget.Button dlPause;
private boolean fromIndex = false; // ADFA-4901: hosted by the Finishing-setup index (observe only)
private boolean launched = false; // ADFA-4900: guard against re-launching maps on view recreation
@@ -85,28 +77,6 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
status = root.findViewById(R.id.k2go_prep_status);
status.setText(getString(R.string.k2go_maps_phase_prepared));
- progressRow = root.findViewById(R.id.k2go_prep_progress_row); // ADFA-5228
- progress = root.findViewById(R.id.k2go_prep_progress);
- progressPct = root.findViewById(R.id.k2go_prep_progress_pct);
- progressEta = root.findViewById(R.id.k2go_prep_progress_eta);
- // K2GO-394: the subordinate download card + its Pause/Resume, fed by MapsDownloadRepository.
- downloadCard = root.findViewById(R.id.k2go_prep_download);
- dlBar = root.findViewById(R.id.k2go_prep_dl_bar);
- dlBytes = root.findViewById(R.id.k2go_prep_dl_bytes);
- dlRate = root.findViewById(R.id.k2go_prep_dl_rate);
- dlPause = root.findViewById(R.id.k2go_prep_dl_pause);
- dlPause.setOnClickListener(v -> {
- // Toggle by the current phase: pause an active download, resume a paused one. The service
- // routes ACTION_PAUSE/RESUME to the in-proot aria2c over RPC (InstallService.doPause/doResume).
- boolean paused = org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().current().isPaused();
- android.content.Intent i = new android.content.Intent(requireContext(),
- org.appdevforall.k2go.install.presentation.InstallService.class);
- i.setAction(paused
- ? org.appdevforall.k2go.install.presentation.InstallService.ACTION_RESUME
- : org.appdevforall.k2go.install.presentation.InstallService.ACTION_PAUSE);
- requireContext().startService(i);
- });
-
// ADFA-4919: the fromIndex=false branch below is the DEPRECATED standalone Get More route
// (its own "Run in background", no index, no gate). Get More now routes through the install
// index (SetupLibraryActivity.openMapsIndex), so this branch is unreachable in that flow.
@@ -140,16 +110,6 @@ && getActivity() instanceof SetupLibraryActivity
// terminal and always wins.
ModuleQueueRepository.get().state().observe(getViewLifecycleOwner(), st -> {
if (st == null) return;
- // ADFA-5228: determinate bar while maps installs; hidden if maps has no table (percent < 0).
- if (progressRow != null) {
- boolean showBar = st.phase == ModuleQueueState.Phase.RUNNING && st.percent >= 0;
- progressRow.setVisibility(showBar ? View.VISIBLE : View.GONE);
- if (showBar) {
- progress.setProgressCompat(st.percent, true);
- progressPct.setText(st.percent + "%");
- progressEta.setText(org.appdevforall.k2go.install.presentation.EtaText.of(requireContext(), st.etaSeconds));
- }
- }
if (st.phase == ModuleQueueState.Phase.RUNNING) {
if (logLines.isEmpty()) status.setText(getString(R.string.k2go_maps_phase_building));
} else if (st.phase == ModuleQueueState.Phase.DONE) {
@@ -160,10 +120,8 @@ && getActivity() instanceof SetupLibraryActivity
}
});
- // K2GO-394: the subordinate download bar. Present only while a live in-proot download exists
- // (the RPC feed); hidden otherwise, so a stock rootfs with no RPC shows the phase spine alone.
- org.appdevforall.k2go.maps.presentation.MapsDownloadRepository.get().state()
- .observe(getViewLifecycleOwner(), this::renderDownload);
+ // K2GO-593: the standard proot install panel (install bar + base-map download card).
+ new ModuleProgressPanel(root, "maps", R.string.k2go_maps_dl_title).observe(getViewLifecycleOwner());
// ADFA-4901: collapsible live log. The status line mirrors the latest line; expanding shows
// the full terminal (LogRepository snapshot + live appends), auto-scrolled.
@@ -187,41 +145,6 @@ && getActivity() instanceof SetupLibraryActivity
return root;
}
- /** K2GO-394: render (or hide) the subordinate download card from the dash-node progress feed. */
- private void renderDownload(org.appdevforall.k2go.maps.domain.MapsDownloadProgress p) {
- if (downloadCard == null) {
- return;
- }
- if (p == null || !p.isRunning()) {
- downloadCard.setVisibility(View.GONE);
- return;
- }
- downloadCard.setVisibility(View.VISIBLE);
- // A network drop: dash-node is re-establishing (aria2 --continue). Show the attempt counter
- // and an indeterminate bar; the partial is kept, so the percent will pick back up on resume.
- if (p.isReconnecting()) {
- dlBar.setIndeterminate(true);
- dlBytes.setText("");
- dlRate.setText(getString(R.string.k2go_dl_attempt, p.reconnectAttempt, p.reconnectTotal));
- dlPause.setText(getString(R.string.k2go_dl_pause));
- return;
- }
- int pct = p.percent;
- dlBar.setIndeterminate(pct < 0);
- if (pct >= 0) {
- dlBar.setProgressCompat(pct, true);
- }
- dlBytes.setText(pct >= 0 ? (pct + "%") : "");
- if (p.isPaused()) {
- dlRate.setText(getString(R.string.k2go_dl_paused));
- dlPause.setText(getString(R.string.k2go_dl_resume));
- } else {
- // The poll gives the rate as a display token ("3.4 MB"); append the per-second suffix.
- dlRate.setText(p.speed.isEmpty() ? "" : p.speed + "/s");
- dlPause.setText(getString(R.string.k2go_dl_pause));
- }
- }
-
/** K2GO-374: seed the panel's deque from the current log snapshot when it is expanded. */
private void seedLog() {
logLines.clear();
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java
index 51fbc90da..a3b91fa87 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleInstallFragment.java
@@ -47,9 +47,6 @@ public static ModuleInstallFragment newInstance(String yamlBaseKey) {
private String key;
private TextView status;
- private View progressRow; // ADFA-5228
- private com.google.android.material.progressindicator.LinearProgressIndicator progress;
- private TextView progressPct, progressEta;
private org.appdevforall.k2go.widget.LiveLogPanel logPanel; // K2GO-374: shared details panel
private boolean terminalDone = false; // this module reached done/failed → stop live status
private final ArrayDeque logLines = new ArrayDeque<>();
@@ -66,15 +63,17 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
title.setText(c != null ? getString(c.detailTitleRes) : (key == null ? "" : key));
status = root.findViewById(R.id.k2go_modinst_status);
- progressRow = root.findViewById(R.id.k2go_modinst_progress_row); // ADFA-5228
- progress = root.findViewById(R.id.k2go_modinst_progress);
- progressPct = root.findViewById(R.id.k2go_modinst_progress_pct);
- progressEta = root.findViewById(R.id.k2go_modinst_progress_eta);
// ADFA-5074: the key is passed so a module that earns its own art can be matched.
org.appdevforall.k2go.util.ProgressVisuals.applyForModule(root, key);
logPanel = root.findViewById(R.id.k2go_modinst_log_panel);
logPanel.setOnExpandListener(this::seedLog); // K2GO-374: seed from the snapshot on expand
+ // K2GO-593: the standard proot install panel (install bar + download card).
+ new ModuleProgressPanel(root, key == null ? "" : key, R.string.k2go_dl_program_title)
+ .observe(getViewLifecycleOwner());
+ org.appdevforall.k2go.install.presentation.ModuleDownloadRepository.get().state()
+ .observe(getViewLifecycleOwner(), p -> updateStatus());
+
updateStatus();
ModuleQueueRepository.get().state().observe(getViewLifecycleOwner(), st -> updateStatus());
// ADFA-4898 P4: surface a "seems stalled" hint over the frozen status line while this module is
@@ -91,7 +90,7 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
logListener = new LogRepository.Listener() {
@Override public void onAppend(String line) {
if (!isAdded() || line == null) return;
- if (!terminalDone && installing()) status.setText(line);
+ if (!terminalDone && installing() && !downloading()) status.setText(line);
if (logPanel.isExpanded()) { pushLine(line); renderLog(); }
}
@Override public void onCleared() {
@@ -104,6 +103,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
return root;
}
+ /** True while THIS module downloads before its role (the one source: ModuleDownloadRepository). */
+ private boolean downloading() {
+ return org.appdevforall.k2go.install.presentation.ModuleDownloadRepository.get().isDownloading(key);
+ }
+
/** True while THIS module is the one currently running. */
private boolean installing() {
ModuleQueueState mq = ModuleQueueRepository.get().current();
@@ -116,18 +120,6 @@ private void updateStatus() {
if (status == null || !isAdded()) return;
ModuleQueueState mq = ModuleQueueRepository.get().current();
- // ADFA-5228: determinate bar above the status line while THIS module installs; hidden when
- // it isn't running or has no task table (percent < 0), leaving the animation alone.
- if (progressRow != null) {
- boolean showBar = installing() && mq.percent >= 0;
- progressRow.setVisibility(showBar ? View.VISIBLE : View.GONE);
- if (showBar) {
- progress.setProgressCompat(mq.percent, true);
- progressPct.setText(mq.percent + "%");
- progressEta.setText(org.appdevforall.k2go.install.presentation.EtaText.of(requireContext(), mq.etaSeconds));
- }
- }
-
// ADFA-4898: one predicate for "did this module fail" across every surface (hub pill, detail
// Retry/Back, this progress line) — ModuleQueueState.didFail(key). Was hand-rolled here as
// failedModules.contains(...); routed through the shared atom so the three can't drift apart.
@@ -142,6 +134,13 @@ private void updateStatus() {
status.setText(getString(R.string.k2go_mod_phase_done));
return;
}
+ if (downloading()) {
+ org.appdevforall.k2go.install.domain.ModuleDownloadProgress dl =
+ org.appdevforall.k2go.install.presentation.ModuleDownloadRepository.get().current();
+ status.setText(getString(dl.isHeld() ? R.string.k2go_mod_phase_queued
+ : dl.isPaused() ? R.string.k2go_dl_paused : R.string.k2go_mod_phase_downloading));
+ return;
+ }
if (installing()) {
// ADFA-4898: a retry from this card brought the module back to RUNNING — clear the terminal
// latch so the live log resumes driving the status line (it stops again on the next terminal).
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProgressPanel.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProgressPanel.java
new file mode 100644
index 000000000..9375d2ae8
--- /dev/null
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProgressPanel.java
@@ -0,0 +1,77 @@
+/*
+ * ============================================================================
+ * Name : ModuleProgressPanel.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-593. The progress panel of a proot module install
+ * (view_k2go_module_progress): the install bar over the download
+ * card, the same on every install screen.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.redesign;
+
+import android.content.Context;
+import android.view.View;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.StringRes;
+import androidx.lifecycle.LifecycleOwner;
+
+import com.google.android.material.progressindicator.LinearProgressIndicator;
+
+import org.appdevforall.k2go.R;
+import org.appdevforall.k2go.install.presentation.EtaText;
+import org.appdevforall.k2go.install.presentation.ModuleQueueRepository;
+import org.appdevforall.k2go.install.presentation.ModuleQueueState;
+
+/**
+ * The standard progress of a proot module install, started with maps (K2GO-394) and Forgejo
+ * (K2GO-593). Two bars, each with one source, and the panel keeps no state of its own:
+ *
+ *
The install bar: {@link ModuleQueueRepository}. It shows while the module runs and its role
+ * has a task table (percent >= 0). It starts at 0% before the module's download, so both bars
+ * show while the module downloads.
+ *
The download card: {@code ModuleDownloadRepository}, through {@link DownloadCard}.
+ *
+ * A new proot module gets both by including the layout and making one panel with its key.
+ */
+public final class ModuleProgressPanel {
+
+ private final Context ctx;
+ private final String module;
+ private final View installRow;
+ private final LinearProgressIndicator installBar;
+ private final TextView installPct, installEta;
+ private final DownloadCard downloadCard;
+
+ /**
+ * @param root a view that contains view_k2go_module_progress
+ * @param module the module key ("maps", "forgejo")
+ * @param downloadTitleRes the download card title
+ */
+ public ModuleProgressPanel(@NonNull View root, @NonNull String module, @StringRes int downloadTitleRes) {
+ this.ctx = root.getContext();
+ this.module = module;
+ installRow = root.findViewById(R.id.k2go_mp_install_row);
+ installBar = root.findViewById(R.id.k2go_mp_install_bar);
+ installPct = root.findViewById(R.id.k2go_mp_install_pct);
+ installEta = root.findViewById(R.id.k2go_mp_install_eta);
+ downloadCard = new DownloadCard(root, module, downloadTitleRes);
+ }
+
+ /** Observe both sources for the life of {@code owner}. */
+ public void observe(@NonNull LifecycleOwner owner) {
+ ModuleQueueRepository.get().state().observe(owner, this::renderInstall);
+ downloadCard.observe(owner);
+ }
+
+ private void renderInstall(ModuleQueueState mq) {
+ boolean show = mq != null && mq.isInstalling(module) && mq.percent >= 0;
+ installRow.setVisibility(show ? View.VISIBLE : View.GONE);
+ if (!show) return;
+ installBar.setProgressCompat(mq.percent, true);
+ installPct.setText(ctx.getString(R.string.dash_format_pct, mq.percent));
+ installEta.setText(EtaText.of(ctx, mq.etaSeconds));
+ }
+}
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProvisioner.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProvisioner.java
index 56ea0dd66..fa18f56d3 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProvisioner.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleProvisioner.java
@@ -96,6 +96,8 @@ public static OperationDispatcher.Dispatch drain(Context ctx) {
public static void startBatch(Context ctx, String[] modules, android.os.Bundle extras) {
if (ctx == null || modules == null || modules.length == 0) return;
final Context app = ctx.getApplicationContext();
+ // K2GO-593: Forgejo downloads before the server stop, so it is the first row of the batch.
+ modules = org.appdevforall.k2go.install.domain.ForgejoBinaryPin.downloadFirst(modules);
ModuleBatch.save(app, modules);
// K2GO-592: every Forgejo install owes its seed (admin account, org, repos), whatever screen
// scheduled it. Banked before the queue starts, so the install index sees it when the batch ends.
diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleRetry.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleRetry.java
index f118b6d81..95039cb54 100644
--- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleRetry.java
+++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleRetry.java
@@ -74,9 +74,8 @@ public static void fire(View anchor, String moduleKey, @Nullable Runnable onStar
final Runnable start = () -> {
// K2GO-588/593: the gate let this retry connect, also "Allow only this time" with Keep
// offline; record it as the start path does, so the run's download does not ask again.
- org.appdevforall.k2go.networkpolicy.data.OnlineAllowance.allow("maps".equals(moduleKey)
- ? org.appdevforall.k2go.system.domain.ContentType.MAPS.key()
- : org.appdevforall.k2go.networkpolicy.data.OnlineAllowance.MODULES);
+ org.appdevforall.k2go.networkpolicy.data.OnlineAllowance.allow(
+ org.appdevforall.k2go.install.presentation.ModuleDownload.allowanceKind(moduleKey));
InstallService.retryModules(ctx, Collections.singletonList(moduleKey));
if (onStarted != null) onStarted.run();
};
diff --git a/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml b/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml
index e87cd8333..0c231f097 100644
--- a/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml
+++ b/controller/app/src/main/res/layout/fragment_k2go_maps_preparing.xml
@@ -36,114 +36,9 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/controller/app/src/main/res/layout/view_k2go_module_progress.xml b/controller/app/src/main/res/layout/view_k2go_module_progress.xml
new file mode 100644
index 000000000..9b604b98e
--- /dev/null
+++ b/controller/app/src/main/res/layout/view_k2go_module_progress.xml
@@ -0,0 +1,57 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/controller/app/src/main/res/values-ar/strings.xml b/controller/app/src/main/res/values-ar/strings.xml
index 0759814e4..f7cc6b0dc 100644
--- a/controller/app/src/main/res/values-ar/strings.xml
+++ b/controller/app/src/main/res/values-ar/strings.xml
@@ -1683,4 +1683,10 @@
إرسال على أي حالأُلغيتوقّف التثبيت. تحقّق من كل وحدة أدناه.
+ جارٍ تنزيل البرنامج
+ %1$s/ث
+ %1$s/ث، %2$s
+ في انتظار شبكة الواي فاي. لن يستخدم التنزيل بيانات الجوال حتى تسمح بذلك.
+ في الانتظار. التطبيق مضبوط على البقاء دون اتصال، لذلك لن يتصل التنزيل حتى تسمح بذلك.
+ جارٍ التنزيل…
diff --git a/controller/app/src/main/res/values-az/strings.xml b/controller/app/src/main/res/values-az/strings.xml
index a4901ad11..e01aa9995 100644
--- a/controller/app/src/main/res/values-az/strings.xml
+++ b/controller/app/src/main/res/values-az/strings.xml
@@ -1699,4 +1699,10 @@
Yenə də göndərLəğv edildiQuraşdırma dayandı. Aşağıda hər modulu yoxlayın.
+ Proqram yüklənir
+ %1$s/s
+ %1$s/s, %2$s
+ Wi-Fi gözlənilir. Siz icazə verənə qədər yükləmə mobil internetdən istifadə etmir.
+ Gözləyir. Tətbiq oflayn saxlanılır, ona görə də siz icazə verənə qədər yükləmə qoşulmur.
+ Yüklənir…
diff --git a/controller/app/src/main/res/values-bg/strings.xml b/controller/app/src/main/res/values-bg/strings.xml
index 3de1e4e97..e79786e2b 100644
--- a/controller/app/src/main/res/values-bg/strings.xml
+++ b/controller/app/src/main/res/values-bg/strings.xml
@@ -1686,4 +1686,10 @@
Изпрати въпреки товаОтмененоИнсталирането спря. Проверете всеки модул по-долу.
+ Изтегляне на програмата
+ %1$s/сек
+ %1$s/сек, %2$s
+ Изчакване на Wi-Fi. Изтеглянето не използва мобилни данни, докато не го разрешите.
+ Изчакване. Приложението е оставено офлайн, затова изтеглянето не се свързва, докато не го разрешите.
+ Изтегляне…
diff --git a/controller/app/src/main/res/values-bn/strings.xml b/controller/app/src/main/res/values-bn/strings.xml
index d9764843a..30d6ca28a 100644
--- a/controller/app/src/main/res/values-bn/strings.xml
+++ b/controller/app/src/main/res/values-bn/strings.xml
@@ -1692,4 +1692,10 @@
তবুও পাঠানবাতিল করা হয়েছেইনস্টল বন্ধ হয়েছে। নিচে প্রতিটি মডিউল দেখুন।
+ প্রোগ্রাম ডাউনলোড হচ্ছে
+ %1$s/সে
+ %1$s/সে, %2$s
+ Wi-Fi-এর জন্য অপেক্ষা করছে। আপনি অনুমতি না দেওয়া পর্যন্ত ডাউনলোডটি মোবাইল ডেটা ব্যবহার করে না।
+ অপেক্ষা করছে। অ্যাপটি অফলাইন রাখা হয়েছে, তাই আপনি অনুমতি না দেওয়া পর্যন্ত ডাউনলোডটি সংযুক্ত হয় না।
+ ডাউনলোড হচ্ছে…
diff --git a/controller/app/src/main/res/values-cs/strings.xml b/controller/app/src/main/res/values-cs/strings.xml
index 83dddf47c..96525587c 100644
--- a/controller/app/src/main/res/values-cs/strings.xml
+++ b/controller/app/src/main/res/values-cs/strings.xml
@@ -1688,4 +1688,10 @@
Přesto odeslatZrušenoInstalace se zastavila. Zkontrolujte níže každý modul.
+ Stahování programu
+ %1$s/s
+ %1$s/s, %2$s
+ Čekání na Wi-Fi. Stahování nepoužije mobilní data, dokud to nepovolíte.
+ Čekání. Aplikace je ponechána offline, proto se stahování nepřipojí, dokud to nepovolíte.
+ Stahování…
diff --git a/controller/app/src/main/res/values-de/strings.xml b/controller/app/src/main/res/values-de/strings.xml
index 96658c9d0..c0710a10c 100644
--- a/controller/app/src/main/res/values-de/strings.xml
+++ b/controller/app/src/main/res/values-de/strings.xml
@@ -1679,4 +1679,10 @@
Trotzdem sendenAbgebrochenDie Installation wurde beendet. Prüfen Sie unten jedes Modul.
+ Programm wird heruntergeladen
+ %1$s/s
+ %1$s/s, %2$s
+ Warten auf WLAN. Der Download nutzt keine mobilen Daten, bis Sie es erlauben.
+ Wartet. Die App bleibt offline, daher stellt der Download keine Verbindung her, bis Sie es erlauben.
+ Wird heruntergeladen…
diff --git a/controller/app/src/main/res/values-el/strings.xml b/controller/app/src/main/res/values-el/strings.xml
index 50c8537f5..456dfae62 100644
--- a/controller/app/src/main/res/values-el/strings.xml
+++ b/controller/app/src/main/res/values-el/strings.xml
@@ -1686,4 +1686,10 @@
Αποστολή ούτως ή άλλωςΑκυρώθηκεΗ εγκατάσταση σταμάτησε. Ελέγξτε παρακάτω κάθε module.
+ Λήψη του προγράμματος
+ %1$s/δ
+ %1$s/δ, %2$s
+ Αναμονή για Wi-Fi. Η λήψη δεν χρησιμοποιεί δεδομένα κινητής μέχρι να το επιτρέψετε.
+ Αναμονή. Η εφαρμογή διατηρείται εκτός σύνδεσης, οπότε η λήψη δεν συνδέεται μέχρι να το επιτρέψετε.
+ Λήψη…
diff --git a/controller/app/src/main/res/values-es/strings.xml b/controller/app/src/main/res/values-es/strings.xml
index 4a4bd3f2e..12b316f84 100644
--- a/controller/app/src/main/res/values-es/strings.xml
+++ b/controller/app/src/main/res/values-es/strings.xml
@@ -1756,4 +1756,10 @@
Enviar de todos modosCanceladoLa instalación se detuvo. Revise cada módulo abajo.
+ Descargando el programa
+ %1$s/s
+ %1$s/s, %2$s
+ Esperando Wi-Fi. La descarga no usa datos móviles hasta que lo permitas.
+ En espera. La app se mantiene sin conexión, así que la descarga no se conecta hasta que lo permitas.
+ Descargando…
diff --git a/controller/app/src/main/res/values-fa/strings.xml b/controller/app/src/main/res/values-fa/strings.xml
index 91891a368..2bc691a39 100644
--- a/controller/app/src/main/res/values-fa/strings.xml
+++ b/controller/app/src/main/res/values-fa/strings.xml
@@ -1679,4 +1679,10 @@
به هر حال ارسال شودلغو شدنصب متوقف شد. هر ماژول را در پایین بررسی کنید.
+ در حال دانلود برنامه
+ %1$s/ثانیه
+ %1$s/ثانیه، %2$s
+ در انتظار Wi-Fi. دانلود تا زمانی که اجازه ندهید از داده تلفن همراه استفاده نمیکند.
+ در انتظار. برنامه آفلاین نگه داشته شده است، بنابراین دانلود تا زمانی که اجازه ندهید وصل نمیشود.
+ در حال دانلود…
diff --git a/controller/app/src/main/res/values-fr/strings.xml b/controller/app/src/main/res/values-fr/strings.xml
index d9da2d0f1..2e3bc5338 100644
--- a/controller/app/src/main/res/values-fr/strings.xml
+++ b/controller/app/src/main/res/values-fr/strings.xml
@@ -1767,4 +1767,10 @@
Envoyer quand mêmeAnnuléL\'installation s\'est arrêtée. Vérifiez chaque module ci-dessous.
+ Téléchargement du programme
+ %1$s/s
+ %1$s/s, %2$s
+ En attente du Wi-Fi. Le téléchargement n\'utilise pas les données mobiles tant que vous ne l\'autorisez pas.
+ En attente. L\'application reste hors ligne, donc le téléchargement ne se connecte pas tant que vous ne l\'autorisez pas.
+ Téléchargement…
diff --git a/controller/app/src/main/res/values-gu/strings.xml b/controller/app/src/main/res/values-gu/strings.xml
index a07edf50f..38f988c74 100644
--- a/controller/app/src/main/res/values-gu/strings.xml
+++ b/controller/app/src/main/res/values-gu/strings.xml
@@ -1692,4 +1692,10 @@
છતાં મોકલોરદ કર્યુંઇન્સ્ટૉલ અટકી ગયું. નીચે દરેક મૉડ્યુલ તપાસો.
+ પ્રોગ્રામ ડાઉનલોડ થઈ રહ્યો છે
+ %1$s/સે
+ %1$s/સે, %2$s
+ Wi-Fi ની રાહ જોઈ રહ્યું છે. તમે મંજૂરી ન આપો ત્યાં સુધી ડાઉનલોડ મોબાઇલ ડેટા વાપરતું નથી.
+ રાહ જોઈ રહ્યું છે. ઍપ ઑફલાઇન રાખવામાં આવી છે, તેથી તમે મંજૂરી ન આપો ત્યાં સુધી ડાઉનલોડ કનેક્ટ થતું નથી.
+ ડાઉનલોડ થઈ રહ્યું છે…
diff --git a/controller/app/src/main/res/values-hi/strings.xml b/controller/app/src/main/res/values-hi/strings.xml
index 8a864ee03..f6aab2c9b 100644
--- a/controller/app/src/main/res/values-hi/strings.xml
+++ b/controller/app/src/main/res/values-hi/strings.xml
@@ -1756,4 +1756,10 @@
फिर भी भेजेंरद्द किया गयाइंस्टॉल रुक गया। नीचे हर मॉड्यूल देखें।
+ प्रोग्राम डाउनलोड हो रहा है
+ %1$s/से
+ %1$s/से, %2$s
+ Wi-Fi की प्रतीक्षा में। जब तक आप अनुमति नहीं देते, डाउनलोड मोबाइल डेटा का उपयोग नहीं करता।
+ प्रतीक्षा में। ऐप को ऑफ़लाइन रखा गया है, इसलिए जब तक आप अनुमति नहीं देते, डाउनलोड कनेक्ट नहीं होता।
+ डाउनलोड हो रहा है…
diff --git a/controller/app/src/main/res/values-hu/strings.xml b/controller/app/src/main/res/values-hu/strings.xml
index f9bdb2287..4e7d1cede 100644
--- a/controller/app/src/main/res/values-hu/strings.xml
+++ b/controller/app/src/main/res/values-hu/strings.xml
@@ -1679,4 +1679,10 @@
Küldés mégisMegszakítvaA telepítés leállt. Alább ellenőrizze az egyes modulokat.
+ A program letöltése
+ %1$s/s
+ %1$s/s, %2$s
+ Várakozás Wi-Fi-re. A letöltés nem használ mobiladatot, amíg nem engedélyezi.
+ Várakozás. Az alkalmazás offline marad, ezért a letöltés nem csatlakozik, amíg nem engedélyezi.
+ Letöltés…
diff --git a/controller/app/src/main/res/values-in/strings.xml b/controller/app/src/main/res/values-in/strings.xml
index 447a8eb4d..c539e6f99 100644
--- a/controller/app/src/main/res/values-in/strings.xml
+++ b/controller/app/src/main/res/values-in/strings.xml
@@ -1685,4 +1685,10 @@
Tetap kirimDibatalkanPemasangan berhenti. Periksa setiap modul di bawah.
+ Mengunduh program
+ %1$s/d
+ %1$s/d, %2$s
+ Menunggu Wi-Fi. Unduhan tidak menggunakan data seluler sampai Anda mengizinkannya.
+ Menunggu. Aplikasi tetap luring, jadi unduhan tidak tersambung sampai Anda mengizinkannya.
+ Mengunduh…
diff --git a/controller/app/src/main/res/values-it/strings.xml b/controller/app/src/main/res/values-it/strings.xml
index 3c8554733..9f4b49869 100644
--- a/controller/app/src/main/res/values-it/strings.xml
+++ b/controller/app/src/main/res/values-it/strings.xml
@@ -1680,4 +1680,10 @@
Invia comunqueAnnullataL\'installazione si è interrotta. Controlla ogni modulo qui sotto.
+ Download del programma
+ %1$s/s
+ %1$s/s, %2$s
+ In attesa del Wi-Fi. Il download non usa i dati mobili finché non lo consenti.
+ In attesa. L\'app è mantenuta offline, quindi il download non si connette finché non lo consenti.
+ Download in corso…
diff --git a/controller/app/src/main/res/values-ja/strings.xml b/controller/app/src/main/res/values-ja/strings.xml
index e0cb77ba3..982ca87f4 100644
--- a/controller/app/src/main/res/values-ja/strings.xml
+++ b/controller/app/src/main/res/values-ja/strings.xml
@@ -1679,4 +1679,10 @@
このまま送信キャンセルしましたインストールが停止しました。下の各モジュールを確認してください。
+ プログラムをダウンロード中
+ %1$s/秒
+ %1$s/秒、%2$s
+ Wi-Fi を待機中です。許可するまで、ダウンロードにモバイルデータは使用されません。
+ 待機中です。アプリはオフラインのままなので、許可するまでダウンロードは接続しません。
+ ダウンロード中…
diff --git a/controller/app/src/main/res/values-ko/strings.xml b/controller/app/src/main/res/values-ko/strings.xml
index 42030e955..5a03a96c8 100644
--- a/controller/app/src/main/res/values-ko/strings.xml
+++ b/controller/app/src/main/res/values-ko/strings.xml
@@ -1679,4 +1679,10 @@
그래도 보내기취소됨설치가 중지되었습니다. 아래에서 각 모듈을 확인하세요.
+ 프로그램 다운로드 중
+ %1$s/초
+ %1$s/초, %2$s
+ Wi-Fi를 기다리는 중입니다. 허용하기 전까지 다운로드에 모바일 데이터를 사용하지 않습니다.
+ 대기 중입니다. 앱이 오프라인으로 유지되므로 허용하기 전까지 다운로드가 연결되지 않습니다.
+ 다운로드 중…
diff --git a/controller/app/src/main/res/values-lt/strings.xml b/controller/app/src/main/res/values-lt/strings.xml
index 1ce4c2c33..481e9d78b 100644
--- a/controller/app/src/main/res/values-lt/strings.xml
+++ b/controller/app/src/main/res/values-lt/strings.xml
@@ -1698,4 +1698,10 @@
Vis tiek siųstiAtšauktaDiegimas sustojo. Patikrinkite kiekvieną modulį žemiau.
+ Atsisiunčiama programa
+ %1$s/s
+ %1$s/s, %2$s
+ Laukiama Wi-Fi. Atsisiuntimas nenaudoja mobiliųjų duomenų, kol to neleisite.
+ Laukiama. Programa paliekama neprisijungus, todėl atsisiuntimas neprisijungia, kol to neleisite.
+ Atsisiunčiama…
diff --git a/controller/app/src/main/res/values-nl/strings.xml b/controller/app/src/main/res/values-nl/strings.xml
index 5a5febbd4..715787e1b 100644
--- a/controller/app/src/main/res/values-nl/strings.xml
+++ b/controller/app/src/main/res/values-nl/strings.xml
@@ -1679,4 +1679,10 @@
Toch verzendenGeannuleerdDe installatie is gestopt. Controleer hieronder elke module.
+ Het programma wordt gedownload
+ %1$s/s
+ %1$s/s, %2$s
+ Wachten op Wi-Fi. De download gebruikt geen mobiele data totdat je het toestaat.
+ Wachten. De app blijft offline, dus de download maakt geen verbinding totdat je het toestaat.
+ Downloaden…
diff --git a/controller/app/src/main/res/values-no/strings.xml b/controller/app/src/main/res/values-no/strings.xml
index 7b49dde36..d179c4690 100644
--- a/controller/app/src/main/res/values-no/strings.xml
+++ b/controller/app/src/main/res/values-no/strings.xml
@@ -1689,4 +1689,10 @@
Send likevelAvbruttInstallasjonen stoppet. Sjekk hver modul nedenfor.
+ Laster ned programmet
+ %1$s/s
+ %1$s/s, %2$s
+ Venter på Wi-Fi. Nedlastingen bruker ikke mobildata før du tillater det.
+ Venter. Appen holdes offline, så nedlastingen kobler ikke til før du tillater det.
+ Laster ned…
diff --git a/controller/app/src/main/res/values-pl/strings.xml b/controller/app/src/main/res/values-pl/strings.xml
index 06e67f40d..84d2fb89f 100644
--- a/controller/app/src/main/res/values-pl/strings.xml
+++ b/controller/app/src/main/res/values-pl/strings.xml
@@ -1691,4 +1691,10 @@
Wyślij mimo toAnulowanoInstalacja została zatrzymana. Sprawdź poniżej każdy moduł.
+ Pobieranie programu
+ %1$s/s
+ %1$s/s, %2$s
+ Oczekiwanie na Wi-Fi. Pobieranie nie używa danych komórkowych, dopóki na to nie zezwolisz.
+ Oczekiwanie. Aplikacja pozostaje offline, więc pobieranie nie łączy się, dopóki na to nie zezwolisz.
+ Pobieranie…
diff --git a/controller/app/src/main/res/values-pt/strings.xml b/controller/app/src/main/res/values-pt/strings.xml
index 71db19089..a4a2a55d4 100644
--- a/controller/app/src/main/res/values-pt/strings.xml
+++ b/controller/app/src/main/res/values-pt/strings.xml
@@ -1759,4 +1759,10 @@
Enviar mesmo assimCanceladoA instalação parou. Verifique cada módulo abaixo.
+ Baixando o programa
+ %1$s/s
+ %1$s/s, %2$s
+ Aguardando Wi-Fi. O download não usa dados móveis até você permitir.
+ Aguardando. O app é mantido offline, então o download não se conecta até você permitir.
+ Baixando…
diff --git a/controller/app/src/main/res/values-ro/strings.xml b/controller/app/src/main/res/values-ro/strings.xml
index 50814a7d0..c70631be3 100644
--- a/controller/app/src/main/res/values-ro/strings.xml
+++ b/controller/app/src/main/res/values-ro/strings.xml
@@ -1680,4 +1680,10 @@
Trimite oricumAnulatăInstalarea s-a oprit. Verifică fiecare modul de mai jos.
+ Se descarcă programul
+ %1$s/s
+ %1$s/s, %2$s
+ Se așteaptă Wi-Fi. Descărcarea nu folosește date mobile până nu permiți.
+ În așteptare. Aplicația este păstrată offline, așa că descărcarea nu se conectează până nu permiți.
+ Se descarcă…
diff --git a/controller/app/src/main/res/values-ru-rRU/strings.xml b/controller/app/src/main/res/values-ru-rRU/strings.xml
index 5a2d4a6aa..cd7c16020 100644
--- a/controller/app/src/main/res/values-ru-rRU/strings.xml
+++ b/controller/app/src/main/res/values-ru-rRU/strings.xml
@@ -1757,4 +1757,10 @@
Всё равно отправитьОтмененоУстановка остановлена. Проверьте каждый модуль ниже.
+ Загрузка программы
+ %1$s/с
+ %1$s/с, %2$s
+ Ожидание Wi-Fi. Загрузка не использует мобильные данные, пока вы не разрешите.
+ Ожидание. Приложение оставлено офлайн, поэтому загрузка не подключается, пока вы не разрешите.
+ Загрузка…
diff --git a/controller/app/src/main/res/values-sk/strings.xml b/controller/app/src/main/res/values-sk/strings.xml
index 9eb2aa1e5..543a8d92b 100644
--- a/controller/app/src/main/res/values-sk/strings.xml
+++ b/controller/app/src/main/res/values-sk/strings.xml
@@ -1688,4 +1688,10 @@
Napriek tomu odoslaťZrušenéInštalácia sa zastavila. Skontrolujte nižšie každý modul.
+ Sťahuje sa program
+ %1$s/s
+ %1$s/s, %2$s
+ Čaká sa na Wi-Fi. Sťahovanie nepoužije mobilné dáta, kým to nepovolíte.
+ Čaká sa. Aplikácia je ponechaná offline, preto sa sťahovanie nepripojí, kým to nepovolíte.
+ Sťahuje sa…
diff --git a/controller/app/src/main/res/values-sr/strings.xml b/controller/app/src/main/res/values-sr/strings.xml
index 9f3d09dd4..6107d58a9 100644
--- a/controller/app/src/main/res/values-sr/strings.xml
+++ b/controller/app/src/main/res/values-sr/strings.xml
@@ -1693,4 +1693,10 @@
Ипак пошаљиОтказаноИнсталација је заустављена. Проверите сваки модул испод.
+ Преузимање програма
+ %1$s/s
+ %1$s/s, %2$s
+ Чекање на Wi-Fi. Преузимање не користи мобилне податке док то не дозволите.
+ Чекање. Апликација је задржана офлајн, па се преузимање не повезује док то не дозволите.
+ Преузимање…
diff --git a/controller/app/src/main/res/values-sw/strings.xml b/controller/app/src/main/res/values-sw/strings.xml
index ad3b3ef63..537df513c 100644
--- a/controller/app/src/main/res/values-sw/strings.xml
+++ b/controller/app/src/main/res/values-sw/strings.xml
@@ -1699,4 +1699,10 @@
Tuma hata hivyoImeghairiwaUsakinishaji umesimama. Kagua kila moduli hapa chini.
+ Inapakua programu
+ %1$s/sek
+ %1$s/sek, %2$s
+ Inasubiri Wi-Fi. Upakuaji hautumii data ya simu hadi utakaporuhusu.
+ Inasubiri. Programu imewekwa nje ya mtandao, kwa hivyo upakuaji hauunganishi hadi utakaporuhusu.
+ Inapakua…
diff --git a/controller/app/src/main/res/values-ta/strings.xml b/controller/app/src/main/res/values-ta/strings.xml
index 48f2b45b8..2a8a49c8e 100644
--- a/controller/app/src/main/res/values-ta/strings.xml
+++ b/controller/app/src/main/res/values-ta/strings.xml
@@ -1699,4 +1699,10 @@
இருந்தாலும் அனுப்புரத்துசெய்யப்பட்டதுநிறுவல் நின்றது. கீழே ஒவ்வொரு தொகுதியையும் சரிபார்க்கவும்.
+ நிரல் பதிவிறக்கப்படுகிறது
+ %1$s/வி
+ %1$s/வி, %2$s
+ Wi-Fi க்காகக் காத்திருக்கிறது. நீங்கள் அனுமதிக்கும் வரை பதிவிறக்கம் மொபைல் டேட்டாவைப் பயன்படுத்தாது.
+ காத்திருக்கிறது. பயன்பாடு ஆஃப்லைனில் வைக்கப்பட்டுள்ளது, எனவே நீங்கள் அனுமதிக்கும் வரை பதிவிறக்கம் இணைக்காது.
+ பதிவிறக்கப்படுகிறது…
diff --git a/controller/app/src/main/res/values-tr/strings.xml b/controller/app/src/main/res/values-tr/strings.xml
index b97c4be35..9aa8e891c 100644
--- a/controller/app/src/main/res/values-tr/strings.xml
+++ b/controller/app/src/main/res/values-tr/strings.xml
@@ -1679,4 +1679,10 @@
Yine de gönderİptal edildiKurulum durdu. Aşağıdaki her modülü kontrol edin.
+ Program indiriliyor
+ %1$s/sn
+ %1$s/sn, %2$s
+ Wi-Fi bekleniyor. Siz izin verene kadar indirme mobil veri kullanmaz.
+ Bekleniyor. Uygulama çevrimdışı tutuluyor, bu yüzden siz izin verene kadar indirme bağlanmaz.
+ İndiriliyor…
diff --git a/controller/app/src/main/res/values-uk/strings.xml b/controller/app/src/main/res/values-uk/strings.xml
index d4ecec314..d4ceaa94f 100644
--- a/controller/app/src/main/res/values-uk/strings.xml
+++ b/controller/app/src/main/res/values-uk/strings.xml
@@ -1681,4 +1681,10 @@
Усе одно надіслатиСкасованоВстановлення зупинилося. Перевірте кожен модуль нижче.
+ Завантаження програми
+ %1$s/с
+ %1$s/с, %2$s
+ Очікування Wi-Fi. Завантаження не використовує мобільні дані, доки ви не дозволите.
+ Очікування. Застосунок залишено офлайн, тому завантаження не підключається, доки ви не дозволите.
+ Завантаження…
diff --git a/controller/app/src/main/res/values-vi/strings.xml b/controller/app/src/main/res/values-vi/strings.xml
index b7ae4f0ee..757f13400 100644
--- a/controller/app/src/main/res/values-vi/strings.xml
+++ b/controller/app/src/main/res/values-vi/strings.xml
@@ -1678,4 +1678,10 @@
Vẫn gửiĐã hủyQuá trình cài đặt đã dừng. Hãy kiểm tra từng mô-đun bên dưới.
+ Đang tải xuống chương trình
+ %1$s/giây
+ %1$s/giây, %2$s
+ Đang chờ Wi-Fi. Bản tải xuống không dùng dữ liệu di động cho đến khi bạn cho phép.
+ Đang chờ. Ứng dụng được giữ ngoại tuyến, vì vậy bản tải xuống không kết nối cho đến khi bạn cho phép.
+ Đang tải xuống…
diff --git a/controller/app/src/main/res/values-yo/strings.xml b/controller/app/src/main/res/values-yo/strings.xml
index c722e3ebb..8e7d446d1 100644
--- a/controller/app/src/main/res/values-yo/strings.xml
+++ b/controller/app/src/main/res/values-yo/strings.xml
@@ -1698,4 +1698,10 @@
Fi ránṣẹ́ bó ti wù kó ríTi fagiléFífi sórí ẹ̀rọ ti dúró. Ṣàyẹ̀wò módù kọ̀ọ̀kan nísàlẹ̀.
+ Ń gba ètò náà sílẹ̀
+ %1$s/ìs
+ %1$s/ìs, %2$s
+ Ń dúró de Wi-Fi. Ìgbàsílẹ̀ kò ní lo data alagbeka títí o fi gbà á láàyè.
+ Ń dúró. A pa ìṣàmúlò mọ́ àìsí-íńtánẹ́ẹ̀tì, nítorí náà ìgbàsílẹ̀ kò ní sopọ̀ títí o fi gbà á láàyè.
+ Ń gba sílẹ̀…
diff --git a/controller/app/src/main/res/values-zh-rCN/strings.xml b/controller/app/src/main/res/values-zh-rCN/strings.xml
index b10dcf561..d8c0e0930 100644
--- a/controller/app/src/main/res/values-zh-rCN/strings.xml
+++ b/controller/app/src/main/res/values-zh-rCN/strings.xml
@@ -1679,4 +1679,10 @@
仍然发送已取消安装已停止。请检查下方的每个模块。
+ 正在下载程序
+ %1$s/秒
+ %1$s/秒,%2$s
+ 正在等待 Wi-Fi。在您允许之前,下载不会使用移动数据。
+ 正在等待。应用保持离线,因此在您允许之前,下载不会联网。
+ 正在下载…
diff --git a/controller/app/src/main/res/values/strings.xml b/controller/app/src/main/res/values/strings.xml
index 6424e724f..a030fcd76 100644
--- a/controller/app/src/main/res/values/strings.xml
+++ b/controller/app/src/main/res/values/strings.xml
@@ -1889,4 +1889,16 @@
CanceledThe install stopped. Check each module below.
+
+ Downloading the program
+
+ %1$s/s
+
+ %1$s/s, %2$s
+
+ Waiting for Wi-Fi. The download does not use mobile data until you allow it.
+
+ Waiting. The app is kept offline, so the download does not connect until you allow it.
+
+ Downloading...
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirementTest.java b/controller/app/src/test/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirementTest.java
index 66ff5b76e..0293cd9e2 100644
--- a/controller/app/src/test/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirementTest.java
+++ b/controller/app/src/test/java/org/appdevforall/k2go/dependency/domain/DashNodeRequirementTest.java
@@ -10,9 +10,9 @@
public class DashNodeRequirementTest {
@Test
- public void forgejoRequiresOneThreeSeven() {
- assertArrayEquals(new int[]{1, 3, 7}, DashNodeRequirement.minFor("forgejo"));
- assertEquals("1.3.7", DashNodeRequirement.minLabel("forgejo"));
+ public void forgejoRequiresOneSixFive() {
+ assertArrayEquals(new int[]{1, 6, 5}, DashNodeRequirement.minFor("forgejo"));
+ assertEquals("1.6.5", DashNodeRequirement.minLabel("forgejo"));
}
@Test
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/install/domain/DownloadHoldTest.java b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/DownloadHoldTest.java
new file mode 100644
index 000000000..ac8dae3f5
--- /dev/null
+++ b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/DownloadHoldTest.java
@@ -0,0 +1,89 @@
+/*
+ * ============================================================================
+ * Name : DownloadHoldTest.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-593. Unit tests for the hold of a module download on
+ * mobile data and with Keep offline.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.domain;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.appdevforall.k2go.install.domain.DownloadHold.Action;
+import org.appdevforall.k2go.install.domain.DownloadHold.Reason;
+import org.appdevforall.k2go.install.domain.DownloadHold.StoppedBy;
+import org.appdevforall.k2go.networkpolicy.domain.NetworkClass;
+import org.junit.Test;
+
+public class DownloadHoldTest {
+
+ /** The A16 case: Wi-Fi drops, the phone moves to 4G, no consent: the running download holds. */
+ @Test
+ public void runningDownloadHoldsOnMobileDataWithoutConsent() {
+ assertEquals(Action.HOLD, DownloadHold.decide(NetworkClass.METERED, false, true, StoppedBy.NOBODY));
+ assertEquals(Reason.METERED_NO_CONSENT, DownloadHold.reason(NetworkClass.METERED, false, true));
+ }
+
+ @Test
+ public void runningDownloadContinuesOnMobileDataWithConsent() {
+ assertEquals(Action.NONE, DownloadHold.decide(NetworkClass.METERED, true, true, StoppedBy.NOBODY));
+ assertNull(DownloadHold.reason(NetworkClass.METERED, true, true));
+ }
+
+ @Test
+ public void heldDownloadContinuesWhenWifiComesBack() {
+ assertEquals(Action.CONTINUE, DownloadHold.decide(NetworkClass.UNMETERED, false, true, StoppedBy.NETWORK));
+ }
+
+ @Test
+ public void heldDownloadContinuesAfterConsent() {
+ assertEquals(Action.CONTINUE, DownloadHold.decide(NetworkClass.METERED, true, true, StoppedBy.NETWORK));
+ }
+
+ @Test
+ public void heldDownloadStaysHeldWhileTheReasonIsTrue() {
+ assertEquals(Action.NONE, DownloadHold.decide(NetworkClass.METERED, false, true, StoppedBy.NETWORK));
+ }
+
+ /** K2GO-588: Keep offline holds the download on any network, Wi-Fi too. */
+ @Test
+ public void keepOfflineHoldsOnWifi() {
+ assertEquals(Action.HOLD, DownloadHold.decide(NetworkClass.UNMETERED, false, false, StoppedBy.NOBODY));
+ assertEquals(Reason.KEPT_OFFLINE, DownloadHold.reason(NetworkClass.UNMETERED, true, false));
+ }
+
+ /** Keep offline is the first reason: allowing it can still leave the mobile data reason. */
+ @Test
+ public void keepOfflineComesBeforeMobileData() {
+ assertEquals(Reason.KEPT_OFFLINE, DownloadHold.reason(NetworkClass.METERED, false, false));
+ assertEquals(Reason.METERED_NO_CONSENT, DownloadHold.reason(NetworkClass.METERED, false, true));
+ }
+
+ /** A user pause is the user's: a network event never continues it and never re-holds it. */
+ @Test
+ public void userPauseIsNeverChangedByTheNetwork() {
+ for (NetworkClass net : NetworkClass.values()) {
+ for (boolean consent : new boolean[]{false, true}) {
+ for (boolean online : new boolean[]{false, true}) {
+ assertEquals(Action.NONE, DownloadHold.decide(net, consent, online, StoppedBy.USER));
+ }
+ }
+ }
+ }
+
+ /** No network is not a hold: the box reconnects by itself and there is no traffic to stop. */
+ @Test
+ public void noNetworkChangesNothing() {
+ assertEquals(Action.NONE, DownloadHold.decide(NetworkClass.NONE, false, true, StoppedBy.NOBODY));
+ assertEquals(Action.NONE, DownloadHold.decide(NetworkClass.NONE, false, true, StoppedBy.NETWORK));
+ }
+
+ @Test
+ public void wifiWithOnlineAllowedRunsFree() {
+ assertEquals(Action.NONE, DownloadHold.decide(NetworkClass.UNMETERED, false, true, StoppedBy.NOBODY));
+ assertNull(DownloadHold.reason(NetworkClass.UNMETERED, false, true));
+ }
+}
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPinTest.java b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPinTest.java
new file mode 100644
index 000000000..09de16c0f
--- /dev/null
+++ b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ForgejoBinaryPinTest.java
@@ -0,0 +1,77 @@
+/*
+ * ============================================================================
+ * Name : ForgejoBinaryPinTest.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-593. Unit tests for the forgejo_version pin in local_vars.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.domain;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class ForgejoBinaryPinTest {
+
+ @Test
+ public void pinWritesOneMarkedLineAfterItRemovesAnOldOne() {
+ assertEquals("sed -i '/# k2go-forgejo-bin$/d' /etc/iiab/local_vars.yml"
+ + " && echo 'forgejo_version: \"17.0.2\" # k2go-forgejo-bin' >> /etc/iiab/local_vars.yml",
+ ForgejoBinaryPin.pinCommand("17.0.2"));
+ }
+
+ @Test
+ public void unpinRemovesOnlyTheMarkedLine() {
+ assertEquals("sed -i '/# k2go-forgejo-bin$/d' /etc/iiab/local_vars.yml", ForgejoBinaryPin.UNPIN);
+ }
+
+ /** The version comes from the box and goes into a root shell command: only X.Y.Z is accepted. */
+ @Test
+ public void onlyAPlainVersionIsPinned() {
+ assertTrue(ForgejoBinaryPin.isVersion("17.0.2"));
+ for (String bad : new String[]{null, "", "latest", "v17.0.2", "17.0", "17.0.2-rc1",
+ "17.0.2'; rm -rf /", "17.0.2\n", "1.2.3 4"}) {
+ assertFalse(String.valueOf(bad), ForgejoBinaryPin.isVersion(bad));
+ assertNull(String.valueOf(bad), ForgejoBinaryPin.pinCommand(bad));
+ }
+ }
+
+ @Test
+ public void ownerPinIsAnUnmarkedVersionLine() {
+ assertEquals("17.0.1", ForgejoBinaryPin.ownerPin(java.util.Arrays.asList(
+ "forgejo_install: True", "forgejo_version: 17.0.1")));
+ assertEquals("17.0.1", ForgejoBinaryPin.ownerPin(java.util.Arrays.asList(
+ "forgejo_version: \"17.0.1\" # keep this release")));
+ assertEquals("17.0.1", ForgejoBinaryPin.ownerPin(java.util.Arrays.asList(
+ "forgejo_version: '16.0.0'", "forgejo_version: 17.0.1"))); // the last one wins
+ }
+
+ @Test
+ public void ourOwnPinLatestAndCommentsAreNotAnOwnerPin() {
+ assertNull(ForgejoBinaryPin.ownerPin(java.util.Arrays.asList(
+ "forgejo_version: \"17.0.2\" # k2go-forgejo-bin")));
+ assertNull(ForgejoBinaryPin.ownerPin(java.util.Arrays.asList("forgejo_version: latest")));
+ assertNull(ForgejoBinaryPin.ownerPin(java.util.Arrays.asList("#forgejo_version: 17.0.1")));
+ assertNull(ForgejoBinaryPin.ownerPin(java.util.Collections.emptyList()));
+ assertNull(ForgejoBinaryPin.ownerPin(null));
+ }
+
+ @Test
+ public void forgejoGoesFirstAndTheOthersKeepTheirOrder() {
+ assertArrayEquals(new String[]{"forgejo", "kiwix", "kolibri"},
+ ForgejoBinaryPin.downloadFirst(new String[]{"kiwix", "forgejo", "kolibri"}));
+ assertArrayEquals(new String[]{"kiwix", "kolibri"},
+ ForgejoBinaryPin.downloadFirst(new String[]{"kiwix", "kolibri"}));
+ }
+
+ @Test
+ public void jobTypeIsTheDashNodeType() {
+ assertEquals("forgejo-bin", ForgejoBinaryPin.JOB_TYPE);
+ assertEquals("forgejo", ForgejoBinaryPin.MODULE);
+ }
+}
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgressTest.java b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgressTest.java
new file mode 100644
index 000000000..97f6fd9c4
--- /dev/null
+++ b/controller/app/src/test/java/org/appdevforall/k2go/install/domain/ModuleDownloadProgressTest.java
@@ -0,0 +1,94 @@
+/*
+ * ============================================================================
+ * Name : ModuleDownloadProgressTest.java
+ * Author : AppDevForAll
+ * Copyright : Copyright (c) 2026 AppDevForAll
+ * Description : K2GO-394, K2GO-593. Unit tests for the module download progress snapshot.
+ * ============================================================================
+ */
+package org.appdevforall.k2go.install.domain;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class ModuleDownloadProgressTest {
+
+ @Test
+ public void activeCarriesPercentSpeedAndTimeLeft() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.active("forgejo", 37, "3.4 MB", 120);
+ assertTrue(p.isActive());
+ assertTrue(p.isRunning());
+ assertEquals(37, p.percent);
+ assertEquals("3.4 MB", p.speed);
+ assertEquals(120, p.etaSeconds);
+ assertEquals(ModuleDownloadProgress.Phase.ACTIVE, p.phase);
+ assertNull(p.holdReason);
+ }
+
+ @Test
+ public void pausedIsRunningWithNoSpeed() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.paused("maps", 14);
+ assertTrue(p.isPaused());
+ assertTrue(p.isRunning());
+ assertEquals(14, p.percent);
+ assertEquals("", p.speed);
+ assertEquals(-1, p.etaSeconds);
+ }
+
+ @Test
+ public void heldKeepsThePercentAndTheReason() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.held("forgejo", 52, DownloadHold.Reason.METERED_NO_CONSENT);
+ assertTrue(p.isHeld());
+ assertTrue(p.isRunning());
+ assertFalse(p.isPaused());
+ assertEquals(52, p.percent);
+ assertEquals(DownloadHold.Reason.METERED_NO_CONSENT, p.holdReason);
+ }
+
+ @Test
+ public void reconnectingCarriesTheCounter() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.reconnecting("maps", 3, 5);
+ assertTrue(p.isReconnecting());
+ assertTrue(p.isRunning());
+ assertEquals(3, p.reconnectAttempt);
+ assertEquals(5, p.reconnectTotal);
+ assertEquals(-1, p.percent); // percent is not known during a reconnect
+ }
+
+ @Test
+ public void completeIsNotRunning() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.complete("forgejo");
+ assertTrue(p.isComplete());
+ assertFalse(p.isRunning());
+ assertEquals(100, p.percent);
+ }
+
+ @Test
+ public void noneIsNotRunningAndBelongsToNoModule() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.none();
+ assertFalse(p.isRunning());
+ assertEquals(ModuleDownloadProgress.Phase.NONE, p.phase);
+ assertEquals(-1, p.percent);
+ assertFalse(p.isFor("maps"));
+ assertFalse(p.isFor(null));
+ }
+
+ @Test
+ public void isForMatchesOnlyItsModule() {
+ ModuleDownloadProgress p = ModuleDownloadProgress.active("forgejo", 1, "", -1);
+ assertTrue(p.isFor("forgejo"));
+ assertFalse(p.isFor("maps"));
+ }
+
+ /** Percent is clamped to 0..100, a negative percent or time left means "unknown" (-1). */
+ @Test
+ public void valuesAreClamped() {
+ assertEquals(100, ModuleDownloadProgress.active("maps", 150, "1 MB", -1).percent);
+ assertEquals(-1, ModuleDownloadProgress.active("maps", -5, "1 MB", -1).percent);
+ assertEquals(-1, ModuleDownloadProgress.active("maps", 5, "1 MB", -9).etaSeconds);
+ }
+}
diff --git a/controller/app/src/test/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgressTest.java b/controller/app/src/test/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgressTest.java
deleted file mode 100644
index 1e127f4a3..000000000
--- a/controller/app/src/test/java/org/appdevforall/k2go/maps/domain/MapsDownloadProgressTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * ============================================================================
- * Name : MapsDownloadProgressTest.java
- * Author : AppDevForAll
- * Copyright : Copyright (c) 2026 AppDevForAll
- * Description : K2GO-394. Unit tests for the maps download progress snapshot.
- * ============================================================================
- */
-package org.appdevforall.k2go.maps.domain;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class MapsDownloadProgressTest {
-
- @Test
- public void activeCarriesPercentAndSpeed() {
- MapsDownloadProgress p = MapsDownloadProgress.active(37, "3.4 MB");
- assertTrue(p.isActive());
- assertTrue(p.isRunning());
- assertEquals(37, p.percent);
- assertEquals("3.4 MB", p.speed);
- assertEquals(MapsDownloadProgress.Phase.ACTIVE, p.phase);
- }
-
- @Test
- public void pausedIsRunningWithNoSpeed() {
- MapsDownloadProgress p = MapsDownloadProgress.paused(14);
- assertTrue(p.isPaused());
- assertTrue(p.isRunning());
- assertEquals(14, p.percent);
- assertEquals("", p.speed);
- }
-
- @Test
- public void reconnectingCarriesTheCounter() {
- MapsDownloadProgress p = MapsDownloadProgress.reconnecting(3, 5);
- assertTrue(p.isReconnecting());
- assertTrue(p.isRunning());
- assertEquals(3, p.reconnectAttempt);
- assertEquals(5, p.reconnectTotal);
- assertEquals(-1, p.percent); // percent is not known during a reconnect
- }
-
- @Test
- public void completeIsNotRunning() {
- MapsDownloadProgress p = MapsDownloadProgress.complete();
- assertTrue(p.isComplete());
- assertFalse(p.isRunning());
- assertEquals(100, p.percent);
- }
-
- @Test
- public void noneIsNotRunning() {
- MapsDownloadProgress p = MapsDownloadProgress.none();
- assertFalse(p.isRunning());
- assertEquals(MapsDownloadProgress.Phase.NONE, p.phase);
- assertEquals(-1, p.percent);
- }
-
- /** Percent is clamped to 0..100, and a negative percent means "unknown" (-1). */
- @Test
- public void percentIsClamped() {
- assertEquals(100, MapsDownloadProgress.active(150, "1 MB").percent);
- assertEquals(-1, MapsDownloadProgress.active(-5, "1 MB").percent);
- }
-}
diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md
index 8ee40e52d..2e6b43792 100644
--- a/static/dashboard/CHANGELOG.md
+++ b/static/dashboard/CHANGELOG.md
@@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i
(the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this
file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`.
+- **1.6.5** - New job type `forgejo-bin` (`POST /forgejo-bin/download` with `{"ids":["forgejo"]}`): downloads the Forgejo binary of the latest release (the codeberg API, as the forgejo role) with aria2 to `/library/forgejo/bin/forgejo-`, with percent, speed, time left, pause, resume, "Reconnecting n/5", and a cancel that removes the partial. The file is checked against the release's published sha-256; a file that does not match is downloaded again. The job `result` gives `{"version"}`, so the app pins `forgejo_version` and the role skips its own download. (K2GO-593)
- **1.6.4** - Admin passwords change inside Kolibri, Calibre-Web and Forgejo, not only in the stored copy: `POST /credentials/:service/password` (one rule for all three: 8+ characters with upper case, lower case, digit and symbol), `POST /credentials/:service/reset` (the factory password, also when the current one is lost), and `GET /credentials/:service/status` (`ok`, `mismatch` or `unreachable`, plus whether the factory password still signs in; a live sign-in, never stored). (K2GO-552)
- **1.6.3** - The `/v1` relay to conex-core forwards the `X-Share-Token` header (never logged). Before, it was dropped, so the sender's close (`DELETE /v1/share/`) got 401 and the share token stayed valid after Done. (K2GO-577)
- **1.6.2** - Box logs no longer identify the user, on boxes installed before bake patches 0010-0012 (K2GO-559). At its first start, dash-node applies the same change once: nginx access log without client IP and User-Agent (`/etc/nginx/nginx.conf`), Forgejo router log off (`LOGGER_ROUTER_MODE` empty in `app.ini`), Calibre-Web log level DEBUG -> INFO (`app.db`). A value an admin changed is kept. Each change applies at the service restart (Forgejo: at the next app open, as a pending privacy change; nginx and Calibre-Web: at the next box start). After that restart, the older logs of each changed service are removed once (rotated copies deleted, live log emptied). Markers: `/library/dashboard/log-less.done`, `/library/dashboard/log-less-purge.done`. No REST change. (K2GO-559)
diff --git a/static/dashboard/package.json b/static/dashboard/package.json
index fdb909307..1135b8e14 100644
--- a/static/dashboard/package.json
+++ b/static/dashboard/package.json
@@ -1,11 +1,11 @@
{
"name": "dashboard-console",
- "version": "1.6.4",
+ "version": "1.6.5",
"description": "",
"main": "index.js",
"scripts": {
"test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts sockets/passwords.test.ts sockets/net-retry.test.ts sockets/services.test.ts sockets/log-rotate.test.ts sockets/rebuild-status.test.ts sockets/conex-proxy.test.ts sockets/maps.fqr-behavior.test.ts sockets/privacy.test.ts sockets/log-less.test.ts",
- "test:db": "node --require ts-node/register --test sockets/jobs.test.ts",
+ "test:db": "node --require ts-node/register --test sockets/jobs.test.ts sockets/forgejo-bin.test.ts",
"typecheck": "tsc --noEmit",
"build": "tsc",
"start": "node dist/server.js"
diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts
index 222bd768f..6b9f67904 100644
--- a/static/dashboard/routes.ts
+++ b/static/dashboard/routes.ts
@@ -44,7 +44,7 @@ const ZIMS_DIR = '/library/zims/content/';
const KIWIX_INDEXER = '/usr/bin/iiab-make-kiwix-lib';
const ZIM_NAME_RE = /^[A-Za-z0-9._-]{1,150}\.zim$/;
-const VALID_TYPES: JobType[] = ['kiwix', 'maps', 'books', 'kolibri', 'basemaps', 'code-assets', 'code-addons', 'forgejo'];
+const VALID_TYPES: JobType[] = ['kiwix', 'maps', 'books', 'kolibri', 'basemaps', 'code-assets', 'code-addons', 'forgejo', 'forgejo-bin'];
function isType(t: string): t is JobType {
return (VALID_TYPES as string[]).includes(t);
}
@@ -1247,7 +1247,8 @@ apiRouter.post('/:type/download', (req: Request, res: Response): void => {
// K2GO-443: these types must run one job at a time: code-assets / code-addons stage into ONE shared
// tree (/library/www/.new), and forgejo fetches+pushes the same repo set (two concurrent runs
// would race the staging / the repos). The app re-attaches via start-or-attach; this is the hard guard.
- const SINGLE_RUN_TYPES = ['code-assets', 'code-addons', 'forgejo'];
+ // K2GO-593: forgejo-bin writes one partial file.
+ const SINGLE_RUN_TYPES = ['code-assets', 'code-addons', 'forgejo', 'forgejo-bin'];
if (SINGLE_RUN_TYPES.includes(type)
&& jobs.list(type).some((j) =>
['queued', 'downloading', 'indexing', 'processing', 'paused'].includes(j.phase))) {
diff --git a/static/dashboard/server.ts b/static/dashboard/server.ts
index 44cc79d96..8db626188 100644
--- a/static/dashboard/server.ts
+++ b/static/dashboard/server.ts
@@ -13,6 +13,7 @@ import './sockets/kolibri.exec';
import './sockets/code_assets.exec'; // K2GO-443: build-assets runner (aria2 job engine)
import './sockets/code_addons.exec'; // K2GO-443: add-ons gallery runner (aria2 job engine)
import './sockets/forgejo.exec'; // K2GO-443: forgejo repo-refresh runner (git, per-repo progress)
+import './sockets/forgejo-bin.exec'; // K2GO-593: forgejo binary download before the module install
import { apiRouter } from './routes';
import { startServiceHeal } from './sockets/service-heal';
import { startLogRotation, stopLogRotation } from './sockets/log-rotate';
diff --git a/static/dashboard/sockets/forgejo-bin.exec.ts b/static/dashboard/sockets/forgejo-bin.exec.ts
new file mode 100644
index 000000000..5398b7e5d
--- /dev/null
+++ b/static/dashboard/sockets/forgejo-bin.exec.ts
@@ -0,0 +1,209 @@
+// sockets/forgejo-bin.exec.ts - K2GO-593
+//
+// Forgejo binary runner for the durable job engine. The forgejo role downloads a ~100 MB binary with
+// Ansible get_url: no percent, no pause, no resume, and it runs after `pdsm stop`, which also stops
+// dash-node. The app runs this job BEFORE the stop. It puts the binary at the path the role uses
+// (/library/forgejo/bin/forgejo-), and the app pins forgejo_version= in local_vars, so the
+// role's get_url finds the file and skips the download. The role still downloads the .asc and does
+// its GPG check (fail closed) on this file.
+//
+// The box resolves the version (the same codeberg API as the role) and makes the URL; the app sends
+// no URL. aria2 downloads into bin/.k2go-download (under the URL's file name: the canonical flags have
+// -Z, and aria2 ignores `out` with -Z), and the runner moves the file to forgejo- at the end, so
+// the final name exists only for a complete file (a partial there would make get_url skip and the GPG
+// check fail). Before the move, the file is checked against the release's published sha-256
+// (forgejo_sha256_url in the role): a wrong file at the final name would fail the GPG check on every
+// Retry.
+import { jobs, RunnerContext, PausedError, CanceledError } from './jobs';
+import { downloadWithAria2, stopError } from './aria2-download';
+import { withRetry } from './net-retry';
+import crypto from 'crypto';
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+
+/** forgejo_root_directory/bin in roles/forgejo/defaults/main.yml. */
+const BIN_DIR = process.env.K2GO_FORGEJO_BIN_DIR || '/library/forgejo/bin';
+/** forgejo_releases_api in the role. */
+const RELEASES_API = 'https://codeberg.org/api/v1/repos/forgejo/forgejo/releases/latest';
+const DOWNLOAD_BASE = 'https://codeberg.org/forgejo/forgejo/releases/download';
+// K2G-P5: a neutral agent, the same one books.exec.ts sends.
+const USER_AGENT = 'K2Go Dashboard/1.0 (https://github.com/appdevforall/KnowledgeToGo)';
+const API_TIMEOUT_MS = 20_000;
+/** Not forgejo-*, so the role's cleanup of superseded binaries never matches it. */
+const STAGE_NAME = '.k2go-download';
+const RETRY_DELAYS = [3_000, 6_000, 9_000, 18_000, 36_000];
+
+/** The role's iset_suffixes map, keyed on `uname -m` (os.machine), the value the role reads. */
+const ISET_SUFFIXES: Record = {
+ x86_64: 'amd64',
+ aarch64: 'arm64',
+ armv7l: 'arm-6',
+ armv6l: 'arm-6',
+ armv8l: 'arm-6',
+};
+
+export function forgejoSuffix(machine: string): string | null {
+ return ISET_SUFFIXES[machine] ?? null;
+}
+
+/** The role's assert: forgejo_version is X.Y.Z. Also keeps the value safe for a path and a URL. */
+export function isForgejoVersion(v: unknown): v is string {
+ return typeof v === 'string' && /^[0-9]+\.[0-9]+\.[0-9]+$/.test(v);
+}
+
+/** forgejo_download_url in the role. */
+export function forgejoUrl(version: string, suffix: string): string {
+ return `${DOWNLOAD_BASE}/v${version}/forgejo-${version}-linux-${suffix}`;
+}
+
+export function finalPath(dir: string, version: string): string {
+ return path.join(dir, `forgejo-${version}`);
+}
+
+export function stageDir(binDir: string): string {
+ return path.join(binDir, STAGE_NAME);
+}
+
+/**
+ * Remove the partial downloads in binDir's staging folder, except the files of keepVersion
+ * (forgejo--linux- and its .aria2 control file). Never touches a binary in binDir itself.
+ */
+export function removePartials(binDir: string, keepVersion: string | null = null): void {
+ const dir = stageDir(binDir);
+ let names: string[] = [];
+ try { names = fs.readdirSync(dir); } catch { return; }
+ for (const n of names) {
+ if (keepVersion !== null && n.startsWith(`forgejo-${keepVersion}-linux-`)) continue;
+ try { fs.rmSync(path.join(dir, n), { recursive: true, force: true }); } catch { /* best effort */ }
+ }
+}
+
+/** One GET with the neutral agent, a timeout, and the job's stop signal. */
+async function fetchText(ctx: RunnerContext, url: string, accept: string): Promise<{ status: number; text: string }> {
+ const ac = new AbortController();
+ const onStop = () => ac.abort();
+ ctx.signal.addEventListener('abort', onStop, { once: true });
+ const timer = setTimeout(() => ac.abort(), API_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, { headers: { 'User-Agent': USER_AGENT, Accept: accept }, signal: ac.signal });
+ return { status: res.status, text: await res.text() };
+ } finally {
+ clearTimeout(timer);
+ ctx.signal.removeEventListener('abort', onStop);
+ }
+}
+
+/** Not worth a retry: the server answered, and the answer is wrong. */
+class BadAnswer extends Error {}
+
+/** The tag of the latest Forgejo release, without the leading "v" (the role's regex_replace). */
+async function latestVersion(ctx: RunnerContext): Promise {
+ const { status, text } = await fetchText(ctx, RELEASES_API, 'application/json');
+ if (status !== 200) throw new Error(`release lookup failed: HTTP ${status}`);
+ let tag: unknown;
+ try { tag = (JSON.parse(text) as { tag_name?: unknown }).tag_name; } catch { tag = undefined; }
+ const version = typeof tag === 'string' ? tag.replace(/^v/, '') : '';
+ if (!isForgejoVersion(version)) throw new BadAnswer(`release lookup gave a bad version: ${String(tag)}`);
+ return version;
+}
+
+/** The first field of a `sha256sum` line ("<64 hex> "), or null. */
+export function parseSha256(text: string): string | null {
+ const m = /^([0-9a-fA-F]{64})(\s|$)/.exec(text.trim());
+ return m ? m[1].toLowerCase() : null;
+}
+
+/** The release's published sha-256 (forgejo_sha256_url in the role), or null when it has none (404). */
+async function releaseSha256(ctx: RunnerContext, url: string): Promise {
+ const { status, text } = await fetchText(ctx, `${url}.sha256`, 'text/plain');
+ if (status === 404) return null;
+ if (status !== 200) throw new Error(`checksum lookup failed: HTTP ${status}`);
+ const sha = parseSha256(text);
+ if (!sha) throw new BadAnswer('the checksum file is not a sha-256 line');
+ return sha;
+}
+
+export function fileSha256(file: string): Promise {
+ return new Promise((resolve, reject) => {
+ const h = crypto.createHash('sha256');
+ fs.createReadStream(file).on('error', reject).on('data', (c) => h.update(c)).on('end', () => resolve(h.digest('hex')));
+ });
+}
+
+async function lookup(ctx: RunnerContext, fn: () => Promise): Promise {
+ try {
+ const v = await withRetry(fn, {
+ delaysMs: RETRY_DELAYS,
+ signal: ctx.signal,
+ isCanceled: ctx.isCanceled,
+ isTransient: (e) => !(e instanceof BadAnswer),
+ onRetry: ({ attempt }) => ctx.reportRetry(attempt, RETRY_DELAYS.length),
+ });
+ ctx.reportRetry(0, 0);
+ return v;
+ } catch (e) {
+ const se = stopError(ctx);
+ if (se) throw se;
+ throw e;
+ }
+}
+
+const forgejoBinRunner: (ctx: RunnerContext) => Promise = async (ctx) => {
+ const suffix = forgejoSuffix(os.machine());
+ if (!suffix) throw new Error(`no Forgejo binary for CPU architecture ${os.machine()}`);
+
+ ctx.update({ phase: 'downloading', percent: -1, speed: 0, eta: -1, detail: 'forgejo version' });
+ const version = await lookup(ctx, () => latestVersion(ctx));
+ const url = forgejoUrl(version, suffix);
+ const sha = await lookup(ctx, () => releaseSha256(ctx, url));
+ if (!sha) ctx.log(`[forgejo-bin] no published sha-256 for ${version}; the role GPG check still runs`);
+ const result = JSON.stringify({ version });
+
+ fs.mkdirSync(BIN_DIR, { recursive: true });
+ removePartials(BIN_DIR, version); // a partial of an older release cannot be resumed
+ const dest = finalPath(BIN_DIR, version);
+ if (fs.existsSync(dest)) {
+ // A wrong file here would fail the role's GPG check on every Retry, so it must not be kept.
+ if (sha && await fileSha256(dest) !== sha) {
+ ctx.log(`[forgejo-bin] ${path.basename(dest)} does not match the release sha-256; downloading it again`);
+ fs.rmSync(dest, { force: true });
+ } else {
+ removePartials(BIN_DIR);
+ ctx.log(`[forgejo-bin] ${path.basename(dest)} is already there`);
+ ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: version, result });
+ return;
+ }
+ }
+
+ const stage = stageDir(BIN_DIR);
+ const staged = path.join(stage, path.basename(url));
+ fs.mkdirSync(stage, { recursive: true });
+ ctx.update({ phase: 'downloading', percent: -1, speed: 0, eta: -1, detail: version });
+ try {
+ await downloadWithAria2(ctx, { destDir: stage, urls: [url] });
+ } catch (e) {
+ const se = stopError(ctx);
+ if (se instanceof PausedError) throw se; // keep the partial: Resume continues it
+ if (se instanceof CanceledError) { removePartials(BIN_DIR); throw se; }
+ throw e; // keep the partial: Retry continues it
+ }
+
+ if (!fs.existsSync(staged) || fs.existsSync(`${staged}.aria2`)) {
+ throw new Error('the Forgejo download did not complete');
+ }
+ if (sha && await fileSha256(staged) !== sha) {
+ removePartials(BIN_DIR); // wrong bytes: a Retry must start from 0
+ throw new Error('the Forgejo download does not match the release sha-256');
+ }
+ fs.renameSync(staged, dest);
+ fs.chmodSync(dest, 0o775); // the role's get_url mode
+ removePartials(BIN_DIR);
+ ctx.update({ phase: 'done', percent: 100, speed: 0, eta: -1, detail: version, result });
+};
+
+jobs.registerRunner('forgejo-bin', forgejoBinRunner);
+// A Cancel of a PAUSED job: its runner already exited and kept the partial for Resume.
+jobs.registerDiscard('forgejo-bin', () => removePartials(BIN_DIR));
+
+export { forgejoBinRunner };
diff --git a/static/dashboard/sockets/forgejo-bin.test.ts b/static/dashboard/sockets/forgejo-bin.test.ts
new file mode 100644
index 000000000..5ac5bf646
--- /dev/null
+++ b/static/dashboard/sockets/forgejo-bin.test.ts
@@ -0,0 +1,259 @@
+///
+// K2GO-593: the forgejo-bin runner. Loads jobs.ts (sqlite), so it runs in `npm run test:db`.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { EventEmitter } from 'events';
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'k2go-forgejo-bin-'));
+const BIN = path.join(tmp, 'bin');
+process.env.K2GO_FORGEJO_BIN_DIR = BIN;
+process.env.K2GO_JOBS_DB = path.join(tmp, 'jobs.db');
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const mod = require('./forgejo-bin.exec') as typeof import('./forgejo-bin.exec');
+const { forgejoSuffix, isForgejoVersion, forgejoUrl, removePartials, forgejoBinRunner, parseSha256 } = mod;
+import type { RunnerContext, JobUpdate } from './jobs';
+import { CanceledError } from './jobs';
+import crypto from 'crypto';
+
+const SUFFIX = forgejoSuffix(os.machine());
+const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
+
+/** The release API answers `tag`; the .sha256 file answers `sha` (null = the release has none, 404). */
+function stubFetch(tag: unknown, seen: Array>, sha: string | null = null): () => void {
+ const orig = globalThis.fetch;
+ globalThis.fetch = (async (url: unknown, init?: { headers?: Record }) => {
+ seen.push(init?.headers ?? {});
+ if (String(url).endsWith('.sha256')) {
+ return sha === null ? new Response('not found', { status: 404 })
+ : new Response(`${sha} forgejo-17.0.2-linux-${SUFFIX}\n`, { status: 200 });
+ }
+ return new Response(JSON.stringify({ tag_name: tag }), { status: 200 });
+ }) as typeof fetch;
+ return () => { globalThis.fetch = orig; };
+}
+
+/** A fake aria2: it writes the files it is told to, then exits as the test says. */
+function fakeCtx(onSpawn: (args: string[], child: EventEmitter & { stdout: EventEmitter; stderr: EventEmitter }) => void) {
+ const updates: JobUpdate[] = [];
+ const state = { canceled: false, paused: false, spawned: 0 };
+ const ac = new AbortController();
+ const ctx = {
+ job: { id: 'forgejo-bin-test' },
+ items: ['forgejo'],
+ ids: ['forgejo'],
+ update: (p: JobUpdate) => { updates.push(p); },
+ isCanceled: () => state.canceled,
+ throwIfCanceled: () => { if (state.canceled) throw new CanceledError(); },
+ isPaused: () => state.paused,
+ signal: ac.signal,
+ spawn: (_cmd: string, args: string[]) => {
+ state.spawned++;
+ const child = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter() });
+ setImmediate(() => onSpawn(args, child));
+ return child;
+ },
+ log: () => { /* quiet */ },
+ reportRetry: () => { /* not checked here */ },
+ } as unknown as RunnerContext;
+ return { ctx, updates, state, ac };
+}
+
+function reset(): void {
+ fs.rmSync(BIN, { recursive: true, force: true });
+}
+
+test('forgejoSuffix uses the role iset_suffixes map', () => {
+ assert.equal(forgejoSuffix('aarch64'), 'arm64');
+ assert.equal(forgejoSuffix('armv7l'), 'arm-6');
+ assert.equal(forgejoSuffix('armv8l'), 'arm-6'); // 32-bit userland on a 64-bit kernel
+ assert.equal(forgejoSuffix('x86_64'), 'amd64');
+ assert.equal(forgejoSuffix('i686'), null);
+});
+
+test('isForgejoVersion accepts only X.Y.Z', () => {
+ assert.equal(isForgejoVersion('17.0.2'), true);
+ for (const bad of ['v17.0.2', '17.0', '17.0.2-rc1', '../1.2.3', '', null, 17]) {
+ assert.equal(isForgejoVersion(bad), false, String(bad));
+ }
+});
+
+test('forgejoUrl is the role forgejo_download_url', () => {
+ assert.equal(forgejoUrl('17.0.2', 'arm64'),
+ 'https://codeberg.org/forgejo/forgejo/releases/download/v17.0.2/forgejo-17.0.2-linux-arm64');
+});
+
+const STAGE = path.join(BIN, '.k2go-download');
+const STAGED = path.join(STAGE, `forgejo-17.0.2-linux-${SUFFIX}`);
+
+test('removePartials empties the staging folder except keepVersion, and never touches bin itself', () => {
+ reset();
+ fs.mkdirSync(STAGE, { recursive: true });
+ for (const n of ['forgejo-17.0.2', 'forgejo-17.0.2.asc']) fs.writeFileSync(path.join(BIN, n), 'x');
+ for (const n of ['forgejo-17.0.1-linux-arm64', 'forgejo-17.0.1-linux-arm64.aria2',
+ 'forgejo-17.0.2-linux-arm64', 'forgejo-17.0.2-linux-arm64.aria2']) fs.writeFileSync(path.join(STAGE, n), 'x');
+ removePartials(BIN, '17.0.2');
+ assert.deepEqual(fs.readdirSync(STAGE).sort(), ['forgejo-17.0.2-linux-arm64', 'forgejo-17.0.2-linux-arm64.aria2']);
+ removePartials(BIN);
+ assert.deepEqual(fs.readdirSync(STAGE), []);
+ assert.deepEqual(fs.readdirSync(BIN).sort(), ['.k2go-download', 'forgejo-17.0.2', 'forgejo-17.0.2.asc']);
+});
+
+test('runner: a binary that is already there ends the job with no download', { skip: !SUFFIX }, async () => {
+ reset();
+ fs.mkdirSync(STAGE, { recursive: true });
+ fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2'), 'binary');
+ fs.writeFileSync(STAGED, 'old partial');
+ fs.writeFileSync(`${STAGED}.aria2`, 'ctl');
+ const headers: Array> = [];
+ const restore = stubFetch('v17.0.2', headers);
+ try {
+ const { ctx, updates, state } = fakeCtx(() => assert.fail('no aria2 expected'));
+ await forgejoBinRunner(ctx);
+ assert.equal(state.spawned, 0);
+ assert.deepEqual(fs.readdirSync(STAGE), []); // an old partial is removed
+ const last = updates[updates.length - 1];
+ assert.equal(last.phase, 'done');
+ assert.deepEqual(JSON.parse(String(last.result)), { version: '17.0.2' });
+ assert.match(headers[0]['User-Agent'], /^K2Go Dashboard\//); // K2G-P5: neutral agent
+ } finally { restore(); }
+});
+
+test('runner: a bad release tag fails at once, with no retry', { skip: !SUFFIX }, async () => {
+ reset();
+ const headers: Array> = [];
+ const restore = stubFetch('nightly', headers);
+ try {
+ const { ctx } = fakeCtx(() => assert.fail('no aria2 expected'));
+ await assert.rejects(forgejoBinRunner(ctx), /bad version/);
+ assert.equal(headers.length, 1);
+ } finally { restore(); }
+});
+
+test('runner: aria2 downloads the URL into the staging folder; the file moves to the final name, mode 0775', { skip: !SUFFIX }, async () => {
+ reset();
+ const restore = stubFetch('v17.0.2', [], sha256('binary'));
+ try {
+ const { ctx, updates } = fakeCtx((args, child) => {
+ assert.equal(args[args.indexOf('-d') + 1], STAGE);
+ assert.ok(args.includes(`https://codeberg.org/forgejo/forgejo/releases/download/v17.0.2/forgejo-17.0.2-linux-${SUFFIX}`));
+ fs.writeFileSync(STAGED, 'binary');
+ child.emit('exit', 0, null);
+ });
+ await forgejoBinRunner(ctx);
+ assert.deepEqual(fs.readdirSync(BIN).sort(), ['.k2go-download', 'forgejo-17.0.2']);
+ assert.deepEqual(fs.readdirSync(STAGE), []);
+ if (process.platform !== 'win32') {
+ assert.equal(fs.statSync(path.join(BIN, 'forgejo-17.0.2')).mode & 0o777, 0o775);
+ }
+ assert.equal(updates[updates.length - 1].phase, 'done');
+ } finally { restore(); }
+});
+
+test('runner: an aria2 run that leaves its control file is not complete', { skip: !SUFFIX }, async () => {
+ reset();
+ const restore = stubFetch('v17.0.2', []);
+ try {
+ const { ctx } = fakeCtx((_args, child) => {
+ fs.writeFileSync(STAGED, 'half');
+ fs.writeFileSync(`${STAGED}.aria2`, 'ctl');
+ child.emit('exit', 0, null);
+ });
+ await assert.rejects(forgejoBinRunner(ctx), /did not complete/);
+ assert.equal(fs.existsSync(path.join(BIN, 'forgejo-17.0.2')), false);
+ assert.equal(fs.existsSync(STAGED), true); // kept for Retry
+ } finally { restore(); }
+});
+
+test('runner: Cancel removes the partial and its control file', { skip: !SUFFIX }, async () => {
+ reset();
+ const restore = stubFetch('v17.0.2', []);
+ try {
+ const box: { state?: { canceled: boolean } } = {};
+ const { ctx, state } = fakeCtx((_args, child) => {
+ fs.writeFileSync(STAGED, 'half');
+ fs.writeFileSync(`${STAGED}.aria2`, 'ctl');
+ box.state!.canceled = true;
+ child.emit('exit', null, 'SIGKILL');
+ });
+ box.state = state;
+ await assert.rejects(forgejoBinRunner(ctx), CanceledError);
+ assert.deepEqual(fs.readdirSync(STAGE), []);
+ assert.equal(fs.existsSync(path.join(BIN, 'forgejo-17.0.2')), false);
+ } finally { restore(); }
+});
+
+test('runner: Pause keeps the partial for Resume', { skip: !SUFFIX }, async () => {
+ reset();
+ const restore = stubFetch('v17.0.2', []);
+ try {
+ const box: { state?: { paused: boolean } } = {};
+ const { ctx, state } = fakeCtx((_args, child) => {
+ fs.writeFileSync(STAGED, 'half');
+ fs.writeFileSync(`${STAGED}.aria2`, 'ctl');
+ box.state!.paused = true;
+ child.emit('exit', null, 'SIGTERM');
+ });
+ box.state = state;
+ await assert.rejects(forgejoBinRunner(ctx), /paused/);
+ assert.deepEqual(fs.readdirSync(STAGE).sort(), [path.basename(STAGED), `${path.basename(STAGED)}.aria2`]);
+ } finally { restore(); }
+});
+
+test('parseSha256 reads the first field of a sha256sum line', () => {
+ const h = 'A'.repeat(64);
+ assert.equal(parseSha256(`${h} forgejo-17.0.2-linux-arm64\n`), 'a'.repeat(64));
+ assert.equal(parseSha256(h), 'a'.repeat(64));
+ assert.equal(parseSha256('not found'), null);
+ assert.equal(parseSha256('abc file'), null);
+});
+
+test('runner: a file that matches the release sha-256 is kept', { skip: !SUFFIX }, async () => {
+ reset();
+ fs.mkdirSync(BIN, { recursive: true });
+ fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2'), 'binary');
+ const restore = stubFetch('v17.0.2', [], sha256('binary'));
+ try {
+ const { ctx, updates, state } = fakeCtx(() => assert.fail('no aria2 expected'));
+ await forgejoBinRunner(ctx);
+ assert.equal(state.spawned, 0);
+ assert.equal(updates[updates.length - 1].phase, 'done');
+ } finally { restore(); }
+});
+
+test('runner: a file that does not match the release sha-256 is downloaded again', { skip: !SUFFIX }, async () => {
+ reset();
+ fs.mkdirSync(BIN, { recursive: true });
+ fs.writeFileSync(path.join(BIN, 'forgejo-17.0.2'), 'corrupt');
+ const restore = stubFetch('v17.0.2', [], sha256('binary'));
+ try {
+ const { ctx, state } = fakeCtx((_args, child) => {
+ assert.equal(fs.existsSync(path.join(BIN, 'forgejo-17.0.2')), false); // the wrong file is gone
+ fs.writeFileSync(STAGED, 'binary');
+ child.emit('exit', 0, null);
+ });
+ await forgejoBinRunner(ctx);
+ assert.equal(state.spawned, 1);
+ assert.equal(fs.readFileSync(path.join(BIN, 'forgejo-17.0.2'), 'utf8'), 'binary');
+ } finally { restore(); }
+});
+
+test('runner: a download that does not match the release sha-256 is removed', { skip: !SUFFIX }, async () => {
+ reset();
+ const restore = stubFetch('v17.0.2', [], sha256('binary'));
+ try {
+ const { ctx } = fakeCtx((_args, child) => {
+ fs.writeFileSync(STAGED, 'wrong');
+ child.emit('exit', 0, null);
+ });
+ await assert.rejects(forgejoBinRunner(ctx), /does not match the release sha-256/);
+ assert.deepEqual(fs.readdirSync(STAGE), []);
+ assert.equal(fs.existsSync(path.join(BIN, 'forgejo-17.0.2')), false);
+ } finally { restore(); }
+});
+
+// The sqlite file stays open in this process (Windows refuses the delete), so the delete is best effort.
+test.after(() => { try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ } });
diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts
index bba5b843e..9d85ca698 100644
--- a/static/dashboard/sockets/jobs.ts
+++ b/static/dashboard/sockets/jobs.ts
@@ -13,7 +13,7 @@ import fs from 'fs';
import path from 'path';
import { RollingLog, LogSlice } from './rolling-log';
-export type JobType = 'kiwix' | 'maps' | 'books' | 'kolibri' | 'basemaps' | 'code-assets' | 'code-addons' | 'forgejo';
+export type JobType = 'kiwix' | 'maps' | 'books' | 'kolibri' | 'basemaps' | 'code-assets' | 'code-addons' | 'forgejo' | 'forgejo-bin';
export type JobPhase =
| 'queued' | 'downloading' | 'indexing' | 'processing'
// ADFA-4894 (control surface): 'paused' is a stopped-but-resumable state — like 'canceled' it