Skip to main content

agentmux_srv_core/backend/update/
download.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Downloading and staging a newer release
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §4, phase 3a).
6//!
7//! Only what the update check found: the release file for this install
8//! (`update::install`), from `github.com/agentmuxai/agentmux/releases`, which
9//! must match the SHA-256 GitHub lists for it. Nothing here names a URL or a
10//! file of its own, and nothing is installed: a Windows portable release is
11//! unpacked into a new folder next to the running one, ready for the launcher
12//! to start (phase 3b); a `setup.exe` install's installer is kept, verified,
13//! in this version's `updates/<version>/`, for the launcher to run (phase 3d);
14//! a Linux portable's tarball is unpacked into `AgentMux-<version>` next to the
15//! running folder, and an AppImage's next version is put beside it, executable
16//! (phase 3e). Progress and the result go out as the `app:updatestatus` event
17//! (`update::check`).
18//!
19//! The download is kept in `updates/<version>/` in this version's data folder
20//! (`AGENTMUX_DATA_HOME`, `channels/<ch>/versions/<v>/data`) while it runs and
21//! deleted once unpacked. Its file and the unpacking folder carry this
22//! process' id, so two AgentMux instances downloading the same release never
23//! write over each other; whichever stages the folder first, the other uses.
24//! On Windows srv decodes the release's `.7z` itself (`update::unpack`,
25//! refusing `..`, absolute and drive paths): Windows 10's own `tar.exe` is
26//! libarchive without LZMA, so it can't read the release's LZMA2 + BCJ2 archive
27//! (`docs/specs/SPEC_UPDATE_UNPACK_7Z_IN_RUST_2026_10_19.md`). On Linux it is
28//! the system's `tar` (with `xz` for the `.tar.xz`).
29
30use std::path::{Path, PathBuf};
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::time::Duration;
33
34use sha2::{Digest, Sha256};
35use tokio::io::AsyncWriteExt;
36
37use crate::backend::update::check::{self, AppUpdateStatus, DownloadStatus, ReleaseAsset};
38use crate::backend::update::install::InstallKind;
39
40/// Release files come only from here (`browser_download_url`).
41pub(crate) const RELEASE_DOWNLOAD_PREFIX: &str = "https://github.com/agentmuxai/agentmux/releases/download/";
42const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
43/// No answer, or no bytes, for this long ends the download.
44const STALL_TIMEOUT: Duration = Duration::from_secs(60);
45/// Unpacking takes seconds; this only stops a hung `tar`.
46const UNPACK_TIMEOUT: Duration = Duration::from_secs(10 * 60);
47/// A download file or unpacking folder untouched this long was left by a
48/// run that was cut short (a crash, a quit): a live run writes continuously.
49const ABANDONED_AFTER: Duration = Duration::from_secs(60 * 60);
50
51static RUNNING: AtomicBool = AtomicBool::new(false);
52
53/// Hashes and counts a download as it arrives.
54struct Received {
55    hasher: Sha256,
56    bytes: u64,
57    expected: u64,
58}
59
60impl Received {
61    fn new(expected: u64) -> Self {
62        Self { hasher: Sha256::new(), bytes: 0, expected }
63    }
64
65    fn push(&mut self, chunk: &[u8]) -> Result<(), String> {
66        self.bytes += chunk.len() as u64;
67        if self.bytes > self.expected {
68            return Err("the download is larger than GitHub lists it".into());
69        }
70        self.hasher.update(chunk);
71        Ok(())
72    }
73
74    /// Whether what arrived is exactly the file GitHub lists.
75    fn finish(self, sha256: &str) -> Result<(), String> {
76        if self.bytes != self.expected {
77            return Err(format!("the download stopped at {} of {} bytes", self.bytes, self.expected));
78        }
79        if !hex::encode(self.hasher.finalize()).eq_ignore_ascii_case(sha256) {
80            return Err("the download doesn't match the checksum GitHub lists for it".into());
81        }
82        Ok(())
83    }
84}
85
86/// What a download leaves ready: a portable's new folder, or an installer.
87enum Staged<'a> {
88    None,
89    Folder(&'a Path),
90    Installer(&'a Path),
91}
92
93/// Record where the download of `version` stands; `false` when that release
94/// is no longer the one on offer (`check::set_download`).
95fn set(version: &str, state: &str, received: u64, total: u64, error: Option<String>, staged: Staged) -> bool {
96    let (folder, installer) = match staged {
97        Staged::None => (None, None),
98        Staged::Folder(f) => (Some(f), None),
99        Staged::Installer(i) => (None, Some(i)),
100    };
101    check::set_download(Some(DownloadStatus {
102        version: version.to_string(),
103        state: state.to_string(),
104        received,
105        total,
106        error,
107        folder: folder.map(|f| f.display().to_string()),
108        installer: installer.map(|i| i.display().to_string()),
109        waiting_for: 0,
110        waiting_on: Vec::new(),
111        stopping: Vec::new(),
112        not_confirmed_at: None,
113        not_confirmed: None,
114    }))
115}
116
117/// What a download stages, by install.
118enum Job {
119    /// A new portable folder beside `root`'s.
120    Portable(PathBuf),
121    /// A `setup.exe` installer (a macOS `.dmg`, a Linux `.deb` or `.rpm`) in `updates/<version>/`.
122    Installer,
123    /// The next AppImage beside this one.
124    AppImage(PathBuf),
125}
126
127/// Start downloading the release the update check found (the user's Download,
128/// through the host).
129/// Returns at once with the status; progress follows as events.
130pub fn start() -> Result<AppUpdateStatus, String> {
131    let status = check::current_status();
132    let (Some(version), Some(asset)) = (status.latest.clone(), status.asset.clone()) else {
133        return Err("no newer release is known yet".into());
134    };
135    // The one rule, again here: an offer can be stale (a release pulled, a channel changed, a
136    // staged status read again later), and a downgrade is a person's explicit rollback, which
137    // this updater does not do (task #49105).
138    if !check::is_newer(&version, &status.current) {
139        tracing::info!(
140            offered = %version,
141            running = %status.current,
142            "update: {version} is not newer than {}; not downloading it",
143            status.current
144        );
145        return Err(format!("{version} isn't newer than {}; there is nothing to download", status.current));
146    }
147    // Older than the release upgrades from: the same reason the check gives, naming the version to install first.
148    if let (true, Some(floor)) = (status.state == "available", status.install_first.as_deref()) {
149        return Err(check::install_first_message(&status.current, &version, floor));
150    }
151    if status.state != "available" || !status.can_download {
152        return Err("AgentMux can't download this release itself; use the release page".into());
153    }
154    // A portable's new folder goes beside the running one; a setup.exe
155    // install's installer is kept as is; an AppImage's next one goes beside it.
156    let job = match check::install_kind() {
157        InstallKind::WindowsPortable { root } | InstallKind::LinuxPortable { root } => Job::Portable(root),
158        // A macOS app's .dmg is staged like a setup.exe installer; the
159        // launcher mounts it and swaps the app after the quit.
160        // A `.deb`/`.rpm` is staged like a setup.exe installer too; the launcher asks
161        // for permission with polkit, and its helper installs it.
162        InstallKind::WindowsSetup | InstallKind::MacApp { blocked: None, .. } | InstallKind::LinuxPackage { .. } => Job::Installer,
163        InstallKind::LinuxAppImage => match std::env::current_exe()
164            .ok()
165            .and_then(|exe| agentmux_common::runtime_mode::running_appimage(&exe))
166        {
167            Some(appimage) => Job::AppImage(appimage),
168            None => return Err("can't tell which AppImage this AgentMux runs from; use the release page".into()),
169        },
170        _ => return Err("AgentMux can't download this release itself; use the release page".into()),
171    };
172    if let Some(d) = &status.download {
173        let staged = d.folder.as_deref().is_some_and(|f| is_staged_portable(Path::new(f), &version))
174            || d.installer.as_deref().is_some_and(|i| is_staged_installer(Path::new(i), &asset));
175        if d.version == version && matches!(d.state.as_str(), "ready" | "waiting" | "restarting") && staged {
176            return Ok(status);
177        }
178    }
179    if RUNNING.swap(true, Ordering::SeqCst) {
180        return Ok(status);
181    }
182    // A check that found a newer release since `status` was read wins: start
183    // nothing for this one (the user downloads the newer one instead).
184    if !set(&version, "downloading", 0, asset.size, None, Staged::None) {
185        RUNNING.store(false, Ordering::SeqCst);
186        return Err(format!("a newer release than {version} was found just now; download that one"));
187    }
188    let running = status.current.clone();
189    tokio::spawn(async move {
190        // Step 3 of signed checksums: nothing is downloaded unless the release's
191        // signed manifest verifies and agrees (an unsigned release from before
192        // signing is the one exception). `docs/specs/SPEC_SIGNED_UPDATE_CHECKSUMS_2026_10_25.md` §7.
193        if let Err(message) = crate::backend::update::signature::gate(&running, &version, &asset).await {
194            RUNNING.store(false, Ordering::SeqCst);
195            tracing::warn!(error = %message, "update: not downloading {version}");
196            set(&version, "failed", 0, asset.size, Some(message), Staged::None);
197            return;
198        }
199        let result = match &job {
200            Job::Portable(root) => run(&asset, &version, root).await.map(|f| (f, true)),
201            Job::Installer => run_installer(&asset, &version).await.map(|i| (i, false)),
202            Job::AppImage(appimage) => run_appimage(&asset, &version, appimage).await.map(|i| (i, false)),
203        };
204        RUNNING.store(false, Ordering::SeqCst);
205        match result {
206            Ok((path, folder)) => {
207                tracing::info!(path = %path.display(), "update: {version} is ready");
208                let staged = if folder { Staged::Folder(&path) } else { Staged::Installer(&path) };
209                set(&version, "ready", asset.size, asset.size, None, staged);
210            }
211            Err(e) => {
212                tracing::warn!(error = %e, "update: downloading {version} failed");
213                set(&version, "failed", 0, asset.size, Some(e), Staged::None);
214            }
215        }
216    });
217    Ok(check::current_status())
218}
219
220/// `updates/` in this version's data folder: `AGENTMUX_DATA_DIR`, the very
221/// folder the launcher checks a staged installer against
222/// (`crates/launcher/src/upgrade_restart.rs`), not a root of srv's own.
223pub(crate) fn updates_root() -> PathBuf {
224    agentmux_common::DataPaths::from_env()
225        .map(|p| p.data_dir)
226        .unwrap_or_else(crate::backend::base::get_mux_data_dir)
227        .join("updates")
228}
229
230async fn run(asset: &ReleaseAsset, version: &str, root: &Path) -> Result<PathBuf, String> {
231    let updates = updates_root();
232    remove_abandoned_downloads(&updates).await;
233    let dir = updates.join(version);
234    tokio::fs::create_dir_all(&dir).await.map_err(|e| format!("can't create {}: {e}", dir.display()))?;
235    let file = dir.join(format!("{}-{}", std::process::id(), asset.name));
236    if let Err(e) = download(asset, &file, version).await {
237        let _ = tokio::fs::remove_file(&file).await;
238        return Err(e);
239    }
240    set(version, "unpacking", asset.size, asset.size, None, Staged::None);
241    // The new folder keeps this AgentMux's data channel, a local build's too.
242    let channel = crate::backend::reactive::registry::local_channel_id();
243    // Next to the running folder, so it's where the user expects; under the
244    // channel's own `updates/` when that folder's parent can't be written.
245    let instance_dir = agentmux_common::DataPaths::from_env().map(|p| p.instance_dir);
246    let fallback = fallback_parent(instance_dir.as_deref(), version, &dir);
247    let beside = beside_parent(root, instance_dir.as_deref());
248    let mut last = String::new();
249    for parent in [beside, Some(fallback)].into_iter().flatten() {
250        match unpack_portable(&file, version, &parent, &channel).await {
251            Ok(folder) => {
252                let _ = tokio::fs::remove_file(&file).await;
253                return Ok(folder);
254            }
255            Err(e) => {
256                tracing::info!(error = %e, parent = %parent.display(), "update: couldn't unpack here");
257                last = e;
258            }
259        }
260    }
261    // Nothing more can be done with it; a later download fetches it again.
262    let _ = tokio::fs::remove_file(&file).await;
263    Err(last)
264}
265
266/// Where a portable is unpacked, or an AppImage put, when the running
267/// folder's parent can't take it: `<channel>/updates/<version>/`, outside every version's data folder.
268/// Under this version's `data/updates/` the new version would run from inside
269/// the old one's data, so removing an old version would remove the running
270/// one, and each later update would nest one level deeper. `dir` (this
271/// version's `updates/<version>/`) only when the channel isn't known. The
272/// launcher accepts a portable here (`upgrade_linux::check_target` on Linux;
273/// any folder on Windows). Like a portable beside the running one, it is the
274/// user's to remove: it may be the version they run.
275fn fallback_parent(instance_dir: Option<&Path>, version: &str, dir: &Path) -> PathBuf {
276    instance_dir.map(|d| d.join("updates").join(version)).unwrap_or_else(|| dir.to_path_buf())
277}
278
279/// The folder beside the running `install` (a portable's folder or an
280/// AppImage) to put the next version in, unless that folder is inside the
281/// channel's own tree: then the running version was itself put in a fallback
282/// (`updates/<v>/` of the channel or of an old version's data), and staging
283/// beside it would nest the new version under the old one's folder.
284fn beside_parent(install: &Path, instance_dir: Option<&Path>) -> Option<PathBuf> {
285    install.parent().filter(|p| !instance_dir.is_some_and(|d| p.starts_with(d))).map(Path::to_path_buf)
286}
287
288/// `rename`, tried again for a few seconds while Windows refuses it: a folder
289/// just unpacked is often still open to antivirus scanning its new files, and
290/// the move fails with "Access is denied" until the scan lets go.
291async fn rename_when_free(from: &Path, to: &Path) -> std::io::Result<()> {
292    let mut wait = Duration::from_millis(250);
293    let mut waited = Duration::ZERO;
294    loop {
295        match tokio::fs::rename(from, to).await {
296            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied && waited < RENAME_PATIENCE => {
297                tokio::time::sleep(wait).await;
298                waited += wait;
299                wait = (wait * 2).min(Duration::from_secs(2));
300            }
301            other => return other,
302        }
303    }
304}
305
306/// How long [`rename_when_free`] keeps trying.
307const RENAME_PATIENCE: Duration = Duration::from_secs(10);
308
309/// The installer's name in `updates/<version>/` once verified: the release's.
310pub(crate) fn installer_path(dir: &Path, asset: &ReleaseAsset) -> PathBuf {
311    dir.join(&asset.name)
312}
313
314/// `name`, or with `-n` before its extension for n > 1
315/// (`AgentMux_0.59.30_amd64-2.AppImage`): a copy beside one that isn't ours.
316fn release_file_variant(name: &str, n: u32) -> String {
317    match (n, name.rsplit_once('.')) {
318        (1, _) => name.to_string(),
319        (_, Some((stem, ext))) => format!("{stem}-{n}.{ext}"),
320        (_, None) => format!("{name}-{n}"),
321    }
322}
323
324/// Whether `path` is that release's installer (or AppImage), whole.
325pub(crate) fn is_staged_installer(path: &Path, asset: &ReleaseAsset) -> bool {
326    path.file_name().is_some_and(|n| (1..100).any(|i| n.to_string_lossy() == release_file_variant(&asset.name, i)))
327        && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() == asset.size)
328}
329
330/// Whether the file at `path` hashes to the release's digest. A file found
331/// already in place is only reused if it does: the name and size alone say
332/// nothing about who wrote it.
333fn has_release_digest(path: &Path, asset: &ReleaseAsset) -> bool {
334    let Ok(mut file) = std::fs::File::open(path) else { return false };
335    let mut hasher = Sha256::new();
336    std::io::copy(&mut file, &mut hasher).is_ok() && hex::encode(hasher.finalize()).eq_ignore_ascii_case(&asset.sha256)
337}
338
339/// [`is_staged_installer`], and whole by its digest too; off the async threads.
340async fn is_verified_installer(path: &Path, asset: &ReleaseAsset) -> bool {
341    if !is_staged_installer(path, asset) {
342        return false;
343    }
344    let (path, asset) = (path.to_path_buf(), asset.clone());
345    tokio::task::spawn_blocking(move || has_release_digest(&path, &asset)).await.unwrap_or(false)
346}
347
348/// Download a `setup.exe` install's installer into `updates/<version>/`,
349/// verified, under the release's own name: what the launcher runs.
350async fn run_installer(asset: &ReleaseAsset, version: &str) -> Result<PathBuf, String> {
351    let updates = updates_root();
352    remove_abandoned_downloads(&updates).await;
353    fetch_file(asset, version, &updates.join(version), None).await
354}
355
356/// Put the next AppImage beside this one, or in the channel's
357/// `updates/<version>/` ([`fallback_parent`]) when that folder can't be
358/// written; executable, with this AgentMux's channel recorded beside it, so
359/// the new version opens this one's data.
360async fn run_appimage(asset: &ReleaseAsset, version: &str, appimage: &Path) -> Result<PathBuf, String> {
361    let updates = updates_root();
362    remove_abandoned_downloads(&updates).await;
363    let paths = agentmux_common::DataPaths::from_env();
364    let channel = upgrade_channel(paths.as_ref().map(|p| p.channel.as_str()), std::env::var("AGENTMUX_CHANNEL").ok().as_deref());
365    let instance_dir = paths.map(|p| p.instance_dir);
366    let fallback = fallback_parent(instance_dir.as_deref(), version, &updates.join(version));
367    // A download cut short in the fallback leaves its `<pid>-` file there.
368    if let Some(root) = fallback.parent().filter(|r| *r != updates) {
369        remove_abandoned_downloads(root).await;
370    }
371    let beside = beside_parent(appimage, instance_dir.as_deref());
372    let mut last = String::new();
373    for dir in [beside, Some(fallback)].into_iter().flatten() {
374        match fetch_file(asset, version, &dir, Some(&channel)).await {
375            Ok(file) => return Ok(file),
376            Err(e) => {
377                tracing::info!(error = %e, dir = %dir.display(), "update: couldn't put the AppImage here");
378                last = e;
379            }
380        }
381    }
382    Err(last)
383}
384
385/// The data channel an in-app upgrade carries to the new AppImage: the one this instance resolved for its own
386/// data (`resolved`, from the paths the launcher gave it), else `AGENTMUX_CHANNEL`, and `stable` only when
387/// neither says. The upgrade keeps the channel of the build that downloaded it (#47873).
388fn upgrade_channel(resolved: Option<&str>, env: Option<&str>) -> String {
389    resolved.or(env).filter(|c| !c.is_empty()).unwrap_or("stable").to_string()
390}
391
392/// Keep the channel of the AppImage at `file` where a move can't lose it (`agentmux_common::appimage_record`),
393/// as well as beside it. Best effort: the record beside the file is what the next start reads first.
394fn keep_channel_with_account(file: &Path, channel: &str) {
395    if let Some(record) = agentmux_common::appimage_record::record_path() {
396        let _ = agentmux_common::appimage_record::remember(&record, file, channel);
397    }
398}
399
400/// The data channel recorded beside the AppImage at `file`, if any.
401fn appimage_channel(file: &Path) -> Option<String> {
402    let record = agentmux_common::runtime_mode::appimage_channel_file(file);
403    std::fs::read_to_string(record).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
404}
405
406/// An AppImage at `file`: executable, its channel recorded beside it.
407fn finish_appimage(file: &Path, channel: &str) -> Result<(), String> {
408    #[cfg(unix)]
409    {
410        use std::os::unix::fs::PermissionsExt;
411        std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o755))
412            .map_err(|e| format!("can't make {} executable: {e}", file.display()))?;
413    }
414    let record = agentmux_common::runtime_mode::appimage_channel_file(file);
415    std::fs::write(&record, format!("{channel}\n")).map_err(|e| format!("can't write {}: {e}", record.display()))
416}
417
418/// Download the release file into `dir` under the release's own name,
419/// verified. With `appimage_channel` it is an AppImage: made executable with
420/// that channel recorded beside it, and never one recorded for another channel
421/// (a copy `…-2.AppImage` is made beside it instead).
422async fn fetch_file(asset: &ReleaseAsset, version: &str, dir: &Path, appimage_channel_of: Option<&str>) -> Result<PathBuf, String> {
423    tokio::fs::create_dir_all(dir).await.map_err(|e| format!("can't create {}: {e}", dir.display()))?;
424    let ours = |p: &Path| appimage_channel_of.is_none_or(|ch| appimage_channel(p).is_none_or(|c| c == ch));
425    let target = (1..100)
426        .map(|n| dir.join(release_file_variant(&asset.name, n)))
427        .find(|p| !p.exists() || ours(p))
428        .unwrap_or_else(|| installer_path(dir, asset));
429    let finish = |file: PathBuf| match appimage_channel_of {
430        Some(channel) => finish_appimage(&file, channel).map(|()| {
431            keep_channel_with_account(&file, channel);
432            file
433        }),
434        None => Ok(file),
435    };
436    // Downloaded before, or by another AgentMux meanwhile.
437    if is_verified_installer(&target, asset).await {
438        return finish(target);
439    }
440    let file = dir.join(format!("{}-{}", std::process::id(), asset.name));
441    if let Err(e) = download(asset, &file, version).await {
442        let _ = tokio::fs::remove_file(&file).await;
443        return Err(e);
444    }
445    match tokio::fs::rename(&file, &target).await {
446        Ok(()) => finish(target),
447        Err(_) if is_verified_installer(&target, asset).await => {
448            let _ = tokio::fs::remove_file(&file).await;
449            finish(target)
450        }
451        Err(e) => {
452            let _ = tokio::fs::remove_file(&file).await;
453            Err(format!("can't put the release file in place: {e}"))
454        }
455    }
456}
457
458async fn download(asset: &ReleaseAsset, dest: &Path, version: &str) -> Result<(), String> {
459    if !asset.url.starts_with(RELEASE_DOWNLOAD_PREFIX) {
460        return Err("the release file isn't on AgentMux's GitHub releases".into());
461    }
462    let client = crate::http_client::builder()
463        .user_agent(format!("AgentMux/{}", env!("CARGO_PKG_VERSION")))
464        .connect_timeout(CONNECT_TIMEOUT)
465        .build()
466        .map_err(|e| e.to_string())?;
467    let mut resp = tokio::time::timeout(STALL_TIMEOUT, client.get(&asset.url).send())
468        .await
469        .map_err(|_| "GitHub didn't answer".to_string())?
470        .and_then(|r| r.error_for_status())
471        .map_err(|e| format!("download failed: {e}"))?;
472    let mut part = dest.as_os_str().to_owned();
473    part.push(".part");
474    let part = PathBuf::from(part);
475    let result = async {
476        let mut out = tokio::fs::File::create(&part).await.map_err(|e| e.to_string())?;
477        let mut received = Received::new(asset.size);
478        let mut shown = u64::MAX;
479        loop {
480            let chunk = tokio::time::timeout(STALL_TIMEOUT, resp.chunk())
481                .await
482                .map_err(|_| "the download stalled".to_string())?
483                .map_err(|e| format!("download failed: {e}"))?;
484            let Some(chunk) = chunk else { break };
485            received.push(&chunk)?;
486            out.write_all(&chunk).await.map_err(|e| e.to_string())?;
487            let percent = received.bytes * 100 / asset.size.max(1);
488            if percent != shown {
489                shown = percent;
490                set(version, "downloading", received.bytes, asset.size, None, Staged::None);
491            }
492        }
493        out.flush().await.map_err(|e| e.to_string())?;
494        drop(out);
495        received.finish(&asset.sha256)?;
496        tokio::fs::rename(&part, dest).await.map_err(|e| e.to_string())
497    }
498    .await;
499    if result.is_err() {
500        let _ = tokio::fs::remove_file(&part).await;
501    }
502    result
503}
504
505/// Whether `dir` is an unpacked AgentMux `version` portable: on Windows the
506/// release's folder (`agentmux.exe`, `runtime/` with the marker and that
507/// version's host); on Linux the tarball's `AgentMux/` (`agentmux.sh`, that
508/// version's srv in `usr/bin/`, and `usr/share/agentmux/VERSION` saying so).
509pub(crate) fn is_staged_portable(dir: &Path, version: &str) -> bool {
510    if cfg!(windows) {
511        dir.join("agentmux.exe").is_file()
512            && dir.join("runtime").join("agentmux-portable.marker").is_file()
513            && dir.join("runtime").join(format!("agentmux-{version}.exe")).is_file()
514    } else {
515        dir.join("agentmux.sh").is_file()
516            && dir.join("usr/bin").join(format!("agentmux-srv-{version}-linux.x64")).is_file()
517            && std::fs::read_to_string(dir.join("usr/share/agentmux/VERSION")).is_ok_and(|v| v.trim() == version)
518    }
519}
520
521/// A staged portable of `version` at `dir`, laid out as this platform's
522/// release is (tests).
523#[cfg(test)]
524pub(crate) fn fake_portable(dir: &Path, version: &str) {
525    if cfg!(windows) {
526        std::fs::create_dir_all(dir.join("runtime")).unwrap();
527        std::fs::write(dir.join("agentmux.exe"), b"").unwrap();
528        std::fs::write(dir.join("runtime/agentmux-portable.marker"), b"").unwrap();
529        std::fs::write(dir.join(format!("runtime/agentmux-{version}.exe")), b"").unwrap();
530    } else {
531        std::fs::create_dir_all(dir.join("usr/bin")).unwrap();
532        std::fs::create_dir_all(dir.join("usr/share/agentmux")).unwrap();
533        std::fs::write(dir.join("agentmux.sh"), b"").unwrap();
534        std::fs::write(dir.join(format!("usr/bin/agentmux-srv-{version}-linux.x64")), b"").unwrap();
535        std::fs::write(dir.join("usr/share/agentmux/VERSION"), format!("{version}
536")).unwrap();
537    }
538}
539
540/// The folder a release's portable is unpacked into, beside the running one.
541fn portable_folder_name(version: &str) -> String {
542    if cfg!(windows) {
543        format!("agentmux-{version}-x64-portable")
544    } else {
545        format!("AgentMux-{version}")
546    }
547}
548
549/// Where in what `tar` unpacked into `partial` the portable is: the Windows
550/// archive holds the folder's contents, the Linux tarball an `AgentMux/` folder.
551fn unpacked_root(partial: &Path) -> PathBuf {
552    if cfg!(windows) {
553        partial.to_path_buf()
554    } else {
555        partial.join("AgentMux")
556    }
557}
558
559/// `parent/name`, or `name-2`, `name-3`… when that is taken by something else.
560fn free_folder(parent: &Path, name: &str) -> PathBuf {
561    let mut n = 1;
562    loop {
563        let candidate = if n == 1 { parent.join(name) } else { parent.join(format!("{name}-{n}")) };
564        if !candidate.exists() {
565            return candidate;
566        }
567        n += 1;
568    }
569}
570
571/// Unpacking folders an earlier, interrupted run left behind (an hour old:
572/// never one another AgentMux is still filling).
573async fn remove_stale_partials(parent: &Path, name: &str) {
574    let prefix = format!(".{name}.");
575    let Ok(mut entries) = tokio::fs::read_dir(parent).await else { return };
576    while let Ok(Some(e)) = entries.next_entry().await {
577        let file_name = e.file_name().to_string_lossy().into_owned();
578        if file_name.starts_with(&prefix) && file_name.ends_with(".partial") && abandoned(&e).await {
579            let _ = tokio::fs::remove_dir_all(e.path()).await;
580        }
581    }
582}
583
584async fn abandoned(e: &tokio::fs::DirEntry) -> bool {
585    e.metadata()
586        .await
587        .ok()
588        .and_then(|m| m.modified().ok())
589        .and_then(|t| t.elapsed().ok())
590        .is_some_and(|age| age > ABANDONED_AFTER)
591}
592
593/// Download files (each run's `<pid>-<file>` and its `.part`) left in
594/// `updates/<version>/` by runs that were cut short. Only those: a verified
595/// installer waiting there for its restart is kept, and so are folders (a
596/// release staged there when its portable's folder couldn't be written;
597/// unpacking folders are `remove_stale_partials`' job).
598async fn remove_abandoned_downloads(updates: &Path) {
599    let pid_prefixed = |name: &str| name.split_once('-').is_some_and(|(pid, _)| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()));
600    let Ok(mut versions) = tokio::fs::read_dir(updates).await else { return };
601    while let Ok(Some(v)) = versions.next_entry().await {
602        let Ok(mut files) = tokio::fs::read_dir(v.path()).await else { continue };
603        while let Ok(Some(f)) = files.next_entry().await {
604            let named = pid_prefixed(&f.file_name().to_string_lossy());
605            if named && f.file_type().await.is_ok_and(|t| t.is_file()) && abandoned(&f).await {
606                let _ = tokio::fs::remove_file(f.path()).await;
607            }
608        }
609    }
610}
611
612/// The system `tar`, for the Linux `.tar.xz` (Windows doesn't use it: `unpack_into`).
613fn tar_exe() -> PathBuf {
614    PathBuf::from("tar")
615}
616
617/// Whether the staged portable `folder` may be used by the AgentMux on
618/// `channel`: it records no channel yet, or that one. A folder another
619/// AgentMux staged for a different channel isn't reused; a copy is made beside it.
620fn for_channel(folder: &Path, channel: &str) -> bool {
621    agentmux_common::runtime_mode::recorded_channel_in(folder).is_none_or(|c| c == channel)
622}
623
624/// Record `channel` in the portable `folder`: the data the new version opens.
625/// In `runtime/` on Windows, at the top on Linux, where its binaries look
626/// (`runtime_mode::recorded_channel_in`).
627fn record_channel(folder: &Path, channel: &str) -> Result<(), String> {
628    let at = if cfg!(windows) { folder.join("runtime") } else { folder.to_path_buf() };
629    let file = at.join(agentmux_common::runtime_mode::RECORDED_CHANNEL_FILE);
630    std::fs::write(&file, format!("{channel}\n")).map_err(|e| format!("can't write {}: {e}", file.display()))
631}
632
633/// Unpack the downloaded release `file` into the staging folder `partial`. On
634/// Windows the `.7z` is decoded in srv (`update::unpack`): Windows 10's own
635/// `tar.exe` has no LZMA. Elsewhere the `.tar.xz` goes through the system `tar`.
636async fn unpack_into(file: &Path, partial: &Path) -> Result<(), String> {
637    if cfg!(windows) {
638        let stop = std::sync::Arc::new(AtomicBool::new(false));
639        let (file, partial, stopper) = (file.to_path_buf(), partial.to_path_buf(), stop.clone());
640        let mut run = tokio::task::spawn_blocking(move || crate::backend::update::unpack::unpack_7z(&file, &partial, &stopper));
641        return match tokio::time::timeout(UNPACK_TIMEOUT, &mut run).await {
642            // The blocking thread can't be cancelled: tell it to stop, and wait
643            // until it has, so nothing writes into the staging folder after it is
644            // removed or reused by a retry (QTest on #5124).
645            Err(_) => {
646                stop.store(true, Ordering::Relaxed);
647                let _ = run.await;
648                Err("unpacking took more than 10 minutes and was stopped".to_string())
649            }
650            Ok(Err(e)) => Err(format!("unpacking stopped unexpectedly: {e}")),
651            Ok(Ok(unpacked)) => unpacked,
652        };
653    }
654    use agentmux_common::win32::NoWindow;
655    let mut tar = tokio::process::Command::new(tar_exe());
656    // tar needs nothing of this instance: none of its AGENTMUX_* variables.
657    crate::backend::pane_env::sanitize_external_command(&mut tar);
658    let run = tar
659        .arg("-xf")
660        .arg(file)
661        .arg("-C")
662        .arg(partial)
663        .stdin(std::process::Stdio::null())
664        .kill_on_drop(true)
665        .no_window()
666        .output();
667    match tokio::time::timeout(UNPACK_TIMEOUT, run).await {
668        Err(_) => Err("unpacking took more than 10 minutes and was stopped".to_string()),
669        Ok(Err(e)) => Err(format!("couldn't run tar to unpack it: {e}")),
670        Ok(Ok(o)) if !o.status.success() => {
671            let why = String::from_utf8_lossy(&o.stderr).lines().next().unwrap_or("").to_string();
672            Err(format!("tar couldn't unpack it ({why}); is `xz` installed?"))
673        }
674        Ok(Ok(_)) => Ok(()),
675    }
676}
677
678/// Unpack the release into `parent`, recording `channel` in it.
679async fn unpack_portable(file: &Path, version: &str, parent: &Path, channel: &str) -> Result<PathBuf, String> {
680    let name = portable_folder_name(version);
681    let fits = |dir: &Path| is_staged_portable(dir, version) && for_channel(dir, channel);
682    // Staged by an earlier download that was then interrupted.
683    if fits(&parent.join(&name)) {
684        record_channel(&parent.join(&name), channel)?;
685        return Ok(parent.join(&name));
686    }
687    remove_stale_partials(parent, &name).await;
688    let partial = parent.join(format!(".{name}.{}.partial", std::process::id()));
689    let _ = tokio::fs::remove_dir_all(&partial).await;
690    tokio::fs::create_dir_all(&partial).await.map_err(|e| format!("can't write to {}: {e}", parent.display()))?;
691    let checked = match unpack_into(file, &partial).await {
692        Err(e) => Err(e),
693        Ok(()) if !is_staged_portable(&unpacked_root(&partial), version) => {
694            Err(format!("what was unpacked isn't an AgentMux {version} portable"))
695        }
696        Ok(()) => record_channel(&unpacked_root(&partial), channel),
697    };
698    let canonical = parent.join(&name);
699    let result = match checked {
700        Err(e) => Err(e),
701        // Another AgentMux on this channel staged the same release while this
702        // one unpacked: use it rather than make a copy beside it.
703        Ok(()) if fits(&canonical) => record_channel(&canonical, channel).map(|()| canonical),
704        Ok(()) => {
705            let target = free_folder(parent, &name);
706            match rename_when_free(&unpacked_root(&partial), &target).await {
707                Ok(()) => Ok(target),
708                // The other one's move won the race.
709                Err(_) if fits(&canonical) => record_channel(&canonical, channel).map(|()| canonical),
710                Err(e) => Err(format!("can't move the unpacked folder into place: {e}")),
711            }
712        }
713    };
714    // Whatever wasn't moved into place.
715    let _ = tokio::fs::remove_dir_all(&partial).await;
716    result
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[test]
724    fn the_fallback_unpacks_outside_every_versions_data_folder() {
725        let channel = Path::new("/home/u/.agentmux/channels/local-main");
726        let own = channel.join("versions").join("0.59.30").join("data").join("updates").join("0.59.34");
727        let parent = fallback_parent(Some(channel), "0.59.34", &own);
728        assert_eq!(parent, channel.join("updates").join("0.59.34"));
729        assert!(!parent.starts_with(channel.join("versions")));
730        // Without the channel, this version's own updates/ as before.
731        assert_eq!(fallback_parent(None, "0.59.34", &own), own);
732    }
733
734    #[test]
735    fn a_version_running_from_a_fallback_is_not_staged_beside() {
736        let channel = Path::new("/home/u/.agentmux/channels/local-main");
737        let desktop = Path::new("/home/u/Desktop/AgentMux-0.59.34");
738        assert_eq!(beside_parent(desktop, Some(channel)).as_deref(), Some(Path::new("/home/u/Desktop")));
739        // Put in the channel's fallback, or in an old version's data/updates/.
740        let in_channel = channel.join("updates/0.59.34/AgentMux-0.59.34");
741        let in_old_data = channel.join("versions/0.59.30/data/updates/0.59.34/AgentMux-0.59.34");
742        assert_eq!(beside_parent(&in_channel, Some(channel)), None);
743        assert_eq!(beside_parent(&in_old_data, Some(channel)), None);
744        assert!(beside_parent(&in_channel, None).is_some());
745    }
746
747    #[tokio::test]
748    async fn a_rename_that_works_is_done_at_once_and_a_missing_source_fails_at_once() {
749        let dir = tempfile::tempdir().unwrap();
750        let (from, to) = (dir.path().join("a"), dir.path().join("b"));
751        std::fs::create_dir(&from).unwrap();
752        rename_when_free(&from, &to).await.unwrap();
753        assert!(to.is_dir() && !from.exists());
754        // Not "Access is denied": no waiting.
755        let started = std::time::Instant::now();
756        assert!(rename_when_free(&dir.path().join("missing"), &dir.path().join("c")).await.is_err());
757        assert!(started.elapsed() < Duration::from_secs(1));
758    }
759
760    /// A file held open without delete sharing blocks moving its folder, as
761    /// a scanner's handle does; the move goes through once it is closed.
762    #[cfg(windows)]
763    #[tokio::test]
764    async fn a_rename_refused_while_a_file_inside_is_open_goes_through_once_it_closes() {
765        use std::os::windows::fs::OpenOptionsExt;
766        let dir = tempfile::tempdir().unwrap();
767        let (from, to) = (dir.path().join("unpacked"), dir.path().join("agentmux-portable"));
768        std::fs::create_dir(&from).unwrap();
769        std::fs::write(from.join("agentmux.exe"), b"x").unwrap();
770        // FILE_SHARE_READ only: no FILE_SHARE_DELETE.
771        let held = std::fs::OpenOptions::new().read(true).share_mode(0x1).open(from.join("agentmux.exe")).unwrap();
772        assert_eq!(std::fs::rename(&from, &to).unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
773        let release = tokio::spawn(async move {
774            tokio::time::sleep(Duration::from_millis(600)).await;
775            drop(held);
776        });
777        rename_when_free(&from, &to).await.unwrap();
778        release.await.unwrap();
779        assert!(to.join("agentmux.exe").is_file());
780    }
781
782    #[test]
783    fn an_installer_found_in_place_is_reused_only_if_it_hashes_right() {
784        let dir = tempfile::tempdir().unwrap();
785        let data = b"agentmux installer bytes";
786        let asset = ReleaseAsset {
787            name: "AgentMux-0.59.27-x64-setup.exe".into(),
788            size: data.len() as u64,
789            url: String::new(),
790            sha256: hex::encode(Sha256::digest(data)),
791        };
792        let path = dir.path().join(&asset.name);
793        std::fs::write(&path, data).unwrap();
794        assert!(is_staged_installer(&path, &asset) && has_release_digest(&path, &asset));
795        // The same name and size, other bytes.
796        std::fs::write(&path, b"agentmux installer BYTES").unwrap();
797        assert!(is_staged_installer(&path, &asset) && !has_release_digest(&path, &asset));
798        assert!(!has_release_digest(&dir.path().join("missing.exe"), &asset));
799    }
800
801    #[test]
802    fn only_the_exact_file_github_lists_is_accepted() {
803        let data = b"agentmux release bytes";
804        let sha = hex::encode(Sha256::digest(data));
805        let mut r = Received::new(data.len() as u64);
806        r.push(&data[..5]).unwrap();
807        r.push(&data[5..]).unwrap();
808        r.finish(&sha.to_uppercase()).unwrap();
809
810        let mut short = Received::new(data.len() as u64 + 1);
811        short.push(data).unwrap();
812        assert!(short.finish(&sha).unwrap_err().contains("stopped at"));
813
814        let mut long = Received::new(4);
815        assert!(long.push(data).unwrap_err().contains("larger"));
816
817        let mut other = Received::new(data.len() as u64);
818        other.push(b"agentmux release bytez").unwrap();
819        assert!(other.finish(&sha).unwrap_err().contains("checksum"));
820    }
821
822
823    #[tokio::test]
824    async fn downloads_left_by_an_interrupted_run_are_removed_and_folders_kept() {
825        let updates = tempfile::tempdir().unwrap();
826        let dir = updates.path().join("0.59.27");
827        std::fs::create_dir_all(dir.join("agentmux-0.59.27-x64-portable")).unwrap();
828        // A verified installer waits here for its restart, however long.
829        let installer = dir.join("AgentMux-0.59.27-x64-setup.exe");
830        std::fs::write(&installer, b"x").unwrap();
831        let age = |p: &Path, secs: u64| {
832            let t = std::time::SystemTime::now() - Duration::from_secs(secs);
833            std::fs::File::options().write(true).open(p).unwrap().set_modified(t).unwrap();
834        };
835        let old = dir.join("4242-agentmux-0.59.27-x64-portable.7z.part");
836        let live = dir.join("777-agentmux-0.59.27-x64-portable.7z.part");
837        std::fs::write(&old, b"x").unwrap();
838        std::fs::write(&live, b"x").unwrap();
839        age(&old, 2 * 60 * 60);
840        age(&live, 5);
841        age(&installer, 2 * 60 * 60);
842        remove_abandoned_downloads(updates.path()).await;
843        assert!(!old.exists());
844        assert!(live.exists());
845        assert!(installer.exists());
846        assert!(dir.join("agentmux-0.59.27-x64-portable").is_dir());
847    }
848
849    #[test]
850    fn a_staged_folder_must_be_that_version_and_never_overwrites_another() {
851        let dir = tempfile::tempdir().unwrap();
852        let folder = dir.path().join("agentmux-0.59.27-x64-portable");
853        fake_portable(&folder, "0.59.27");
854        assert!(is_staged_portable(&folder, "0.59.27"));
855        assert!(!is_staged_portable(&folder, "0.59.28"));
856        assert_eq!(free_folder(dir.path(), "agentmux-0.59.27-x64-portable"), dir.path().join("agentmux-0.59.27-x64-portable-2"));
857        assert_eq!(free_folder(dir.path(), "other"), dir.path().join("other"));
858    }
859
860    /// The real thing, against a published release (125 MB; run by hand):
861    /// `cargo test -p agentmux-srv-core --lib -- --ignored real_portable_release`.
862    #[cfg(windows)]
863    #[tokio::test]
864    #[ignore]
865    async fn real_portable_release_downloads_verifies_and_unpacks() {
866        let name = "agentmux-0.59.27-x64-portable.7z";
867        let asset = ReleaseAsset {
868            name: name.into(),
869            size: 124_705_866,
870            url: format!("{RELEASE_DOWNLOAD_PREFIX}v0.59.27/{name}"),
871            sha256: "db750e1689752519ad21b730436f783493c63b59ad734677a433e413c9b47f2a".into(),
872        };
873        let dir = tempfile::tempdir().unwrap();
874        let file = dir.path().join(name);
875        download(&asset, &file, "0.59.27").await.unwrap();
876        let folder = unpack_portable(&file, "0.59.27", dir.path(), "stable").await.unwrap();
877        assert!(is_staged_portable(&folder, "0.59.27"));
878        // One wrong byte of checksum and the download is refused and removed.
879        let wrong = ReleaseAsset { sha256: "0".repeat(64), ..asset };
880        let err = download(&wrong, &dir.path().join("again.7z"), "0.59.27").await.unwrap_err();
881        assert!(err.contains("checksum"), "{err}");
882        assert!(!dir.path().join("again.7z.part").exists());
883    }
884
885    /// The release's `.7z` (a fixture with its LZMA2 + BCJ2 coders, see
886    /// `update::unpack`) is decoded and the folder lands in place. A zip used to
887    /// stand in for it here, which Windows' tar.exe reads, and hid that it
888    /// can't read the real thing.
889    #[cfg(windows)]
890    #[tokio::test]
891    async fn unpacks_the_release_7z_and_checks_what_came_out() {
892        let dir = tempfile::tempdir().unwrap();
893        let archive = std::path::PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/src/backend/testdata/update-portable-0.59.27.7z"));
894        let parent = dir.path().join("apps");
895        std::fs::create_dir_all(&parent).unwrap();
896        let local = "local-main-b28b7a-f62415cd";
897        let folder = unpack_portable(&archive, "0.59.27", &parent, local).await.unwrap();
898        assert_eq!(folder, parent.join("agentmux-0.59.27-x64-portable"));
899        assert!(is_staged_portable(&folder, "0.59.27"));
900        // It opens this AgentMux's data, a local build's channel included.
901        assert_eq!(agentmux_common::runtime_mode::recorded_channel_in(&folder).as_deref(), Some(local));
902        let leftovers = || std::fs::read_dir(&parent).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().starts_with('.')).count();
903        assert_eq!(leftovers(), 0);
904        // Asked again, the staged folder is reused.
905        assert_eq!(unpack_portable(&archive, "0.59.27", &parent, local).await.unwrap(), folder);
906        // Not by an AgentMux on another channel: it gets a copy of its own.
907        let other = unpack_portable(&archive, "0.59.27", &parent, "stable").await.unwrap();
908        assert_eq!(other, parent.join("agentmux-0.59.27-x64-portable-2"));
909        assert_eq!(agentmux_common::runtime_mode::recorded_channel_in(&other).as_deref(), Some("stable"));
910        assert_eq!(agentmux_common::runtime_mode::recorded_channel_in(&folder).as_deref(), Some(local));
911        // An archive of another version is refused and leaves nothing.
912        let err = unpack_portable(&archive, "0.59.28", &parent, local).await.unwrap_err();
913        assert!(err.contains("isn't an AgentMux 0.59.28 portable"), "{err}");
914        assert_eq!(leftovers(), 0);
915        assert!(!parent.join("agentmux-0.59.28-x64-portable").exists());
916    }
917
918    #[test]
919    fn a_copy_beside_a_release_file_keeps_its_extension() {
920        assert_eq!(release_file_variant("AgentMux_0.59.30_amd64.AppImage", 1), "AgentMux_0.59.30_amd64.AppImage");
921        assert_eq!(release_file_variant("AgentMux_0.59.30_amd64.AppImage", 2), "AgentMux_0.59.30_amd64-2.AppImage");
922        let dir = tempfile::tempdir().unwrap();
923        let asset = ReleaseAsset { name: "AgentMux_0.59.30_amd64.AppImage".into(), size: 3, url: String::new(), sha256: String::new() };
924        let copy = dir.path().join("AgentMux_0.59.30_amd64-2.AppImage");
925        std::fs::write(&copy, b"abc").unwrap();
926        assert!(is_staged_installer(&copy, &asset));
927        let other = dir.path().join("AgentMux_0.59.31_amd64.AppImage");
928        std::fs::write(&other, b"abc").unwrap();
929        assert!(!is_staged_installer(&other, &asset));
930    }
931
932    #[test]
933    fn an_appimage_is_made_executable_with_its_channel_beside_it() {
934        let dir = tempfile::tempdir().unwrap();
935        let file = dir.path().join("AgentMux_0.59.30_amd64.AppImage");
936        std::fs::write(&file, b"x").unwrap();
937        assert_eq!(appimage_channel(&file), None);
938        finish_appimage(&file, "local-main-b28b7a-f62415cd").unwrap();
939        assert_eq!(appimage_channel(&file).as_deref(), Some("local-main-b28b7a-f62415cd"));
940        #[cfg(unix)]
941        {
942            use std::os::unix::fs::PermissionsExt;
943            assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o755);
944        }
945    }
946
947    #[test]
948    fn an_in_app_upgrade_keeps_the_channel_of_the_build_that_downloaded_it() {
949        // The channel the instance resolved for its own data wins, whatever the environment says.
950        assert_eq!(upgrade_channel(Some("local-main-b28b7a-f62415cd"), None), "local-main-b28b7a-f62415cd");
951        assert_eq!(upgrade_channel(Some("local-main-b28b7a-f62415cd"), Some("stable")), "local-main-b28b7a-f62415cd");
952        assert_eq!(upgrade_channel(None, Some("local-main-b28b7a-f62415cd")), "local-main-b28b7a-f62415cd");
953        // `stable` only when nothing says otherwise (a stable instance, or no channel known at all).
954        assert_eq!(upgrade_channel(Some("stable"), None), "stable");
955        assert_eq!(upgrade_channel(None, None), "stable");
956        assert_eq!(upgrade_channel(Some(""), Some("")), "stable");
957    }
958
959    #[test]
960    fn an_upgraded_appimage_is_remembered_so_that_moving_it_does_not_lose_its_channel() {
961        let dir = tempfile::tempdir().unwrap();
962        let record = dir.path().join("shared").join(agentmux_common::appimage_record::RECORD_FILE);
963        let file = dir.path().join("AgentMux_0.60.30_amd64.AppImage");
964        std::fs::write(&file, b"x").unwrap();
965        finish_appimage(&file, "local-main-b28b7a-f62415cd").unwrap();
966        agentmux_common::appimage_record::remember(&record, &file, "local-main-b28b7a-f62415cd").unwrap();
967        // The file moves and is renamed; the record beside it stays behind.
968        let moved = dir.path().join("Applications").join("AgentMux_0.60.30_amd64_9f8e7d.AppImage");
969        std::fs::create_dir_all(moved.parent().unwrap()).unwrap();
970        std::fs::rename(&file, &moved).unwrap();
971        assert_eq!(appimage_channel(&moved), None);
972        let found = agentmux_common::appimage_record::lookup(&record, &moved).unwrap();
973        assert_eq!(found.channel, "local-main-b28b7a-f62415cd");
974    }
975
976    /// The system `tar` unpacks a release-shaped tarball (`AgentMux/` with
977    /// `agentmux.sh` above `usr/bin/`) into `AgentMux-<v>` beside the running
978    /// folder, recording the channel at its top.
979    #[cfg(target_os = "linux")]
980    #[tokio::test]
981    async fn unpacks_a_linux_tarball_beside_the_running_folder() {
982        let dir = tempfile::tempdir().unwrap();
983        let src = dir.path().join("src");
984        let top = src.join("AgentMux");
985        std::fs::create_dir_all(top.join("usr/bin")).unwrap();
986        std::fs::create_dir_all(top.join("usr/share/agentmux")).unwrap();
987        std::fs::write(top.join("agentmux.sh"), b"#!/bin/sh
988").unwrap();
989        std::fs::write(top.join("usr/bin/agentmux-srv-0.59.30-linux.x64"), b"").unwrap();
990        std::fs::write(top.join("usr/share/agentmux/VERSION"), b"0.59.30
991").unwrap();
992        let archive = dir.path().join("AgentMux_0.59.30_amd64-portable.tar.xz");
993        let made = std::process::Command::new(tar_exe()).arg("-cJf").arg(&archive).arg("-C").arg(&src).arg("AgentMux").status().unwrap();
994        assert!(made.success());
995        let parent = dir.path().join("apps");
996        std::fs::create_dir_all(&parent).unwrap();
997        let local = "local-main-b28b7a-f62415cd";
998        let folder = unpack_portable(&archive, "0.59.30", &parent, local).await.unwrap();
999        assert_eq!(folder, parent.join("AgentMux-0.59.30"));
1000        assert!(is_staged_portable(&folder, "0.59.30"));
1001        assert_eq!(agentmux_common::runtime_mode::recorded_channel_in(&folder.join("usr/bin")).as_deref(), Some(local));
1002        let err = unpack_portable(&archive, "0.59.31", &parent, local).await.unwrap_err();
1003        assert!(err.contains("isn't an AgentMux 0.59.31 portable"), "{err}");
1004    }
1005
1006}