Skip to main content

agentmux_srv/server/service/
user_workspace.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The open workspace: a named set of windows, saved as it changes
5//! (docs/specs/SPEC_WORKSPACES_2026_10_23.md §2, §4, §8). Not the srv
6//! `Workspace` object, which is one window's contents.
7//!
8//! - **Which one is open:** `Client.meta["workspace:current"]` (its id) and
9//!   `Client.meta["workspace:name"]` (its name, for the status bar panel). A
10//!   start with no workspace makes **Default Workspace**; a new version's first
11//!   start copies the previous version's instead ([`prepare_at_startup`]).
12//! - **Saving:** every write to a window, a window's contents, a tab, a layout
13//!   or a block counts as a change (`LayoutWrites`, bumped by the store). The
14//!   saver ([`spawn_saver`]) writes the whole session
15//!   (`session_windows::snapshot_session`) as the workspace's `record` 1 s after
16//!   the last change, and at least every 15 s while changes keep coming. A quit,
17//!   an OS shutdown and the last window's close write it at once
18//!   ([`write_record_now`]), and so does a window losing focus
19//!   (`workspace.Flush`). A write that would store what is already there is
20//!   skipped; one with no window open is never made. Each window in the
21//!   record has a `state`: `open`, or `closed` for the windows the user closed
22//!   (`session_closed`), which a cold start keeps closed.
23//! - **Loading:** a cold start restores the newer of the session record and the
24//!   workspace's record, then falls back to the last record that loaded
25//!   cleanly (`previous`) and the copy made before an upgrade (`pre_upgrade`)
26//!   ([`restore_at_launch`]). Only a clean load replaces `previous`.
27//!
28//! The session record (`session:last_topology`) is still written as before:
29//! the version after this one reads it if it has no workspace yet.
30
31use std::path::Path;
32use std::sync::Arc;
33use std::time::Duration;
34
35use agentmux_common::ipc::Event;
36use agentmux_common::time::now_ms;
37use serde_json::{json, Value};
38
39use crate::backend::obj::{mux_obj_to_value, Client, MuxObjUpdate};
40use crate::backend::service::{self, WebCallType, WebReturnType};
41use crate::backend::storage::store::Store;
42use crate::backend::storage::user_workspaces::{self, UserWorkspaceRow};
43use crate::server::AppState;
44
45use super::session_other_builds::{newest_other_version_db, open_other_db, ScanRoots};
46use super::session_windows::{is_recent_quit_record, set_client_meta, windows_of};
47
48/// The open workspace's id.
49pub(crate) const CURRENT_META_KEY: &str = "workspace:current";
50/// The open workspace's name.
51pub(crate) const NAME_META_KEY: &str = "workspace:name";
52/// Set when a launch had to load an older copy of the workspace: `previous`
53/// or `pre_upgrade`. The window says so once and clears it.
54pub(crate) const RESTORED_FROM_META_KEY: &str = "workspace:restored_from";
55
56/// The workspace everyone starts in.
57pub(crate) const DEFAULT_NAME: &str = "Default Workspace";
58/// The longest name kept, in characters (a window's name has the same cap).
59const NAME_MAX_CHARS: usize = 64;
60
61/// How often the saver looks for changes.
62const TICK: Duration = Duration::from_millis(250);
63/// A change is saved this long after the last one...
64pub(crate) const DEBOUNCE_MS: i64 = 1_000;
65/// ...and no later than this after the first one not yet saved.
66pub(crate) const CEILING_MS: i64 = 15_000;
67/// A change to blocks' settings alone (an agent pane writes them as it works)
68/// waits this long instead; a close, a quit or focus loss saves it at once.
69pub(crate) const SETTINGS_ONLY_MS: i64 = 30_000;
70
71/// One save at a time: the saver, a flush and a boundary write never
72/// interleave their read-compare-write.
73static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
74
75
76
77fn client(store: &Store) -> Option<Client> {
78    store.get_all::<Client>().ok()?.into_iter().next()
79}
80
81/// The open workspace's id, if one is set.
82pub(crate) fn current_id(store: &Store) -> Option<String> {
83    client(store)?
84        .meta
85        .get(CURRENT_META_KEY)
86        .and_then(|v| v.as_str())
87        .filter(|s| !s.is_empty())
88        .map(str::to_string)
89}
90
91/// `name` trimmed and capped, or `None` when nothing is left.
92pub(crate) fn clean_name(name: &str) -> Option<String> {
93    let trimmed = name.trim();
94    (!trimmed.is_empty()).then(|| trimmed.chars().take(NAME_MAX_CHARS).collect())
95}
96
97fn new_row(name: &str, now: i64) -> UserWorkspaceRow {
98    UserWorkspaceRow {
99        id: uuid::Uuid::new_v4().to_string(),
100        name: name.to_string(),
101        created_at: now,
102        updated_at: now,
103        ..Default::default()
104    }
105}
106
107// ---- Startup ----
108
109/// Before the store's first window is made (`wcore::ensure_initial_data`):
110/// make sure there is a workspace. With none, copy the previous version's
111/// ([`copy_from_previous_version`]), else make Default Workspace. Returns the
112/// workspace this start opens when it decided one, for [`adopt_current`].
113///
114/// When the copied workspace has windows and the store has no client yet (a
115/// new version's first start), only the client is made: with no window, the
116/// first window's cold start restores them (`window_create`) instead of
117/// seeding the default layout, so a build that is new here opens where the
118/// last one left off, and offers no other build's layout (nothing was seeded).
119pub(crate) fn prepare_at_startup(store: &Store, roots: Option<&ScanRoots>) -> Option<String> {
120    match store.user_workspace_list() {
121        Ok(rows) if !rows.is_empty() => return None,
122        Ok(_) => {}
123        Err(e) => {
124            tracing::warn!(error = %e, "user_workspace: couldn't read the workspaces");
125            return None;
126        }
127    }
128    if let Some(copied) = roots.and_then(|r| copy_from_previous_version(store, r)) {
129        let has_windows = store
130            .user_workspace_get(&copied)
131            .ok()
132            .flatten()
133            .and_then(|w| w.record)
134            .and_then(|r| serde_json::from_str::<Value>(&r).ok())
135            .is_some_and(|r| record_has_tabs(&r));
136        if has_windows && client(store).is_none() {
137            if let Err(e) = create_client_only(store) {
138                tracing::warn!(error = %e, "user_workspace: couldn't make the client; the default window opens");
139            }
140        }
141        return Some(copied);
142    }
143    let row = new_row(DEFAULT_NAME, now_ms());
144    match store.user_workspace_insert(&row) {
145        Ok(()) => {
146            tracing::info!(workspace = %row.id, "user_workspace: made Default Workspace");
147            Some(row.id)
148        }
149        Err(e) => {
150            tracing::warn!(error = %e, "user_workspace: couldn't make Default Workspace");
151            None
152        }
153    }
154}
155
156/// Whether any window in `record` has a tab to restore.
157fn record_has_tabs(record: &Value) -> bool {
158    windows_of(record)
159        .iter()
160        .any(|w| w.get("tabs").and_then(|t| t.as_array()).is_some_and(|t| !t.is_empty()))
161}
162
163/// The client row alone, as `ensure_initial_data` makes it (insert, then the
164/// temp id), with no window: `ensure_initial_data` then sees a store that is
165/// set up and seeds nothing.
166fn create_client_only(store: &Store) -> Result<(), crate::backend::storage::StoreError> {
167    let mut client = Client { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
168    store.insert(&mut client)?;
169    client.tempoid = uuid::Uuid::new_v4().to_string();
170    store.update(&mut client)?;
171    Ok(())
172}
173
174/// After `ensure_initial_data`: open `decided` (from [`prepare_at_startup`]),
175/// or keep the one the client names, or the most recently opened. Writes its
176/// id and name onto the client, and when it was opened onto its row.
177pub(crate) fn adopt_current(store: &Store, decided: Option<String>) {
178    let rows = match store.user_workspace_list() {
179        Ok(rows) => rows,
180        Err(e) => {
181            tracing::warn!(error = %e, "user_workspace: couldn't read the workspaces");
182            return;
183        }
184    };
185    let named = current_id(store).filter(|id| rows.iter().any(|w| &w.id == id));
186    let Some(row) = decided
187        .or(named)
188        .and_then(|id| rows.iter().find(|w| w.id == id))
189        .or_else(|| rows.first())
190        .cloned()
191    else {
192        return;
193    };
194    let result = store.with_tx(|tx| {
195        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(()) };
196        let was = client.meta.get(CURRENT_META_KEY).and_then(|v| v.as_str()).map(str::to_string);
197        let same = was.as_deref() == Some(row.id.as_str())
198            && client.meta.get(NAME_META_KEY).and_then(|v| v.as_str()) == Some(row.name.as_str());
199        // The closed windows belong to the workspace that was open.
200        if was.is_some_and(|w| w != row.id) {
201            client.meta.remove(super::session_closed::CLOSED_META_KEY);
202        }
203        if !same {
204            client.meta.insert(CURRENT_META_KEY.to_string(), json!(row.id));
205            client.meta.insert(NAME_META_KEY.to_string(), json!(row.name));
206            tx.update(&mut client)?;
207        }
208        Ok(())
209    });
210    if let Err(e) = result {
211        tracing::warn!(error = %e, "user_workspace: couldn't record the open workspace");
212    }
213    let _ = store.user_workspace_mark_opened(&row.id, now_ms());
214    tracing::info!(workspace = %row.id, name = %row.name, "user_workspace: opened");
215}
216
217/// The workspaces in the database at `path`, read-only, with the id its client
218/// names as open. `Ok(None)` for a database without workspaces (an older
219/// version's has no table).
220pub(crate) fn read_other_workspaces(path: &Path) -> Result<Option<(Vec<UserWorkspaceRow>, Option<String>)>, String> {
221    use rusqlite::OptionalExtension;
222    let conn = open_other_db(path)?;
223    let has_table: bool = conn
224        .query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'db_workspaces'", [], |_| Ok(true))
225        .optional()
226        .map_err(|e| e.to_string())?
227        .unwrap_or(false);
228    if !has_table {
229        return Ok(None);
230    }
231    let rows = user_workspaces::list_in(&conn).map_err(|e| e.to_string())?;
232    if rows.is_empty() {
233        return Ok(None);
234    }
235    let client: Option<Vec<u8>> = conn
236        .query_row("SELECT data FROM db_client LIMIT 1", [], |row| row.get(0))
237        .optional()
238        .map_err(|e| e.to_string())?;
239    let current = client
240        .and_then(|d| serde_json::from_slice::<Value>(&d).ok())
241        .and_then(|c| c.get("meta")?.get(CURRENT_META_KEY)?.as_str().map(str::to_string));
242    Ok(Some((rows, current)))
243}
244
245/// A new version's first start (spec §4.2 "Upgrades"): copy every workspace
246/// the channel's most recently written other version has, once, reading its
247/// database only. Ids and names are kept; each record is also kept as the
248/// row's `pre_upgrade`. Returns the one to open: the one that version had
249/// open. `None` when there is nothing to copy.
250pub(crate) fn copy_from_previous_version(store: &Store, roots: &ScanRoots) -> Option<String> {
251    let path = newest_other_version_db(roots)?;
252    let (rows, current) = match read_other_workspaces(&path) {
253        Ok(Some(found)) => found,
254        Ok(None) => return None,
255        Err(e) => {
256            tracing::warn!(error = %e, "user_workspace: couldn't read the previous version's workspaces");
257            return None;
258        }
259    };
260    let copied: Vec<UserWorkspaceRow> =
261        rows.into_iter().map(|w| UserWorkspaceRow { pre_upgrade: w.record.clone(), ..w }).collect();
262    let written = store.with_tx(|tx| {
263        for w in &copied {
264            tx.user_workspace_insert(w)?;
265        }
266        Ok(())
267    });
268    if let Err(e) = written {
269        tracing::warn!(error = %e, "user_workspace: couldn't copy the previous version's workspaces");
270        return None;
271    }
272    let open = current.filter(|id| copied.iter().any(|w| &w.id == id)).unwrap_or_else(|| copied[0].id.clone());
273    tracing::info!(
274        workspaces = copied.len(),
275        from = %path.display(),
276        "user_workspace: copied the previous version's workspaces"
277    );
278    Some(open)
279}
280
281// ---- Saving ----
282
283/// What a save did.
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub(crate) enum Saved {
286    Written,
287    /// The record already says this.
288    Unchanged,
289    /// No window is open: nothing to save, and the record is kept.
290    NoWindow,
291    /// A quit is closing the windows: it saved them all, and a save now
292    /// would keep only the ones still open.
293    HeldForQuit,
294    /// A switch is moving the windows to another workspace
295    /// (`user_workspace_switch`): a save now would store a mix of the two.
296    HeldForSwitch,
297    NoWorkspace,
298    Failed,
299}
300
301/// A change not yet saved: when the first came, and the last, and whether
302/// any changed the arrangement (not only blocks' settings).
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub(crate) struct Pending {
305    pub first_ms: i64,
306    pub last_ms: i64,
307    pub arranged: bool,
308}
309
310impl Pending {
311    /// A change seen at `now`, after `prev`; `arranged` when it changed the
312    /// arrangement.
313    pub(crate) fn changed(prev: Option<Pending>, now: i64, arranged: bool) -> Pending {
314        Pending {
315            first_ms: prev.map_or(now, |p| p.first_ms),
316            last_ms: now,
317            arranged: arranged || prev.is_some_and(|p| p.arranged),
318        }
319    }
320
321    /// Whether to save now. The arrangement: nothing changed for
322    /// [`DEBOUNCE_MS`], or the first unsaved change is [`CEILING_MS`] old.
323    /// Blocks' settings alone: the first is [`SETTINGS_ONLY_MS`] old.
324    pub(crate) fn due(&self, now: i64) -> bool {
325        if !self.arranged {
326            return now - self.first_ms >= SETTINGS_ONLY_MS;
327        }
328        now - self.last_ms >= DEBOUNCE_MS || now - self.first_ms >= CEILING_MS
329    }
330}
331
332/// Whether two records hold the same windows: equal but for `saved_at_ms`.
333fn same_windows(a: &Value, b: &Value) -> bool {
334    let strip = |v: &Value| {
335        let mut v = v.clone();
336        if let Some(o) = v.as_object_mut() {
337            o.remove("saved_at_ms");
338        }
339        v
340    };
341    strip(a) == strip(b)
342}
343
344/// Store `record` (the open windows) as the open workspace's windows, with
345/// its closed windows (`session_closed::with_closed`), unless that is what is
346/// stored already. Takes no lock; callers hold [`WRITE_LOCK`].
347fn write_record(store: &Store, record: Value) -> Saved {
348    let Some(id) = current_id(store) else { return Saved::NoWorkspace };
349    let mut record = super::session_closed::with_closed(store, record);
350    super::session_slots::into_record(store, &mut record);
351    let row = match store.user_workspace_get(&id) {
352        Ok(Some(row)) => row,
353        Ok(None) => return Saved::NoWorkspace,
354        Err(e) => {
355            tracing::warn!(error = %e, "user_workspace: couldn't read the open workspace");
356            return Saved::Failed;
357        }
358    };
359    let stored = row.record.as_deref().and_then(|r| serde_json::from_str::<Value>(r).ok());
360    if stored.is_some_and(|s| same_windows(&s, &record)) {
361        return Saved::Unchanged;
362    }
363    let now = now_ms();
364    if record.get("saved_at_ms").is_none() {
365        record["saved_at_ms"] = json!(now);
366    }
367    match store.user_workspace_save_record(&id, &record.to_string(), now) {
368        Ok(true) => Saved::Written,
369        Ok(false) => Saved::NoWorkspace,
370        Err(e) => {
371            tracing::warn!(error = %e, "user_workspace: saving the workspace failed");
372            Saved::Failed
373        }
374    }
375}
376
377/// Write `record` (a session record a boundary just built: a quit's, an OS
378/// shutdown's, the last close's) as the open workspace's windows.
379pub(crate) fn write_record_now(store: &Store, record: Value) -> Saved {
380    let _guard = WRITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
381    write_record(store, record)
382}
383
384/// Whether a quit is under way: its record is the session record and was
385/// saved within the last two minutes (`session_windows::is_recent_quit_record`).
386fn quit_holds_saves(store: &Store) -> bool {
387    super::session_restore::load_last_session_snapshot(store).is_some_and(|r| is_recent_quit_record(&r, now_ms()))
388}
389
390/// Save the open workspace from the live windows now.
391pub(crate) fn save_now(store: &Store) -> Saved {
392    let _guard = WRITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
393    // Read before the snapshot: a write after this is a change it may miss.
394    let generation = store.layout_writes().changed();
395    if store.layout_writes().saves_held() {
396        return Saved::HeldForSwitch;
397    }
398    if quit_holds_saves(store) {
399        return Saved::HeldForQuit;
400    }
401    let saved = match super::session_windows::snapshot_session(store, false) {
402        Some(record) => write_record(store, record),
403        None => Saved::NoWindow,
404    };
405    if matches!(saved, Saved::Written | Saved::Unchanged | Saved::NoWindow) {
406        store.layout_writes().mark_saved(generation);
407    }
408    if saved == Saved::Written {
409        tracing::debug!("user_workspace: saved");
410    }
411    saved
412}
413
414/// Save the open workspace as it changes, for as long as srv runs. The state
415/// it starts with is saved too (§8: the windows open at the first start with
416/// this become Default Workspace at once).
417pub(crate) fn spawn_saver(store: Arc<Store>) {
418    tokio::spawn(async move {
419        let mut seen = store.layout_writes().changed();
420        let mut seen_arranged = store.layout_writes().arranged();
421        let mut pending = Some(Pending::changed(None, now_ms(), true));
422        let mut first = true;
423        let mut tick = tokio::time::interval(TICK);
424        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
425        loop {
426            tick.tick().await;
427            let now = now_ms();
428            let changed = store.layout_writes().changed();
429            if changed != seen {
430                let arranged = store.layout_writes().arranged();
431                pending = Some(Pending::changed(pending, now, arranged != seen_arranged));
432                seen = changed;
433                seen_arranged = arranged;
434            }
435            let Some(p) = pending else { continue };
436            if !first && !store.layout_writes().dirty() {
437                // A flush saved it in between.
438                pending = None;
439                continue;
440            }
441            if !p.due(now) {
442                continue;
443            }
444            let s = Arc::clone(&store);
445            match tokio::task::spawn_blocking(move || save_now(&s)).await {
446                // Try again once the quit or the switch is over.
447                Ok(Saved::HeldForQuit | Saved::HeldForSwitch) => {}
448                Ok(Saved::Failed) | Err(_) => pending = Some(Pending::changed(None, now, p.arranged)),
449                Ok(_) => {
450                    pending = None;
451                    first = false;
452                }
453            }
454        }
455    });
456}
457
458/// `workspace.Flush`: save the open workspace now if anything changed since
459/// its last save. The window calls it when it loses focus. Returns
460/// `{ saved }`.
461pub(crate) async fn handle_flush(state: &AppState, _call: &WebCallType) -> WebReturnType {
462    if !state.mstore.layout_writes().dirty() {
463        return WebReturnType::success(json!({ "saved": false }));
464    }
465    let store = Arc::clone(&state.mstore);
466    match tokio::task::spawn_blocking(move || save_now(&store)).await {
467        Ok(saved) => WebReturnType::success(json!({ "saved": saved == Saved::Written })),
468        Err(e) => WebReturnType::error(format!("workspace flush: {e}")),
469    }
470}
471
472/// `workspace.RenameUserWorkspace(workspaceId, name)`: rename a workspace
473/// (`""` is the open one). The row and, for the open one, the client's
474/// `workspace:name` change in one transaction; the client goes back as an
475/// object update so every window's status bar panel shows the new name.
476pub(crate) fn handle_rename(state: &AppState, call: &WebCallType) -> WebReturnType {
477    let store = &state.mstore;
478    let requested: String = service::get_arg(&call.args, 0).unwrap_or_default();
479    let name: String = service::get_arg(&call.args, 1).unwrap_or_default();
480    let Some(name) = clean_name(&name) else {
481        return WebReturnType::error("a workspace needs a name");
482    };
483    let id = if requested.is_empty() { current_id(store).unwrap_or_default() } else { requested };
484    if id.is_empty() {
485        return WebReturnType::error("no workspace is open");
486    }
487    let result = store.with_tx(|tx| {
488        if !tx.user_workspace_rename(&id, &name, now_ms())? {
489            return Ok(Err(format!("no such workspace: {id}")));
490        }
491        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(Ok(None)) };
492        if client.meta.get(CURRENT_META_KEY).and_then(|v| v.as_str()) != Some(id.as_str()) {
493            return Ok(Ok(None));
494        }
495        client.meta.insert(NAME_META_KEY.to_string(), json!(name));
496        tx.update(&mut client)?;
497        Ok(Ok(Some(client)))
498    });
499    match result {
500        Ok(Ok(Some(client))) => {
501            tracing::info!(workspace = %id, name = %name, "user_workspace: renamed");
502            WebReturnType::success_with_updates(vec![MuxObjUpdate {
503                updatetype: "update".into(),
504                otype: "client".into(),
505                oid: client.oid.clone(),
506                obj: Some(mux_obj_to_value(&client)),
507            }])
508        }
509        Ok(Ok(None)) => WebReturnType::success_empty(),
510        Ok(Err(e)) => WebReturnType::error(e),
511        Err(e) => WebReturnType::error(format!("rename failed: {e}")),
512    }
513}
514
515// ---- Loading ----
516
517/// Which copy a launch loaded.
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519pub(crate) enum LoadedFrom {
520    /// The session record (`session:last_topology`).
521    Session,
522    /// The workspace's record.
523    Record,
524    /// The workspace's last clean load.
525    Previous,
526    /// The copy made before this version's first start.
527    PreUpgrade,
528}
529
530impl LoadedFrom {
531    /// An older copy, which the window tells the user about.
532    pub(crate) fn notice(self) -> Option<&'static str> {
533        match self {
534            LoadedFrom::Previous => Some("previous"),
535            LoadedFrom::PreUpgrade => Some("pre_upgrade"),
536            LoadedFrom::Session | LoadedFrom::Record => None,
537        }
538    }
539}
540
541fn parse_copy(which: &str, text: Option<&str>) -> Option<Value> {
542    let text = text?;
543    match serde_json::from_str::<Value>(text) {
544        Ok(v) if v.is_object() => Some(v),
545        Ok(_) => {
546            tracing::warn!(copy = which, "user_workspace: a saved copy is not a record; skipping it");
547            None
548        }
549        Err(e) => {
550            tracing::warn!(copy = which, error = %e, "user_workspace: a saved copy doesn't parse; skipping it");
551            None
552        }
553    }
554}
555
556fn saved_at(record: &Value) -> i64 {
557    record.get("saved_at_ms").and_then(|v| v.as_i64()).unwrap_or(0)
558}
559
560/// The records a cold start tries, in order: the newer of the session record
561/// and the workspace's record (the session record on a tie: a quit writes
562/// both), then the other, then `previous`, then `pre_upgrade`. A copy that
563/// doesn't parse is left out.
564pub(crate) fn launch_candidates(session: Option<Value>, row: Option<&UserWorkspaceRow>) -> Vec<(LoadedFrom, Value)> {
565    let record = row.and_then(|w| parse_copy("record", w.record.as_deref()));
566    let mut out = Vec::new();
567    match (session.filter(Value::is_object), record) {
568        (Some(s), Some(r)) if saved_at(&r) > saved_at(&s) => {
569            out.push((LoadedFrom::Record, r));
570            out.push((LoadedFrom::Session, s));
571        }
572        (Some(s), Some(r)) => {
573            out.push((LoadedFrom::Session, s));
574            out.push((LoadedFrom::Record, r));
575        }
576        (Some(s), None) => out.push((LoadedFrom::Session, s)),
577        (None, Some(r)) => out.push((LoadedFrom::Record, r)),
578        (None, None) => {}
579    }
580    if let Some(p) = row.and_then(|w| parse_copy("previous", w.previous.as_deref())) {
581        out.push((LoadedFrom::Previous, p));
582    }
583    if let Some(p) = row.and_then(|w| parse_copy("pre_upgrade", w.pre_upgrade.as_deref())) {
584        out.push((LoadedFrom::PreUpgrade, p));
585    }
586    out
587}
588
589/// What a launch restored: the window being created's workspace and events
590/// (as `restore_last_session` returns them), the record and where it came from.
591pub(crate) struct Restored {
592    pub main: (String, Vec<Event>),
593    pub loaded: Value,
594    pub from: LoadedFrom,
595}
596
597/// A cold start's restore: each of [`launch_candidates`] in turn until one
598/// brings a window back. `Ok(None)` when none had anything; the default seed
599/// follows.
600pub(crate) async fn restore_at_launch(state: &AppState) -> Result<Option<Restored>, String> {
601    let store = &state.mstore;
602    let row = current_id(store).and_then(|id| store.user_workspace_get(&id).ok().flatten());
603    let candidates = launch_candidates(super::session_restore::load_last_session_snapshot(store), row.as_ref());
604    let mut first_err = None;
605    for (from, record) in candidates {
606        // Its windows keep the order they were listed in.
607        super::session_slots::adopt(store, &record);
608        match super::session_windows::restore_all(state, &record).await {
609            Ok(Some(main)) => {
610                if let Some(which) = from.notice() {
611                    tracing::warn!(copy = which, "user_workspace: the saved workspace didn't load; restored an older copy");
612                }
613                // The session record holds only the open windows: the closed
614                // ones come from the workspace's record (§5).
615                if from == LoadedFrom::Session {
616                    if let Some(own) = row.as_ref().and_then(|w| parse_copy("record", w.record.as_deref())) {
617                        let shown = super::session_windows::windows_of(&record)
618                            .iter()
619                            .filter_map(|w| w.get("workspaceid").and_then(|v| v.as_str()).map(str::to_string))
620                            .collect();
621                        super::session_closed::restore_closed(state, &own, &main.0, &shown).await;
622                    }
623                }
624                return Ok(Some(Restored { main, loaded: record, from }));
625            }
626            Ok(None) => tracing::warn!(copy = ?from, "user_workspace: nothing came back from a saved copy"),
627            Err(e) => {
628                tracing::warn!(copy = ?from, error = %e, "user_workspace: a saved copy didn't restore");
629                first_err.get_or_insert(e);
630            }
631        }
632    }
633    match first_err {
634        Some(e) => Err(e),
635        None => Ok(None),
636    }
637}
638
639/// A restore finished cleanly (`window_create`'s final read-back): keep what
640/// loaded as the workspace's `previous`, and when it was an older copy, leave
641/// the window a note to say so.
642pub(crate) fn after_clean_load(store: &Store, loaded: &Value, from: LoadedFrom) {
643    if let Some(id) = current_id(store) {
644        // A quit's record holds the open windows only: keep the closed ones
645        // the restore listed with it, so `previous` recovers them too (#5359).
646        let has_closed = super::session_windows::windows_of(loaded).iter().any(super::session_closed::is_closed);
647        let loaded = if has_closed || super::session_closed::closed_entries(store).is_empty() {
648            loaded.clone()
649        } else {
650            super::session_closed::with_closed(store, loaded.clone())
651        };
652        if let Err(e) = store.user_workspace_set_previous(&id, &loaded.to_string()) {
653            tracing::warn!(error = %e, "user_workspace: couldn't keep the loaded copy");
654        }
655    }
656    if let Some(which) = from.notice() {
657        set_client_meta(store, RESTORED_FROM_META_KEY, Some(json!(which)));
658    }
659}
660
661#[cfg(test)]
662#[path = "user_workspace_tests.rs"]
663mod tests;