Skip to main content

agentmux_common/
appimage_record.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which data channel an AppImage runs in, kept so that moving or renaming the file doesn't lose it (#47873).
5//!
6//! An in-app upgrade records the channel beside the AppImage, as `<file>.agentmux-channel`
7//! ([`runtime_mode::appimage_channel_file`]). A move or a rename leaves that file behind: AppImageLauncher's
8//! "Integrate" moves the AppImage into `~/Applications` under a new name, and the moved file then came up in
9//! `stable`, with another channel's windows and tabs.
10//!
11//! So the channel is also kept in a small record in the account-wide `shared` folder, keyed by which *file*
12//! the AppImage is, not where it is: the same size and modification time, and, while the old path is still
13//! there, the same file system object (a rename keeps both). A copy that still sits at its old path is another
14//! file, never a move, so a duplicate of a release never takes a channel from its twin. A move that changes
15//! the modification time (a copy across file systems) is not recognised, and the file starts in the channel
16//! built into it, as before.
17//!
18//! What a start does with it ([`reconcile`]):
19//! - the file's own record beside it wins, and is remembered here;
20//! - with none beside it, a record of this same file gives the channel, and the record beside the file is
21//!   written again, so the next start doesn't need this one;
22//! - with neither, nothing changes.
23//!
24//! A record that isn't a plain channel name is ignored, and so is one that can't be read.
25
26use crate::runtime_mode::{appimage_channel_file, read_channel_file};
27use serde::{Deserialize, Serialize};
28use std::fs::{File, OpenOptions, TryLockError};
29use std::path::{Path, PathBuf};
30use std::time::{Duration, Instant};
31
32/// The record, in the account-wide `shared` folder.
33pub const RECORD_FILE: &str = "appimage-channels.json";
34
35/// How many AppImages are remembered, the most recently started last.
36const MAX_RECORDS: usize = 16;
37
38/// What identifies an AppImage file apart from its path.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct FileId {
41    pub size: u64,
42    /// Modification time, nanoseconds since the epoch.
43    pub mtime_ns: u128,
44    /// The file system object (0 where there is none): kept by a rename, new for a copy.
45    pub dev: u64,
46    pub ino: u64,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50struct Record {
51    path: String,
52    channel: String,
53    id: FileId,
54}
55
56/// The identity of the file at `path`.
57pub fn file_id(path: &Path) -> Option<FileId> {
58    let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
59    let mtime_ns = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos();
60    #[cfg(unix)]
61    let (dev, ino) = {
62        use std::os::unix::fs::MetadataExt;
63        (meta.dev(), meta.ino())
64    };
65    #[cfg(not(unix))]
66    let (dev, ino) = (0, 0);
67    Some(FileId { size: meta.len(), mtime_ns, dev, ino })
68}
69
70/// A channel name as AppRun and the data paths accept it.
71fn plain_channel(s: &str) -> bool {
72    !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
73}
74
75/// Whether `record` is of the file at `path`, whose identity is `now`: the same size and modification time, and
76/// either the same path, the same file system object, or an old path that has nothing at it any more (the file
77/// was moved). An old path that still holds a file means this one is another file, a copy.
78fn is_this_file(record: &Record, path: &str, now: &FileId) -> bool {
79    let old = &record.id;
80    if old.size != now.size || old.mtime_ns != now.mtime_ns {
81        return false;
82    }
83    let has_object = old.dev != 0 || old.ino != 0;
84    record.path == path || (has_object && old.dev == now.dev && old.ino == now.ino) || !Path::new(&record.path).is_file()
85}
86
87/// The record's layout version. A build reads and rewrites only a record of this version or none: a newer
88/// build's file is left alone (it is neither read nor overwritten), as every file in `shared` is.
89const VERSION: u32 = 1;
90
91#[derive(Serialize, Deserialize)]
92struct Stored {
93    version: u32,
94    records: Vec<Record>,
95}
96
97/// What the record file holds, and whether this build may rewrite it (it may not when a newer build wrote it).
98fn load(record: &Path) -> (Vec<Record>, bool) {
99    let Ok(text) = std::fs::read_to_string(record) else { return (Vec::new(), true) };
100    // The version first, on its own: a newer build may have changed what follows it.
101    let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return (Vec::new(), true) };
102    match value.get("version").and_then(serde_json::Value::as_u64) {
103        Some(v) if v > u64::from(VERSION) => (Vec::new(), false),
104        Some(_) => match serde_json::from_value::<Stored>(value) {
105            Ok(stored) => (stored.records, true),
106            Err(_) => (Vec::new(), true),
107        },
108        // Not ours, or damaged: nothing to keep, and a new one replaces it.
109        None => (Vec::new(), true),
110    }
111}
112
113fn save(record: &Path, records: Vec<Record>) -> std::io::Result<()> {
114    if let Some(dir) = record.parent() {
115        std::fs::create_dir_all(dir)?;
116    }
117    let tmp = record.with_extension(format!("tmp{}", std::process::id()));
118    std::fs::write(&tmp, serde_json::to_vec_pretty(&Stored { version: VERSION, records }).map_err(std::io::Error::other)?)?;
119    std::fs::rename(&tmp, record).inspect_err(|_| {
120        let _ = std::fs::remove_file(&tmp);
121    })
122}
123
124/// A record of the file at `appimage`: its channel, and the path it was last started from.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct Found {
127    pub channel: String,
128    pub was_at: String,
129}
130
131/// The record of this very file, wherever it was before.
132pub fn lookup(record: &Path, appimage: &Path) -> Option<Found> {
133    let now = file_id(appimage)?;
134    let path = appimage.to_string_lossy();
135    load(record)
136        .0
137        .into_iter()
138        .rev()
139        .filter(|r| plain_channel(&r.channel))
140        .find(|r| is_this_file(r, &path, &now))
141        .map(|r| Found { channel: r.channel, was_at: r.path })
142}
143
144/// How long a writer waits for another's turn. A turn is one small file's read and atomic replace.
145const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
146const LOCK_RETRY: Duration = Duration::from_millis(10);
147
148/// The lock file beside the record, held until the returned file is dropped. An OS file lock
149/// (`LockFileEx` / `flock`, through `std`) binds one open handle, so it keeps writers apart in this process as
150/// well as in other AgentMux instances, and the OS drops it if its holder dies. The file is never removed:
151/// deleting it while another writer waits would give two writers two different locks.
152fn lock_record(record: &Path, timeout: Duration) -> std::io::Result<File> {
153    if let Some(dir) = record.parent() {
154        std::fs::create_dir_all(dir)?;
155    }
156    let mut name = record.file_name().map(std::ffi::OsString::from).unwrap_or_else(|| RECORD_FILE.into());
157    name.push(".lock");
158    #[allow(clippy::suspicious_open_options)]
159    let file = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(record.with_file_name(name))?;
160    let started = Instant::now();
161    loop {
162        match file.try_lock() {
163            Ok(()) => return Ok(file),
164            Err(TryLockError::WouldBlock) if started.elapsed() < timeout => std::thread::sleep(LOCK_RETRY),
165            Err(TryLockError::WouldBlock) => {
166                return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "the AppImage channel record is locked by another start"))
167            }
168            Err(TryLockError::Error(e)) => return Err(e),
169        }
170    }
171}
172
173/// Remember that the file at `appimage` runs in `channel`.
174///
175/// The whole read, change and write is one turn under [`lock_record`]: without it two starts at once each read
176/// the same records and the later write drops the earlier one's entry. When the lock can't be had (another
177/// start holds it for longer than [`LOCK_TIMEOUT`]) nothing is written, and the entry comes back from the
178/// record beside the file at its next start.
179pub fn remember(record: &Path, appimage: &Path, channel: &str) -> std::io::Result<()> {
180    remember_within(record, appimage, channel, LOCK_TIMEOUT)
181}
182
183fn remember_within(record: &Path, appimage: &Path, channel: &str, timeout: Duration) -> std::io::Result<()> {
184    if !plain_channel(channel) {
185        return Ok(());
186    }
187    let Some(id) = file_id(appimage) else { return Ok(()) };
188    let path = appimage.to_string_lossy().into_owned();
189    let _turn = lock_record(record, timeout)?;
190    let (mut records, writable) = load(record);
191    if !writable {
192        return Ok(());
193    }
194    // This path, and this file wherever it was, are replaced by this one.
195    records.retain(|r| r.path != path && !is_this_file(r, &path, &id));
196    records.push(Record { path, channel: channel.to_string(), id });
197    if records.len() > MAX_RECORDS {
198        let extra = records.len() - MAX_RECORDS;
199        records.drain(..extra);
200    }
201    save(record, records)
202}
203
204/// What a start found out about the AppImage it runs from.
205#[derive(Debug, Clone, Default, PartialEq, Eq)]
206pub struct Reconciled {
207    /// The channel the file is recorded for, if any.
208    pub channel: Option<String>,
209    /// Where the file was last started from, when that isn't where it is now: it was moved or renamed.
210    pub moved_from: Option<String>,
211}
212
213/// Bring the records about `appimage` in line with where it is now (see the module doc). Best effort: a
214/// folder that can't be written leaves the channel as it was.
215pub fn reconcile(record: &Path, appimage: &Path) -> Reconciled {
216    let beside = read_channel_file(&appimage_channel_file(appimage)).filter(|c| plain_channel(c));
217    let found = lookup(record, appimage);
218    let Some(channel) = beside.clone().or_else(|| found.as_ref().map(|f| f.channel.clone())) else {
219        return Reconciled::default();
220    };
221    if beside.is_none() {
222        let _ = std::fs::write(appimage_channel_file(appimage), format!("{channel}\n"));
223    }
224    let moved_from = found.map(|f| f.was_at).filter(|was| *was != appimage.to_string_lossy());
225    let _ = remember(record, appimage, &channel);
226    Reconciled { channel: Some(channel), moved_from }
227}
228
229/// The record's place: the account-wide `shared` folder.
230pub fn record_path() -> Option<PathBuf> {
231    crate::data_paths::agentmux_root().ok().map(|root| root.join("shared").join(RECORD_FILE))
232}
233
234/// The channel recorded for the AppImage at `appimage` when its own record was left behind by a move.
235pub fn moved_channel(appimage: &Path) -> Option<String> {
236    lookup(&record_path()?, appimage).map(|f| f.channel)
237}
238
239#[cfg(test)]
240mod tests;