Skip to main content

agentmux_srv/server/service/
session_windows.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Every window comes back after a quit, an upgrade's included
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §6.1).
6//!
7//! The session record (`session_restore`, `Client.meta["session:last_topology"]`)
8//! held one workspace: the last window's, saved by the close that emptied
9//! `Client.windowids`. A quit closes the windows one by one and each close
10//! deletes its workspace, so with several windows open only the last came back.
11//!
12//! Now:
13//! - a quit asks srv for the whole session before any window closes
14//!   (`SaveSessionSnapshot` with `for_quit`, from the host's `quit_app`), and so
15//!   does the OS-shutdown flush: one entry per window in `windows`, the main
16//!   window first, each the shape `snapshot_workspace` makes plus the window's
17//!   position and size under `window`;
18//! - the close that then empties `Client.windowids` keeps a quit's record
19//!   instead of replacing it with its own workspace ([`save_on_last_close`]);
20//! - restore rebuilds the first entry into the window being created, as
21//!   before, and every other entry into a workspace of its own, which the main
22//!   window then opens each where it was (`TakeRestoredWindows`, then the
23//!   host's `open_restored_window`).
24//!
25//! Names come back too: each window's own (`window:displayname`, under
26//! `window.name`) and its workspace's (`name`). The restore names each
27//! workspace as it creates it.
28//!
29//! So does each window's appearance: its own theme and opacity
30//! (`window:theme`, `window:opacity`, [`INHERITED_KEYS`]), under `window.meta`.
31//! They live only on the Window row, and a quit deletes the row, so without
32//! this every quit and relaunch put them back to the defaults
33//! (`RCA_UPGRADE_0_59_30_TO_0_59_34_ISSUES_2026_10_19.md` §2). `window:transparent`
34//! is not among them: it is a setting of the whole app, in settings.json.
35//!
36//! A window's name and appearance wait in the client's meta
37//! (`session:restored_window_names`, by workspace) for the window that opens
38//! onto that workspace, which `CreateWindow` writes onto its row
39//! ([`restored_window_meta`]), and is forgotten only once that is written
40//! ([`forget_restored_window_meta`]). The value is the window's meta patch;
41//! the bare name an earlier version left still reads.
42//!
43//! The record keeps the main window's tabs at its top level too, the shape it
44//! always had, so an older AgentMux reading it still restores that window. A
45//! record without `windows` reads as one window.
46
47use agentmux_common::ipc::Event;
48use serde_json::{json, Value};
49
50use super::window_inherit::INHERITED_KEYS;
51use crate::backend::obj::{Client, Window, Workspace};
52use crate::backend::service::{WebCallType, WebReturnType};
53use crate::backend::storage::store::Store;
54use crate::server::AppState;
55
56/// Restored workspaces waiting for the main window to open them.
57const WAITING_META_KEY: &str = "session:restored_windows";
58
59/// Restored workspaces the main window took (`TakeRestoredWindows`) and is
60/// opening: kept for saves until a window shows each, so a save in between
61/// doesn't drop one that opens slowly or not at all (#5358).
62const OPENING_META_KEY: &str = "session:restored_windows_opening";
63
64/// Restored windows' names and appearance, by workspace, waiting for their
65/// windows. (Named for what it first held: a name.)
66const NAMES_META_KEY: &str = "session:restored_window_names";
67
68/// The Window meta key of the name the user gave the window.
69const NAME_KEY: &str = "window:displayname";
70
71/// The name window `w` goes by in a session record: the user's, or one a
72/// restore still holds for it, whose write to the window failed: the next
73/// save keeps it, so the restore after names it.
74pub(crate) fn saved_name(store: &Store, w: &Window) -> Option<String> {
75    window_name(w).or_else(|| restored_window_name(store, &w.workspaceid))
76}
77
78/// The appearance a session record keeps for window `w`: its own theme and
79/// opacity, or those a restore still holds for it, whose write to the window
80/// failed (the next save keeps them, as it keeps a name).
81pub(crate) fn saved_appearance(store: &Store, w: &Window) -> serde_json::Map<String, Value> {
82    let waiting = restored_window_meta(store, &w.workspaceid);
83    INHERITED_KEYS
84        .iter()
85        .filter_map(|k| {
86            let v = w.meta.get(*k).filter(|v| !v.is_null()).or_else(|| waiting.get(*k))?;
87            Some((k.to_string(), v.clone()))
88        })
89        .collect()
90}
91
92/// The meta patch a record entry's `window` section gives its restored window:
93/// the name, and the appearance that is a theme (a string) and an opacity (a
94/// number). Nothing else a record says reaches a row.
95pub(crate) fn patch_of(window: &Value) -> serde_json::Map<String, Value> {
96    let mut patch = serde_json::Map::new();
97    if let Some(name) = window.get("name").and_then(|v| v.as_str()).map(str::trim).filter(|n| !n.is_empty()) {
98        patch.insert(NAME_KEY.to_string(), json!(name));
99    }
100    let meta = window.get("meta");
101    if let Some(theme) = meta.and_then(|m| m.get("window:theme")).filter(|v| v.is_string()) {
102        patch.insert("window:theme".to_string(), theme.clone());
103    }
104    if let Some(opacity) = meta.and_then(|m| m.get("window:opacity")).filter(|v| v.is_number()) {
105        patch.insert("window:opacity".to_string(), opacity.clone());
106    }
107    patch
108}
109
110/// What waits for one workspace, as a patch: an object of meta, or the bare
111/// name an earlier version left.
112fn waiting_patch(v: &Value) -> serde_json::Map<String, Value> {
113    match v {
114        Value::String(name) => patch_of(&json!({ "name": name })),
115        Value::Object(o) => patch_of(&json!({ "name": o.get(NAME_KEY), "meta": o })),
116        _ => serde_json::Map::new(),
117    }
118}
119
120/// The name the user gave window `w`, if any.
121pub(crate) fn window_name(w: &Window) -> Option<String> {
122    w.meta
123        .get(NAME_KEY)
124        .and_then(|v| v.as_str())
125        .map(str::trim)
126        .filter(|n| !n.is_empty())
127        .map(str::to_string)
128}
129
130/// How long a quit's record outranks the last close's: a quit closes every
131/// window within seconds, and one that stalls longer than this was abandoned.
132const QUIT_RECORD_KEPT_FOR_MS: i64 = 120_000;
133
134/// The live full windows, the main one first, each with its workspace.
135/// Subwindows belong to their parent's window; a window whose workspace is
136/// gone, or an id with no window row, is skipped.
137pub(crate) fn live_windows(store: &Store) -> Vec<(Window, String)> {
138    let Some(client) = store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next()) else {
139        return Vec::new();
140    };
141    let mut seen = std::collections::HashSet::new();
142    let mut windows: Vec<(Window, String)> = client
143        .windowids
144        .iter()
145        .filter_map(|id| store.get::<Window>(id).ok().flatten())
146        .filter(|w| w.kind.as_deref() != Some("subwindow"))
147        .filter(|w| store.get::<Workspace>(&w.workspaceid).ok().flatten().is_some())
148        .filter(|w| seen.insert(w.workspaceid.clone()))
149        .map(|w| {
150            let ws = w.workspaceid.clone();
151            (w, ws)
152        })
153        .collect();
154    // The main window first: by its `host:label`, and otherwise by the order
155    // the windows opened, since it opens first (a row can lack the label).
156    windows.sort_by_key(|(w, _)| w.meta.get("host:label").and_then(|v| v.as_str()) != Some("main"));
157    windows
158}
159
160/// The workspaces some open window shows, a subwindow's included: a pane in one of them is on screen.
161pub(crate) fn open_workspace_ids(store: &Store) -> std::collections::HashSet<String> {
162    let Some(client) = store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next()) else {
163        return Default::default();
164    };
165    client
166        .windowids
167        .iter()
168        .filter_map(|id| store.get::<Window>(id).ok().flatten())
169        .map(|w| w.workspaceid)
170        .filter(|ws| store.get::<Workspace>(ws).ok().flatten().is_some())
171        .collect()
172}
173
174/// Whether any live window has a workspace to capture.
175pub(crate) fn has_live_window(store: &Store) -> bool {
176    !live_windows(store).is_empty()
177}
178
179/// The whole session: every live window's workspace and placement, the main
180/// window's tabs also at the top level. `None` when no window has anything to
181/// capture. `for_quit` marks it as a quit's, which the closes that follow keep.
182pub(crate) fn snapshot_session(store: &Store, for_quit: bool) -> Option<Value> {
183    let live = live_windows(store);
184    let window_ids: Vec<String> = live.iter().map(|(w, _)| w.oid.clone()).collect();
185    let live_ws: std::collections::HashSet<String> = live.iter().map(|(_, ws)| ws.clone()).collect();
186    let windows: Vec<Value> = live
187        .into_iter()
188        .filter_map(|(w, ws)| {
189            let mut entry = super::session_restore::snapshot_workspace(store, &ws)?;
190            entry["window"] = super::session_closed::placement_of(store, &w);
191            // A close keeps the window's contents (`session_closed`): the
192            // restore reopens them, and rebuilds them from this entry only if
193            // they are gone.
194            entry["workspaceid"] = json!(ws);
195            Some(entry)
196        })
197        .chain(waiting_windows(store, &live_ws))
198        .collect();
199    let mut record = windows.first()?.clone();
200    if let Some(obj) = record.as_object_mut() {
201        obj.remove("window");
202    }
203    record["windows"] = Value::Array(windows);
204    super::session_slots::into_record(store, &mut record);
205    if for_quit {
206        record["saved_for"] = json!("quit");
207        record["saved_at_ms"] = json!(agentmux_common::time::now_ms());
208        // The windows this quit saved: the only ones startup may forget.
209        record["window_ids"] = json!(window_ids);
210    }
211    Some(record)
212}
213
214/// The restored windows still waiting for the main window to open them
215/// (`restore_all`), as record entries: their workspaces exist, but no window
216/// shows them yet, so a snapshot of the live windows alone would drop them
217/// (#5358).
218fn waiting_windows(store: &Store, live_ws: &std::collections::HashSet<String>) -> Vec<Value> {
219    let client = store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next());
220    let list = |key: &str| client.as_ref().and_then(|c| c.meta.get(key)?.as_array().cloned()).unwrap_or_default();
221    let mut seen = std::collections::HashSet::new();
222    list(WAITING_META_KEY)
223        .into_iter()
224        .chain(list(OPENING_META_KEY))
225        .filter(|p| p.get("workspaceid").and_then(|v| v.as_str()).is_some_and(|ws| seen.insert(ws.to_string())))
226        .filter_map(|mut placement| {
227            let ws = placement.get("workspaceid")?.as_str()?.to_string();
228            if live_ws.contains(&ws) {
229                return None;
230            }
231            let mut entry = super::session_restore::snapshot_workspace(store, &ws)?;
232            placement.as_object_mut()?.remove("workspaceid");
233            entry["window"] = placement;
234            entry["workspaceid"] = json!(ws);
235            Some(entry)
236        })
237        .collect()
238}
239
240/// The contents of the restored windows still waiting for the main window to
241/// open them.
242pub(crate) fn waiting_workspaces(store: &Store) -> std::collections::HashSet<String> {
243    store
244        .get_all::<Client>()
245        .ok()
246        .and_then(|cs| cs.into_iter().next())
247        .and_then(|c| c.meta.get(WAITING_META_KEY).and_then(|v| v.as_array().cloned()))
248        .unwrap_or_default()
249        .iter()
250        .filter_map(|w| w.get("workspaceid").and_then(|v| v.as_str()).map(str::to_string))
251        .collect()
252}
253
254/// The windows a record holds: its `windows`, or the record itself for one
255/// saved before records held several.
256pub(crate) fn windows_of(record: &Value) -> Vec<Value> {
257    match record.get("windows").and_then(|v| v.as_array()) {
258        Some(windows) if !windows.is_empty() => windows.clone(),
259        _ => vec![record.clone()],
260    }
261}
262
263/// Whether `record` is a quit's, saved within the last two minutes: the
264/// closes of that quit are still arriving.
265pub(crate) fn is_recent_quit_record(record: &Value, now_ms: i64) -> bool {
266    record.get("saved_for").and_then(|v| v.as_str()) == Some("quit")
267        && record
268            .get("saved_at_ms")
269            .and_then(|v| v.as_i64())
270            .is_some_and(|at| (0..QUIT_RECORD_KEPT_FOR_MS).contains(&(now_ms - at)))
271}
272
273/// The close that empties `Client.windowids`, before `ws_id` is kept or
274/// deleted: saves that workspace as the session, with the closing window's `name` and
275/// `appearance` (read before its row was pruned), unless this close is one of
276/// a quit's that already saved every window.
277pub(crate) fn save_on_last_close(
278    store: &Store,
279    ws_id: &str,
280    name: Option<&str>,
281    appearance: &serde_json::Map<String, Value>,
282) {
283    let kept = super::session_restore::load_last_session_snapshot(store)
284        .is_some_and(|r| is_recent_quit_record(&r, agentmux_common::time::now_ms()));
285    if kept {
286        tracing::info!(workspace_id = %ws_id, "session_restore: keeping the record the quit saved for every window");
287        return;
288    }
289    if let Some(mut snapshot) = super::session_restore::snapshot_workspace(store, ws_id) {
290        let mut window = serde_json::Map::new();
291        if let Some(name) = name.map(str::trim).filter(|n| !n.is_empty()) {
292            window.insert("name".to_string(), json!(name));
293        }
294        if !appearance.is_empty() {
295            window.insert("meta".to_string(), Value::Object(appearance.clone()));
296        }
297        if !window.is_empty() {
298            snapshot["window"] = Value::Object(window);
299        }
300        // When it was closed, for another build offering it (`session_other_builds`).
301        snapshot["saved_at_ms"] = json!(agentmux_common::time::now_ms());
302        // The close keeps the workspace: the restore reopens it as it was.
303        snapshot["workspaceid"] = json!(ws_id);
304        super::session_restore::save_last_session_snapshot(store, snapshot.clone());
305        // The open workspace keeps it too (`user_workspace`), whole: the saver
306        // makes no save with no window open.
307        super::user_workspace::write_record_now(store, snapshot);
308    }
309}
310
311/// At startup, before anything reads the windows: when the last run ended in
312/// a quit that saved every window (the record is a quit's), a window still
313/// listed is one whose close didn't reach srv before it stopped. The host
314/// closes windows concurrently and srv can exit first; seen in a simulated
315/// upgrade, where the second window's row survived and the main window then
316/// took it instead of restoring the session. The record holds that window, so
317/// forget its row: the first window then restores every window as designed.
318/// Its workspace stays when the record names it (the restore reopens it), and
319/// goes with its tabs and panes when it doesn't (a record an older build
320/// wrote, which rebuilds it instead). Only the windows the quit saved (its
321/// `window_ids`) are forgotten: a record left from an older quit never costs a
322/// later run its windows. Returns how many it forgot.
323pub(crate) fn forget_windows_left_by_quit(store: &Store) -> usize {
324    let record = super::session_restore::load_last_session_snapshot(store)
325        .filter(|r| r.get("saved_for").and_then(|v| v.as_str()) == Some("quit"));
326    let saved: std::collections::HashSet<String> = record
327        .as_ref()
328        .and_then(|r| r.get("window_ids").and_then(|v| v.as_array()).cloned())
329        .unwrap_or_default()
330        .into_iter()
331        .filter_map(|v| v.as_str().map(str::to_string))
332        .collect();
333    let named: std::collections::HashSet<String> = record
334        .as_ref()
335        .map(windows_of)
336        .unwrap_or_default()
337        .iter()
338        .filter_map(|w| w.get("workspaceid").and_then(|v| v.as_str()).map(str::to_string))
339        .collect();
340    let Some(mut client) = store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next()) else {
341        return 0;
342    };
343    let (left, kept): (Vec<String>, Vec<String>) = client.windowids.iter().cloned().partition(|id| saved.contains(id));
344    if left.is_empty() {
345        return 0;
346    }
347    client.windowids = kept;
348    for id in &left {
349        if let Some(w) = store.get::<Window>(id).ok().flatten() {
350            if !named.contains(&w.workspaceid) && store.get::<Workspace>(&w.workspaceid).ok().flatten().is_some() {
351                let _ = crate::backend::wcore::delete_workspace(store, &w.workspaceid);
352            }
353            let _ = store.delete::<Window>(id);
354        }
355    }
356    if let Err(e) = store.update(&mut client) {
357        tracing::warn!(error = %e, "session_restore: couldn't forget the windows a quit left behind");
358        return 0;
359    }
360    tracing::info!(windows = left.len(), "session_restore: forgot windows a quit left behind; the session restores them");
361    left.len()
362}
363
364/// Forget the restored windows waiting to open, those opening, and their
365/// names: they belong to the workspace that was open, which a switch closes
366/// (`user_workspace_switch`).
367pub(crate) fn forget_restore_lists(meta: &mut crate::backend::obj::MetaMapType) {
368    for key in RESTORE_LIST_KEYS {
369        meta.remove(key);
370    }
371}
372
373/// The client meta keys of the restored windows' queues.
374pub(crate) const RESTORE_LIST_KEYS: [&str; 3] = [WAITING_META_KEY, OPENING_META_KEY, NAMES_META_KEY];
375
376/// Set (or, with `None`, remove) one of the client's meta keys.
377pub(crate) fn set_client_meta(store: &Store, key: &str, value: Option<Value>) {
378    let result = store.with_tx(|tx| {
379        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else {
380            return Ok(());
381        };
382        match value {
383            Some(v) => {
384                client.meta.insert(key.to_string(), v);
385            }
386            None => {
387                if client.meta.remove(key).is_none() {
388                    return Ok(());
389                }
390            }
391        }
392        tx.update(&mut client)?;
393        Ok(())
394    });
395    if let Err(e) = result {
396        tracing::warn!(error = %e, key, "session_restore: client meta write failed");
397    }
398}
399
400/// Restore every window in `record`: the first that comes back is the one
401/// being created (returned, as `restore_last_session` always did); each other
402/// one gets a workspace of its own, published and left for
403/// [`handle_take_restored_windows`]. A workspace record's closed windows
404/// (`"state": "closed"`) stay closed (`session_closed::restore_closed`), once
405/// a window came back.
406pub(crate) async fn restore_all(state: &AppState, record: &Value) -> Result<Option<(String, Vec<Event>)>, String> {
407    let mut main = None;
408    let mut waiting = Vec::new();
409    let mut waiting_meta = serde_json::Map::new();
410    let mut first_err = None;
411    let mut restored_count = 0usize;
412    let mut reopened = 0usize;
413    let mut taken = std::collections::HashSet::new();
414    let all = windows_of(record);
415    let open: Vec<&Value> = all.iter().filter(|w| !super::session_closed::is_closed(w)).collect();
416    for (i, window) in open.iter().copied().enumerate() {
417        let restored = match reusable_workspace(state, window, &taken).await {
418            Some(ws_id) => {
419                reopened += 1;
420                taken.insert(ws_id.clone());
421                super::session_closed::forget(&state.mstore, &ws_id);
422                // Agents a switch away parked (the record names them) are back in their tabs before the window shows them.
423                let back = crate::sagas::park_agents::reattach_window_agents(state, &ws_id, &super::session_closed::parked_of(window)).await;
424                if back > 0 {
425                    tracing::info!(workspace_id = %ws_id, agents = back, "session_restore: the workspace's agents are back in its tabs");
426                }
427                Ok(Some((ws_id, Vec::new())))
428            }
429            None => super::session_restore::restore_workspace(state, window).await,
430        };
431        if let Ok(Some((ws_id, _))) = &restored {
432            let patch = window.get("window").map(patch_of).unwrap_or_default();
433            if !patch.is_empty() {
434                waiting_meta.insert(ws_id.clone(), Value::Object(patch));
435            }
436        }
437        match restored {
438            Ok(Some(restored)) if main.is_none() => {
439                restored_count += 1;
440                main = Some(restored);
441            }
442            Ok(Some((ws_id, events))) => {
443                restored_count += 1;
444                super::reducer_helpers::publish_events(state, &events);
445                let mut entry = window.get("window").cloned().unwrap_or_else(|| json!({}));
446                entry["workspaceid"] = json!(ws_id);
447                waiting.push(entry);
448            }
449            Ok(None) => tracing::warn!(window = i, "session_restore: a window's tabs didn't come back; skipping it"),
450            Err(e) => {
451                tracing::warn!(window = i, error = %e, "session_restore: a window didn't come back");
452                first_err.get_or_insert(e);
453            }
454        }
455    }
456    // One line for every restore, a one-window one included: after a quit the
457    // store loads no workspace, tab, block or window, which reads like data loss
458    // unless this says the layout came back from the record.
459    if restored_count > 0 {
460        let from = if record.get("saved_for").and_then(|v| v.as_str()) == Some("quit") { "quit" } else { "last-close" };
461        tracing::info!(
462            windows = restored_count,
463            reopened,
464            "session_restore: restored {} window(s) from the {} record ({} kept as they were, the rest rebuilt)",
465            restored_count,
466            from,
467            reopened
468        );
469    }
470    set_client_meta(&state.mstore, WAITING_META_KEY, (!waiting.is_empty()).then(|| Value::Array(waiting)));
471    set_client_meta(&state.mstore, OPENING_META_KEY, None);
472    set_client_meta(&state.mstore, NAMES_META_KEY, (!waiting_meta.is_empty()).then(|| Value::Object(waiting_meta)));
473    if let Some((main_ws, _)) = &main {
474        let shown = open
475            .iter()
476            .filter_map(|w| w.get("workspaceid").and_then(|v| v.as_str()).map(str::to_string))
477            .collect();
478        super::session_closed::restore_closed(state, record, main_ws, &shown).await;
479    }
480    match (main, first_err) {
481        (Some(main), _) => Ok(Some(main)),
482        (None, Some(e)) => Err(e),
483        (None, None) => Ok(None),
484    }
485}
486
487/// The workspace a record entry names, when it is still there to reopen as it
488/// was: the reducer and the store have it, it holds a pane, no window shows
489/// it, and no earlier entry of this restore took it. `None` means rebuild the
490/// entry from the record.
491async fn reusable_workspace(
492    state: &AppState,
493    window: &Value,
494    taken: &std::collections::HashSet<String>,
495) -> Option<String> {
496    let ws_id = window.get("workspaceid").and_then(|v| v.as_str()).filter(|s| !s.is_empty())?;
497    if taken.contains(ws_id) || !state.srv_state.lock().await.workspaces.contains_key(ws_id) {
498        return None;
499    }
500    // A close still stopping its agents (srv kept running with no window) finishes first.
501    drop(crate::sagas::close_pane::workspace_close_lock(ws_id).await);
502    let store = &state.mstore;
503    super::session_restore::snapshot_workspace(store, ws_id)?;
504    if super::session_closed::open_workspaces(store).contains(ws_id) {
505        return None;
506    }
507    Some(ws_id.to_string())
508}
509
510/// Add restored workspaces for the main window to open beside it
511/// (`entries`: placement plus `workspaceid`, as [`restore_all`] queues them)
512/// and their windows' meta patches, keeping any already waiting.
513pub(crate) fn queue_restored_windows(store: &Store, entries: Vec<Value>, metas: serde_json::Map<String, Value>) {
514    let client = store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next());
515    let meta_of = |key: &str| client.as_ref().and_then(|c| c.meta.get(key).cloned());
516    if !entries.is_empty() {
517        let mut waiting = meta_of(WAITING_META_KEY).and_then(|v| v.as_array().cloned()).unwrap_or_default();
518        waiting.extend(entries);
519        set_client_meta(store, WAITING_META_KEY, Some(Value::Array(waiting)));
520    }
521    if !metas.is_empty() {
522        let mut names = meta_of(NAMES_META_KEY).and_then(|v| v.as_object().cloned()).unwrap_or_default();
523        names.extend(metas);
524        set_client_meta(store, NAMES_META_KEY, Some(Value::Object(names)));
525    }
526}
527
528/// The name and appearance a restored window had, as the meta patch for the
529/// window now opening onto its workspace `ws_id` (`CreateWindow`). It stays
530/// until [`forget_restored_window_meta`]: a window whose meta couldn't be
531/// written (srv stopped in between, a failed write) gets it on its next try.
532pub(crate) fn restored_window_meta(store: &Store, ws_id: &str) -> serde_json::Map<String, Value> {
533    store
534        .get_all::<Client>()
535        .ok()
536        .and_then(|cs| cs.into_iter().next())
537        .and_then(|c| c.meta.get(NAMES_META_KEY)?.get(ws_id).map(waiting_patch))
538        .unwrap_or_default()
539}
540
541/// The name a restored window had, for the window now opening onto `ws_id`.
542pub(crate) fn restored_window_name(store: &Store, ws_id: &str) -> Option<String> {
543    restored_window_meta(store, ws_id).get(NAME_KEY).and_then(|v| v.as_str()).map(str::to_string)
544}
545
546/// `ws_id`'s window has its meta: forget it, once. Read, remove and write
547/// back in one transaction: restored windows open together, and two of these
548/// must not each write back the entry the other removed.
549pub(crate) fn forget_restored_window_meta(store: &Store, ws_id: &str) -> Option<serde_json::Map<String, Value>> {
550    let taken = store.with_tx(|tx| {
551        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(None) };
552        let Some(mut waiting) = client.meta.get(NAMES_META_KEY).and_then(|v| v.as_object().cloned()) else {
553            return Ok(None);
554        };
555        let Some(entry) = waiting.remove(ws_id) else { return Ok(None) };
556        if waiting.is_empty() {
557            client.meta.remove(NAMES_META_KEY);
558        } else {
559            client.meta.insert(NAMES_META_KEY.to_string(), Value::Object(waiting));
560        }
561        tx.update(&mut client)?;
562        Ok(Some(waiting_patch(&entry)))
563    });
564    taken.unwrap_or_else(|e| {
565        tracing::warn!(error = %e, "session_restore: couldn't forget a restored window's meta");
566        None
567    })
568}
569
570/// `window.TakeRestoredWindows`: the workspaces a restore rebuilt beside the
571/// main window's, each with its saved placement (`workspaceid`, `x`, `y`,
572/// `width`, `height`), for the main window to open. Handed out once; one
573/// whose workspace is gone since is left out.
574pub(crate) fn handle_take_restored_windows(state: &AppState, _call: &WebCallType) -> WebReturnType {
575    let store = &state.mstore;
576    // One transaction moves them from waiting to opening, so no save sees
577    // them in neither list (#5358).
578    let waiting = store
579        .with_tx(|tx| {
580            let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(Vec::new()) };
581            let Some(waiting) = client.meta.remove(WAITING_META_KEY).and_then(|v| v.as_array().cloned()) else {
582                return Ok(Vec::new());
583            };
584            let mut opening = client.meta.get(OPENING_META_KEY).and_then(|v| v.as_array().cloned()).unwrap_or_default();
585            opening.extend(waiting.iter().cloned());
586            if !opening.is_empty() {
587                client.meta.insert(OPENING_META_KEY.to_string(), Value::Array(opening));
588            }
589            tx.update(&mut client)?;
590            Ok(waiting)
591        })
592        .unwrap_or_else(|e| {
593            tracing::warn!(error = %e, "session_restore: couldn't take the restored windows");
594            Vec::new()
595        });
596    let live: Vec<Value> = waiting
597        .into_iter()
598        .filter(|w| {
599            w.get("workspaceid")
600                .and_then(|v| v.as_str())
601                .is_some_and(|id| store.get::<Workspace>(id).ok().flatten().is_some())
602        })
603        .collect();
604    WebReturnType::success(Value::Array(live))
605}
606
607/// A window now shows restored workspace `ws_id`: saves take it from the
608/// live windows from here on.
609pub(crate) fn restored_window_opened(store: &Store, ws_id: &str) {
610    let _ = store.with_tx(|tx| {
611        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(()) };
612        let Some(opening) = client.meta.get(OPENING_META_KEY).and_then(|v| v.as_array().cloned()) else { return Ok(()) };
613        let left: Vec<Value> =
614            opening.into_iter().filter(|e| e.get("workspaceid").and_then(|v| v.as_str()) != Some(ws_id)).collect();
615        if left.is_empty() {
616            client.meta.remove(OPENING_META_KEY);
617        } else {
618            client.meta.insert(OPENING_META_KEY.to_string(), Value::Array(left));
619        }
620        tx.update(&mut client)?;
621        Ok(())
622    });
623}
624
625#[cfg(test)]
626#[path = "session_windows_tests.rs"]
627mod tests;