1use std::collections::{HashMap, HashSet};
22use std::path::{Path, PathBuf};
23use std::time::{Duration, Instant};
24
25use agentmux_common::ipc::Command;
26use serde_json::{json, Value};
27
28use crate::backend::obj::{Block, Client, Tab, Window, Workspace};
29use crate::backend::rpc_types::{OtherBuildLayout, RestoreOtherBuildLayoutResult};
30use crate::backend::storage::store::Store;
31use crate::server::AppState;
32
33use super::reducer_helpers::{dispatch_to_reducer, publish_events};
34use super::session_restore::{replay_tabs, replay_tabs_of, restore_active_tab, restore_workspace, SNAPSHOT_META_KEY};
35use super::session_windows::{patch_of, queue_restored_windows, set_client_meta, windows_of};
36
37const SEEDED_META_KEY: &str = "session:seeded_default";
39
40const MAX_SCANNED: usize = 16;
43
44pub(crate) const SCAN_BUDGET: Duration = Duration::from_millis(1500);
46
47const BUSY_TIMEOUT: Duration = Duration::from_millis(200);
50
51const DEFAULT_VIEWS: [&str; 3] = ["agent", "swarm", "sysinfo"];
54
55pub(crate) struct ScanRoots {
58 pub channels_root: PathBuf,
59 pub own_db_dir: Option<PathBuf>,
60}
61
62impl ScanRoots {
63 pub(crate) fn live() -> Option<Self> {
66 let paths = agentmux_common::DataPaths::from_env()?;
67 Some(Self { channels_root: paths.home_dir.join("channels"), own_db_dir: Some(paths.data_dir.join("db")) })
68 }
69}
70
71struct DbFile {
72 channel: String,
73 version: String,
74 path: PathBuf,
75 written_ms: i64,
76}
77
78fn srv_running(db: &Path) -> bool {
81 let Some(data) = db.parent().and_then(Path::parent) else { return false };
82 let lock = data.join(crate::backend::base::SRV_DATA_LOCK_FILE);
83 let written = std::fs::metadata(&lock).and_then(|m| m.modified()).ok();
84 crate::backend::slug_migration::stamp::lock_pid(&lock)
85 .filter(|pid| *pid != 0)
86 .is_some_and(|pid| crate::backend::process_identity::srv_alive(pid, written))
87}
88
89fn modified_ms(path: &Path) -> Option<i64> {
90 let at = std::fs::metadata(path).ok()?.modified().ok()?;
91 Some(at.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis() as i64)
92}
93
94fn same_dir(a: &Path, b: &Path) -> bool {
95 match (a.canonicalize(), b.canonicalize()) {
96 (Ok(a), Ok(b)) => a == b,
97 _ => a == b,
98 }
99}
100
101fn db_files(roots: &ScanRoots) -> Vec<DbFile> {
104 let mut out = Vec::new();
105 let Ok(channels) = std::fs::read_dir(&roots.channels_root) else {
106 return out;
107 };
108 for channel in channels.flatten() {
109 let Ok(versions) = std::fs::read_dir(channel.path().join("versions")) else {
110 continue;
111 };
112 for version in versions.flatten() {
113 let db_dir = version.path().join("data").join("db");
114 let path = db_dir.join("objects.db");
115 let Some(db_ms) = modified_ms(&path) else {
116 continue;
117 };
118 if roots.own_db_dir.as_deref().is_some_and(|own| same_dir(own, &db_dir)) {
119 continue;
120 }
121 let wal = wal_of(&path);
124 let written_ms = if wal_len(&wal) > 0 { modified_ms(&wal).map_or(db_ms, |w| w.max(db_ms)) } else { db_ms };
125 out.push(DbFile {
126 channel: channel.file_name().to_string_lossy().into_owned(),
127 version: version.file_name().to_string_lossy().into_owned(),
128 path,
129 written_ms,
130 });
131 }
132 }
133 out
134}
135
136fn own_channel(roots: &ScanRoots) -> Option<String> {
140 let own = roots.own_db_dir.as_deref()?;
141 let versions = own.parent()?.parent()?.parent()?;
143 if versions.file_name()? != "versions" {
144 return None;
145 }
146 let channel = versions.parent()?;
147 if !same_dir(channel.parent()?, &roots.channels_root) {
148 return None;
149 }
150 Some(channel.file_name()?.to_string_lossy().into_owned())
151}
152
153pub(crate) fn newest_other_version_db(roots: &ScanRoots) -> Option<PathBuf> {
157 let channel = own_channel(roots)?;
158 db_files(roots)
159 .into_iter()
160 .filter(|f| f.channel == channel)
161 .max_by_key(|f| f.written_ms)
162 .map(|f| {
163 tracing::debug!(version = %f.version, "session_other_builds: newest other version of this channel");
164 f.path
165 })
166}
167
168fn wal_of(db: &Path) -> PathBuf {
169 let mut name = db.as_os_str().to_owned();
170 name.push("-wal");
171 PathBuf::from(name)
172}
173
174fn wal_len(wal: &Path) -> u64 {
175 std::fs::metadata(wal).map(|m| m.len()).unwrap_or(0)
176}
177
178fn immutable_uri(path: &Path) -> String {
180 let p = path.to_string_lossy().replace('\\', "/").replace('%', "%25").replace('?', "%3f").replace('#', "%23");
181 let sep = if p.starts_with('/') { "//" } else { "///" };
182 format!("file:{sep}{p}?immutable=1")
183}
184
185pub(crate) fn open_other_db(path: &Path) -> Result<rusqlite::Connection, String> {
190 use rusqlite::OpenFlags;
191 let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
192 let conn = if wal_len(&wal_of(path)) == 0 {
193 rusqlite::Connection::open_with_flags(immutable_uri(path), flags | OpenFlags::SQLITE_OPEN_URI)
194 } else {
195 rusqlite::Connection::open_with_flags(path, flags)
196 }
197 .map_err(|e| format!("open {}: {e}", path.display()))?;
198 conn.busy_timeout(BUSY_TIMEOUT).map_err(|e| e.to_string())?;
199 Ok(conn)
200}
201
202pub(crate) fn read_record(path: &Path) -> Result<Option<Value>, String> {
204 use rusqlite::OptionalExtension;
205 let conn = open_other_db(path)?;
206 let data: Option<Vec<u8>> = conn
207 .query_row("SELECT data FROM db_client LIMIT 1", [], |row| row.get(0))
208 .optional()
209 .map_err(|e| format!("read {}: {e}", path.display()))?;
210 let Some(data) = data else {
211 return Ok(None);
212 };
213 let client: Value = serde_json::from_slice(&data).map_err(|e| e.to_string())?;
214 Ok(client.get("meta").and_then(|m| m.get(SNAPSHOT_META_KEY)).filter(|v| !v.is_null()).cloned())
215}
216
217fn meta_str<'a>(meta: &'a Value, key: &str) -> &'a str {
218 meta.get(key).and_then(|v| v.as_str()).unwrap_or_default()
219}
220
221pub(crate) fn summarize(record: &Value, channel: &str, version: &str, written_ms: i64) -> Option<OtherBuildLayout> {
225 let windows = windows_of(record);
226 let (mut tabs, mut panes) = (0u32, 0u32);
227 let mut agents = Vec::new();
228 let mut seen = HashSet::new();
229 let mut only_default_views = true;
230 for window in &windows {
231 for tab in window.get("tabs").and_then(|v| v.as_array()).into_iter().flatten() {
232 let blocks = tab.get("blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
233 if blocks.is_empty() {
234 continue;
235 }
236 tabs += 1;
237 for block in &blocks {
238 panes += 1;
239 let meta = block.get("meta").unwrap_or(&Value::Null);
240 let view = meta_str(meta, "view");
241 only_default_views &= DEFAULT_VIEWS.contains(&view);
242 let agent_id = meta_str(meta, "agentId");
243 if view == "agent" && !agent_id.is_empty() && seen.insert(agent_id.to_string()) {
244 let name = meta_str(meta, "agentName");
245 agents.push(if name.is_empty() { agent_id } else { name }.to_string());
246 }
247 }
248 }
249 }
250 if tabs == 0 || (windows.len() == 1 && tabs == 1 && agents.is_empty() && only_default_views) {
251 return None;
252 }
253 let saved_at = record.get("saved_at_ms").and_then(|v| v.as_i64());
254 Some(OtherBuildLayout {
255 channel: channel.to_string(),
256 version: version.to_string(),
257 saved_at_ms: saved_at.unwrap_or(written_ms),
258 saved_at_exact: saved_at.is_some(),
259 windows: windows.len() as u32,
260 tabs,
261 panes,
262 agents,
263 })
264}
265
266pub(crate) fn discover(roots: &ScanRoots, budget: Duration) -> Vec<OtherBuildLayout> {
271 let started = Instant::now();
272 let mut files = db_files(roots);
273 files.sort_by_key(|f| std::cmp::Reverse(f.written_ms));
274 files.truncate(MAX_SCANNED);
275 let mut found = Vec::new();
276 for file in files {
277 if started.elapsed() > budget {
278 tracing::debug!("session_other_builds: scan budget spent; skipping older builds");
279 break;
280 }
281 if srv_running(&file.path) {
282 tracing::debug!(channel = %file.channel, version = %file.version, "session_other_builds: not offered, it is running now");
283 continue;
284 }
285 match read_record(&file.path) {
286 Ok(Some(record)) => found.extend(summarize(&record, &file.channel, &file.version, file.written_ms)),
287 Ok(None) => {}
288 Err(e) => tracing::debug!(channel = %file.channel, version = %file.version, error = %e, "session_other_builds: skipped a database"),
289 }
290 }
291 found.sort_by_key(|l| std::cmp::Reverse(l.saved_at_ms));
292 found
293}
294
295pub(crate) fn remember_seeded_default(store: &Store, ws_id: &str, tab_id: &str, block_ids: &[String]) {
297 set_client_meta(
298 store,
299 SEEDED_META_KEY,
300 Some(json!({ "workspace_id": ws_id, "tab_id": tab_id, "block_ids": block_ids })),
301 );
302}
303
304pub(crate) fn remember_first_launch_default(store: &Store) {
307 let seeded = (|| {
308 let client = store.get_all::<Client>().ok()?.into_iter().next()?;
309 let window = store.get::<Window>(client.windowids.first()?).ok()??;
310 let workspace = store.get::<Workspace>(&window.workspaceid).ok()??;
311 let tab_id = workspace.pinnedtabids.iter().chain(workspace.tabids.iter()).next()?.clone();
312 let tab = store.get::<Tab>(&tab_id).ok()??;
313 Some((workspace.oid, tab_id, tab.blockids))
314 })();
315 if let Some((ws_id, tab_id, block_ids)) = seeded {
316 remember_seeded_default(store, &ws_id, &tab_id, &block_ids);
317 }
318}
319
320pub(crate) fn untouched_default_tab(store: &Store, ws_id: &str) -> Option<String> {
323 let client = store.get_all::<Client>().ok()?.into_iter().next()?;
324 let seeded = client.meta.get(SEEDED_META_KEY)?;
325 if meta_str(seeded, "workspace_id") != ws_id {
326 return None;
327 }
328 let tab_id = meta_str(seeded, "tab_id").to_string();
329 let workspace = store.get::<Workspace>(ws_id).ok()??;
330 let tabs: Vec<&String> = workspace.pinnedtabids.iter().chain(workspace.tabids.iter()).collect();
331 if tabs != [&tab_id] {
332 return None;
333 }
334 let tab = store.get::<Tab>(&tab_id).ok()??;
335 let seeded_blocks: HashSet<&str> =
336 seeded.get("block_ids")?.as_array()?.iter().filter_map(|v| v.as_str()).collect();
337 let blocks: HashSet<&str> = tab.blockids.iter().map(String::as_str).collect();
338 if blocks != seeded_blocks {
339 return None;
340 }
341 let agent_chosen = tab.blockids.iter().any(|id| {
342 store
343 .get::<Block>(id)
344 .ok()
345 .flatten()
346 .is_some_and(|b| b.meta.get("agentId").and_then(|v| v.as_str()).is_some_and(|s| !s.is_empty()))
347 });
348 (!agent_chosen).then_some(tab_id)
349}
350
351fn is_plain_segment(s: &str) -> bool {
353 !s.is_empty() && s != "." && s != ".." && !s.contains(['/', '\\', ':', '\0'])
354}
355
356fn locate(roots: &ScanRoots, channel: &str, version: &str) -> Result<PathBuf, String> {
358 if !is_plain_segment(channel) || !is_plain_segment(version) {
359 return Err("not a build of this AgentMux".to_string());
360 }
361 let db_dir = roots.channels_root.join(channel).join("versions").join(version).join("data").join("db");
362 if roots.own_db_dir.as_deref().is_some_and(|own| same_dir(own, &db_dir)) {
363 return Err("that is this build's own layout".to_string());
364 }
365 let path = db_dir.join("objects.db");
366 if !path.is_file() {
367 return Err(format!("no build {version} ({channel}) on this computer"));
368 }
369 if srv_running(&path) {
370 return Err(format!("{version} ({channel}) is running now: quit it first, or its agents would run twice"));
371 }
372 Ok(path)
373}
374
375async fn apply_publish(state: &AppState, events: &[agentmux_common::ipc::Event]) {
376 for ev in events {
377 if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
378 tracing::warn!(error = %e, "session_other_builds: SQLite write failed");
379 }
380 }
381 publish_events(state, events);
382}
383
384pub(crate) async fn restore(
390 state: &AppState,
391 roots: &ScanRoots,
392 window_id: &str,
393 channel: &str,
394 version: &str,
395) -> Result<RestoreOtherBuildLayoutResult, String> {
396 let path = locate(roots, channel, version)?;
397 let record = tokio::task::spawn_blocking(move || read_record(&path))
398 .await
399 .map_err(|e| format!("task: {e}"))??
400 .ok_or_else(|| format!("{version} has no saved layout"))?;
401 let store = &state.mstore;
402 let ws_id = store
403 .get::<Window>(window_id)
404 .map_err(|e| e.to_string())?
405 .ok_or_else(|| format!("no such window: {window_id}"))?
406 .workspaceid;
407 let seeded_tab = untouched_default_tab(store, &ws_id);
408 let windows = windows_of(&record);
409 let first = windows.first().ok_or("the saved layout has no windows")?;
410
411 let saved_tabs = replay_tabs_of(first);
412 let (events, replayed) = replay_tabs(state, &ws_id, &saved_tabs, "restore_other_build").await;
413 publish_events(state, &events);
414 let by_index: HashMap<usize, String> =
415 replayed.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|r| (i, r.tab_id.clone()))).collect();
416 let tab_ids: Vec<String> = replayed.iter().flatten().map(|r| r.tab_id.clone()).collect();
417 if tab_ids.is_empty() {
418 return Err("none of the saved tabs could be created".to_string());
419 }
420 let mut active = restore_active_tab(state, &ws_id, first, &by_index).await;
421 if active.is_empty() {
422 active = dispatch_to_reducer(
424 state,
425 Command::SetActiveTab { workspace_id: ws_id.clone(), tab_id: tab_ids[0].clone() },
426 )
427 .await;
428 for ev in &active {
429 let _ = crate::persist_subscriber::apply_event_to_mstore(ev, store);
430 }
431 }
432 publish_events(state, &active);
433
434 let replaced_default = match &seeded_tab {
435 Some(tab_id) => match crate::sagas::delete_tab::run(state, ws_id.clone(), tab_id.clone()).await {
436 Ok(_) => true,
437 Err(e) => {
438 tracing::warn!(error = %e, "session_other_builds: couldn't remove the default tab");
439 false
440 }
441 },
442 None => false,
443 };
444 if replaced_default {
445 for (saved, came_back) in saved_tabs.iter().zip(&replayed) {
449 let Some(came_back) = came_back else { continue };
450 let current = store.get::<Tab>(&came_back.tab_id).ok().flatten().map(|t| t.name);
451 if current.as_deref().is_some_and(|c| c != saved.name) && !saved.name.is_empty() {
452 let evs = dispatch_to_reducer(
453 state,
454 Command::RenameTab { tab_id: came_back.tab_id.clone(), name: saved.name.clone() },
455 )
456 .await;
457 apply_publish(state, &evs).await;
458 }
459 }
460 let patch = first.get("window").map(patch_of).unwrap_or_default();
462 if !patch.is_empty() {
463 let evs = dispatch_to_reducer(
464 state,
465 Command::UpdateWindowMeta { window_id: window_id.to_string(), meta_patch: Value::Object(patch) },
466 )
467 .await;
468 apply_publish(state, &evs).await;
469 }
470 }
471 set_client_meta(store, SEEDED_META_KEY, None);
473
474 let mut waiting = Vec::new();
475 let mut metas = serde_json::Map::new();
476 for (i, window) in windows.iter().enumerate().skip(1) {
477 match restore_workspace(state, window).await {
478 Ok(Some((new_ws, evs))) => {
479 publish_events(state, &evs);
480 let mut entry = window.get("window").cloned().unwrap_or_else(|| json!({}));
481 entry["workspaceid"] = json!(new_ws);
482 waiting.push(entry);
483 let patch = window.get("window").map(patch_of).unwrap_or_default();
484 if !patch.is_empty() {
485 metas.insert(new_ws, Value::Object(patch));
486 }
487 }
488 Ok(None) => tracing::warn!(window = i, "session_other_builds: a window's tabs didn't come back"),
489 Err(e) => tracing::warn!(window = i, error = %e, "session_other_builds: a window didn't come back"),
490 }
491 }
492 let other_windows = waiting.len() as u32;
493 queue_restored_windows(store, waiting, metas);
494 tracing::info!(
495 channel,
496 version,
497 tabs = tab_ids.len(),
498 other_windows,
499 replaced_default,
500 "session_other_builds: restored a layout another build saved"
501 );
502 Ok(RestoreOtherBuildLayoutResult { workspace_id: ws_id, tab_ids, replaced_default, other_windows })
503}
504
505#[cfg(test)]
506#[path = "session_other_builds_tests.rs"]
507mod tests;