Skip to main content

agentmux_srv/server/service/
session_closed.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Closed windows: closing a window keeps it in the open workspace
5//! (`docs/specs/SPEC_WORKSPACES_2026_10_23.md` §2, §5; closing is not
6//! deleting, `SPEC_OFFLINE_RESILIENCE_2026_10_20.md` G8).
7//!
8//! A window's close stops what runs in its contents (its shells, the ordinary
9//! graceful close) and keeps them: its tabs, its panes with their ids and meta,
10//! and their layout. Its agents keep running (`agents:always_available`): their
11//! blocks are parked, and a reopen puts them back in their tabs. The window is then a **closed** window of
12//! the workspace, listed in the client's meta (`workspace:closed_windows`,
13//! newest first) with when it closed, where it was, its name and appearance.
14//! - The workspace record keeps each one as a `"state": "closed"` entry
15//!   ([`with_closed`]). A cold start keeps it closed ([`restore_closed`]): its
16//!   contents are reused when they are still here and rebuilt from the entry
17//!   when not, and no window opens for it.
18//! - The status bar panel lists them (`ListClosedWindows`), reopens one where
19//!   it was (`TakeClosedWindow`) and deletes one (`DeleteClosedWindow`). An
20//!   open window is deleted by marking its close (`DiscardWorkspaceOnClose`),
21//!   which then deletes its contents instead of keeping them.
22//!
23//! They stay until the user deletes them: no cap. Not listed: the close that
24//! ends the session (the last window's, or one of a quit's), whose window
25//! stays open in the workspace and reopens at the next launch; a workspace
26//! switch's closes (`user_workspace_switch`), whose windows stay open in the
27//! workspace they leave and open again with it; and a window
28//! with nothing of the user's in it (no pane, or only the untouched default
29//! layout), whose contents are deleted at its close.
30
31use std::collections::{HashMap, HashSet};
32use std::sync::{LazyLock, Mutex};
33use std::time::{Duration, Instant};
34
35use agentmux_common::time::now_ms;
36use serde_json::{json, Value};
37
38use crate::backend::obj::{Block, Client, Window, Workspace};
39use crate::backend::service::{self, WebCallType, WebReturnType};
40use crate::backend::storage::store::Store;
41use crate::server::AppState;
42
43/// The open workspace's closed windows, newest first:
44/// `{workspaceid, closed_at_ms, window}`.
45pub(crate) const CLOSED_META_KEY: &str = "workspace:closed_windows";
46
47/// A workspace record entry's `state`: shown now, or reopened at the next launch.
48pub(crate) const STATE_OPEN: &str = "open";
49/// A workspace record entry's `state`: closed, kept to reopen.
50pub(crate) const STATE_CLOSED: &str = "closed";
51
52/// How long a delete waits for its window's close to reach srv. A close that
53/// never comes (the window stayed open) must not make a later, ordinary close
54/// delete the window's contents.
55const DISCARD_FOR: Duration = Duration::from_secs(60);
56
57static DISCARD: LazyLock<Mutex<HashMap<String, Instant>>> = LazyLock::new(Default::default);
58
59/// Delete an open window: the next close of `window_id` deletes its contents.
60pub(crate) fn mark_discard(window_id: &str) {
61    let mut marks = DISCARD.lock().unwrap_or_else(|e| e.into_inner());
62    marks.retain(|_, at| at.elapsed() < DISCARD_FOR);
63    marks.insert(window_id.to_string(), Instant::now());
64}
65
66/// Whether this close of `window_id` is a delete's. Asked once.
67pub(crate) fn take_discard(window_id: &str) -> bool {
68    let mut marks = DISCARD.lock().unwrap_or_else(|e| e.into_inner());
69    marks.remove(window_id).is_some_and(|at| at.elapsed() < DISCARD_FOR)
70}
71
72/// Where window `w` is, its name and appearance: a record entry's `window`.
73pub(crate) fn placement_of(store: &Store, w: &Window) -> Value {
74    let mut window = json!({
75        "x": w.pos.x,
76        "y": w.pos.y,
77        "width": w.winsize.width,
78        "height": w.winsize.height,
79    });
80    if let Some(name) = super::session_windows::saved_name(store, w) {
81        window["name"] = json!(name);
82    }
83    let appearance = super::session_windows::saved_appearance(store, w);
84    if !appearance.is_empty() {
85        window["meta"] = Value::Object(appearance);
86    }
87    window
88}
89
90fn workspace_of(entry: &Value) -> Option<&str> {
91    entry.get("workspaceid").and_then(|v| v.as_str()).filter(|s| !s.is_empty())
92}
93
94fn closed_at(entry: &Value) -> i64 {
95    entry.get("closed_at_ms").and_then(|v| v.as_i64()).unwrap_or(0)
96}
97
98/// Whether a workspace record entry is a closed window's.
99pub(crate) fn is_closed(entry: &Value) -> bool {
100    entry.get("state").and_then(|v| v.as_str()) == Some(STATE_CLOSED)
101}
102
103fn client(store: &Store) -> Option<Client> {
104    store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next())
105}
106
107fn entries(store: &Store) -> Vec<Value> {
108    client(store)
109        .and_then(|c| c.meta.get(CLOSED_META_KEY).and_then(|v| v.as_array()).cloned())
110        .unwrap_or_default()
111}
112
113/// Read, change and write back the list in one transaction: closes, reopens
114/// and deletes run concurrently. A change counts as one to the workspace's
115/// windows, so the saver saves it. `None` when the store couldn't be written.
116fn update<R>(store: &Store, f: impl FnOnce(&mut Vec<Value>) -> R) -> Option<R> {
117    let result = store.with_tx(|tx| {
118        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else {
119            return Ok(None);
120        };
121        let mut list = client.meta.get(CLOSED_META_KEY).and_then(|v| v.as_array()).cloned().unwrap_or_default();
122        let before = list.clone();
123        let out = f(&mut list);
124        let changed = list != before;
125        if changed {
126            if list.is_empty() {
127                client.meta.remove(CLOSED_META_KEY);
128            } else {
129                client.meta.insert(CLOSED_META_KEY.to_string(), Value::Array(list));
130            }
131            tx.update(&mut client)?;
132        }
133        Ok(Some((out, changed)))
134    });
135    match result {
136        Ok(Some((out, changed))) => {
137            if changed {
138                store.layout_writes().wrote("window");
139            }
140            Some(out)
141        }
142        Ok(None) => None,
143        Err(e) => {
144            tracing::warn!(error = %e, "session_closed: couldn't update the closed windows");
145            None
146        }
147    }
148}
149
150/// The window contents a window shows now.
151pub(crate) fn open_workspaces(store: &Store) -> HashSet<String> {
152    client(store)
153        .map(|c| c.windowids)
154        .unwrap_or_default()
155        .iter()
156        .filter_map(|id| store.get::<Window>(id).ok().flatten())
157        .map(|w| w.workspaceid)
158        .collect()
159}
160
161/// How many full windows are open (a subwindow belongs to its parent's).
162fn open_window_count(store: &Store) -> usize {
163    client(store)
164        .map(|c| c.windowids)
165        .unwrap_or_default()
166        .iter()
167        .filter_map(|id| store.get::<Window>(id).ok().flatten())
168        .filter(|w| w.kind.as_deref() != Some("subwindow"))
169        .count()
170}
171
172/// Whether `ws_id` holds anything of the user's: a tab with a pane that isn't
173/// the untouched default layout.
174fn worth_keeping(store: &Store, ws_id: &str) -> bool {
175    super::session_restore::snapshot_workspace(store, ws_id)
176        .and_then(|snap| super::session_other_builds::summarize(&snap, "", "", 0))
177        .is_some()
178}
179
180/// List `ws_id` as closed at `closed_at_ms`, its window at `window`, keeping
181/// the list newest first.
182fn remember(store: &Store, ws_id: &str, window: Value, closed_at_ms: i64) {
183    let entry = json!({
184        "workspaceid": ws_id,
185        "closed_at_ms": closed_at_ms,
186        "window": window,
187    });
188    update(store, |list| {
189        list.retain(|e| workspace_of(e) != Some(ws_id));
190        list.push(entry);
191        list.sort_by_key(|e| std::cmp::Reverse(closed_at(e)));
192    });
193}
194
195/// Name the agent blocks a closed window parked, on its entry: what a reopen puts back.
196fn set_parked(store: &Store, ws_id: &str, parked: &[String]) {
197    if parked.is_empty() {
198        return;
199    }
200    update(store, |list| {
201        if let Some(entry) = list.iter_mut().find(|e| workspace_of(e) == Some(ws_id)) {
202            entry["parked"] = json!(parked);
203        }
204    });
205}
206
207/// Name the agent blocks a switch parked on the window entry for `ws_id` in the saved record of user
208/// workspace `row_id`, so that opening the workspace again reattaches them (`restore_all`). The record
209/// was saved before the close parked them; nothing else rewrites it until the workspace is open again.
210fn mark_parked_in_record(store: &Store, row_id: &str, ws_id: &str, parked: &[String]) {
211    if parked.is_empty() {
212        return;
213    }
214    let Ok(Some(row)) = store.user_workspace_get(row_id) else { return };
215    let Some(mut record) = row.record.as_deref().and_then(|r| serde_json::from_str::<Value>(r).ok()) else { return };
216    let mut marked = false;
217    let mut mark = |window: &mut Value| {
218        if workspace_of(window) == Some(ws_id) {
219            window["parked"] = json!(parked);
220            marked = true;
221        }
222    };
223    match record.get_mut("windows").and_then(|v| v.as_array_mut()) {
224        Some(windows) if !windows.is_empty() => windows.iter_mut().for_each(&mut mark),
225        _ => mark(&mut record),
226    }
227    if !marked {
228        return;
229    }
230    if let Err(e) = store.user_workspace_save_record(row_id, &record.to_string(), now_ms()) {
231        tracing::warn!(error = %e, workspace_id = %ws_id, "session_closed: couldn't note the parked agents on the left workspace's record");
232    }
233}
234
235/// The block ids a closed window's entry names as parked at its close.
236pub(crate) fn parked_of(entry: &Value) -> Vec<String> {
237    entry
238        .get("parked")
239        .and_then(|v| v.as_array())
240        .map(|ids| ids.iter().filter_map(|id| id.as_str().map(str::to_string)).collect())
241        .unwrap_or_default()
242}
243
244/// The agent blocks a closed window parked that are still parked, each with the tab it was parked
245/// from. The window's list entry counts them: parked, they are in none of its tabs.
246pub(crate) fn parked_blocks(store: &Store, ws_id: &str) -> Vec<(String, String)> {
247    use crate::persist_subscriber::parked::{PARKED_FROM_TAB_META_KEY, PARKED_META_KEY};
248    let Some(entry) = entries(store).into_iter().find(|e| workspace_of(e) == Some(ws_id)) else {
249        return Vec::new();
250    };
251    parked_of(&entry)
252        .into_iter()
253        .filter_map(|id| {
254            let block = store.get::<Block>(&id).ok().flatten()?;
255            if !crate::backend::obj::meta_get_bool(&block.meta, PARKED_META_KEY, false) {
256                return None;
257            }
258            let tab = crate::backend::obj::meta_get_string(&block.meta, PARKED_FROM_TAB_META_KEY, "");
259            (!tab.is_empty()).then_some((id, tab))
260        })
261        .collect()
262}
263
264/// `ws_id` is open again, or deleted: drop it from the list. Returns its entry.
265pub(crate) fn forget(store: &Store, ws_id: &str) -> Option<Value> {
266    update(store, |list| {
267        let at = list.iter().position(|e| workspace_of(e) == Some(ws_id))?;
268        Some(list.remove(at))
269    })
270    .flatten()
271}
272
273/// Whether a quit is closing the windows: its record is the session record,
274/// saved within the last two minutes.
275pub(crate) fn quit_under_way(store: &Store) -> bool {
276    super::session_restore::load_last_session_snapshot(store)
277        .is_some_and(|r| super::session_windows::is_recent_quit_record(&r, now_ms()))
278}
279
280/// A window onto `ws_id` closed, and no other window shows it (`window`: where
281/// it was). Stop what runs in it and keep its contents, listed as a closed
282/// window unless `unlisted`, or a quit is closing every window: then the
283/// window stays open in its workspace's record and opens again with it. A
284/// listed window's agents are not stopped but parked (`agents:always_available`),
285/// and its record names them, so a reopen puts them back.
286/// `unlisted` is the close that ends the session (it emptied
287/// `Client.windowids`) and a workspace switch's closes. Contents with nothing
288/// of the user's in them are deleted instead.
289///
290/// `left_for_switch` is the user workspace a switch is leaving: that close is unlisted, but its agents
291/// are parked like a listed window's (closing parks, Stop is the only stop), and the saved record of
292/// that workspace names them so switching back reattaches them ([`mark_parked_in_record`]). The close
293/// that ends the session still stops its agents.
294pub(crate) async fn keep_workspace(state: &AppState, ws_id: String, window: Value, unlisted: bool, left_for_switch: Option<&str>) {
295    if !worth_keeping(&state.mstore, &ws_id) {
296        super::window_close::close_workspace(state, ws_id).await;
297        return;
298    }
299    // Held until what runs in it has stopped and its agents are parked: a reopen waits for it
300    // (`TakeClosedWindow`), so it can't start them while they are stopping.
301    let guard = crate::sagas::close_pane::workspace_close_lock(&ws_id).await;
302    let listed = !unlisted && !quit_under_way(&state.mstore);
303    if listed {
304        remember(&state.mstore, &ws_id, window, now_ms());
305    }
306    let parks = listed || left_for_switch.is_some();
307    tracing::info!(
308        workspace_id = %ws_id,
309        listed,
310        "CloseWindow: keeping the window's contents (its agents {}; {})",
311        if parks { "keep running" } else { "stop" },
312        if listed { "a closed window of the workspace" } else { "it opens again with its workspace" }
313    );
314    let st = state.clone();
315    let left_for_switch = left_for_switch.map(str::to_string);
316    let done = crate::sagas::agent_teardown::detached(async move {
317        let _guard = guard;
318        let block_ids = super::window_close::store_block_ids(&st.mstore, &ws_id);
319        // A window that stays listed, or one a switch leaves, keeps its agents running (parked); only the
320        // close that ends the session stops them, for the next launch to resume.
321        let parked = if parks { crate::sagas::park_agents::park_window_agents(&st, &ws_id, &block_ids).await } else { Vec::new() };
322        set_parked(&st.mstore, &ws_id, &parked);
323        if let Some(from) = &left_for_switch {
324            mark_parked_in_record(&st.mstore, from, &ws_id, &parked);
325        }
326        let stopping = crate::sagas::park_agents::not_parked(&block_ids, &parked);
327        crate::sagas::agent_teardown::run_many(&st, &stopping, crate::sagas::agent_teardown::Policy::close()).await;
328        // Lifts each block's respawn guard; the blocks stay, so nothing is purged.
329        for block_id in &block_ids {
330            crate::sagas::close_pane::finish_close(&st, block_id).await;
331        }
332    })
333    .await;
334    if done.is_none() {
335        tracing::warn!("CloseWindow: stopping a kept window's agents panicked");
336    }
337}
338
339/// The closed windows as workspace record entries, newest first: each one's
340/// contents (`snapshot_workspace`), where its window was (`window`), its
341/// `workspaceid`, `"state": "closed"` and `closed_at_ms`. One whose contents
342/// are gone or shown by a window is left out.
343pub(crate) fn closed_entries(store: &Store) -> Vec<Value> {
344    let open = open_workspaces(store);
345    entries(store)
346        .iter()
347        .filter_map(|e| {
348            let ws = workspace_of(e)?;
349            if open.contains(ws) {
350                return None;
351            }
352            let mut entry = match super::session_restore::snapshot_workspace(store, ws) {
353                Some(snap) => snap,
354                // A window of agents only has no block in any tab once they are parked: still a closed window.
355                None if !parked_blocks(store, ws).is_empty() => json!({ "tabs": [], "active_tab_index": null }),
356                None => return None,
357            };
358            let parked = parked_of(e);
359            if !parked.is_empty() {
360                entry["parked"] = json!(parked);
361            }
362            entry["window"] = e.get("window").cloned().unwrap_or_else(|| json!({}));
363            entry["workspaceid"] = json!(ws);
364            entry["state"] = json!(STATE_CLOSED);
365            entry["closed_at_ms"] = json!(closed_at(e));
366            Some(entry)
367        })
368        .collect()
369}
370
371/// A session record (the open windows) as the workspace's record: each of its
372/// windows marked `"state": "open"`, then the closed windows
373/// ([`closed_entries`]) it doesn't already hold. A record with closed entries
374/// already comes back the same.
375pub(crate) fn with_closed(store: &Store, mut record: Value) -> Value {
376    if !record.is_object() {
377        return record;
378    }
379    let mut windows = super::session_windows::windows_of(&record);
380    for w in &mut windows {
381        if w.get("state").is_none() {
382            w["state"] = json!(STATE_OPEN);
383        }
384    }
385    let held: HashSet<String> = windows.iter().filter_map(|w| workspace_of(w).map(str::to_string)).collect();
386    windows.extend(
387        closed_entries(store)
388            .into_iter()
389            .filter(|e| !matches!(workspace_of(e), Some(ws) if held.contains(ws))),
390    );
391    record["windows"] = Value::Array(windows);
392    record
393}
394
395/// A cold start's closed windows: `record`'s `"state": "closed"` entries,
396/// kept closed. An entry whose contents are still here (its `workspaceid`, not
397/// shown by a window, not `main_ws`, not waiting to open) is listed as it is;
398/// one whose contents are gone (a new version's first start, which copied the
399/// record) is rebuilt from the entry, with new ids. No window opens for
400/// either. An entry naming contents in `skip` (an open window's in the record
401/// that was restored) is left out. Returns how many are listed.
402pub(crate) async fn restore_closed(state: &AppState, record: &Value, main_ws: &str, skip: &HashSet<String>) -> usize {
403    let store = &state.mstore;
404    let mut busy = open_workspaces(store);
405    busy.extend(super::session_windows::waiting_workspaces(store));
406    busy.insert(main_ws.to_string());
407    let mut listed = 0usize;
408    let mut rebuilt = 0usize;
409    for entry in super::session_windows::windows_of(record).iter().filter(|w| is_closed(w)) {
410        if workspace_of(entry).is_some_and(|ws| skip.contains(ws)) {
411            continue;
412        }
413        let here = match workspace_of(entry).filter(|ws| !busy.contains(*ws)) {
414            Some(ws) => {
415                let known = state.srv_state.lock().await.workspaces.contains_key(ws);
416                (known && (super::session_restore::snapshot_workspace(store, ws).is_some() || !parked_of(entry).is_empty()))
417                    .then(|| ws.to_string())
418            }
419            None => None,
420        };
421        // Contents that are still here still have their parked agents; a rebuilt window has new tabs.
422        let carried = if here.is_some() { parked_of(entry) } else { Vec::new() };
423        let ws_id = match here {
424            Some(ws) => ws,
425            None => match super::session_restore::restore_workspace(state, entry).await {
426                Ok(Some((ws, events))) => {
427                    super::reducer_helpers::publish_events(state, &events);
428                    rebuilt += 1;
429                    ws
430                }
431                Ok(None) => {
432                    tracing::warn!("session_closed: a closed window's tabs didn't come back; skipping it");
433                    continue;
434                }
435                Err(e) => {
436                    tracing::warn!(error = %e, "session_closed: a closed window didn't come back");
437                    continue;
438                }
439            },
440        };
441        busy.insert(ws_id.clone());
442        let window = entry.get("window").cloned().unwrap_or_else(|| json!({}));
443        remember(store, &ws_id, window, closed_at(entry));
444        set_parked(store, &ws_id, &carried);
445        listed += 1;
446    }
447    if listed > 0 {
448        tracing::info!(listed, rebuilt, "session_closed: kept {} closed window(s) closed ({} rebuilt)", listed, rebuilt);
449    }
450    listed
451}
452
453/// The tabs and panes a window snapshot holds.
454fn snapshot_counts(snap: &Value) -> (u32, u32) {
455    let tabs = snap.get("tabs").and_then(|v| v.as_array()).cloned().unwrap_or_default();
456    let panes = tabs.iter().map(|t| t.get("blocks").and_then(|b| b.as_array()).map_or(0, |b| b.len())).sum::<usize>();
457    (tabs.len() as u32, panes as u32)
458}
459
460/// What a closed window's parked agents add to its list entry: the tabs they alone keep, and their names.
461fn parked_summary(store: &Store, parked: &[(String, String)]) -> (u32, Vec<String>) {
462    use crate::backend::obj::{meta_get_string, Tab};
463    let mut alone = HashSet::new();
464    let mut names = Vec::new();
465    for (block_id, tab_id) in parked {
466        if store.get::<Tab>(tab_id).ok().flatten().is_some_and(|t| t.blockids.is_empty()) {
467            alone.insert(tab_id.clone());
468        }
469        if let Ok(Some(block)) = store.get::<Block>(block_id) {
470            let name = meta_get_string(&block.meta, "agentName", "");
471            let name = if name.is_empty() { meta_get_string(&block.meta, "agentId", "") } else { name };
472            if !name.is_empty() && !names.contains(&name) {
473                names.push(name);
474            }
475        }
476    }
477    (alone.len() as u32, names)
478}
479
480/// `window.ListClosedWindows`: the open workspace's closed windows, newest
481/// first, each `{workspaceid, closed_at_ms, name, tabs, panes, agents, running}`
482/// for the status bar panel (`running`: its agents that keep running, parked). One whose contents are gone or shown again is left
483/// out.
484pub(crate) fn handle_list_closed_windows(state: &AppState, _call: &WebCallType) -> WebReturnType {
485    let store = &state.mstore;
486    let open = open_workspaces(store);
487    let list: Vec<Value> = entries(store)
488        .iter()
489        .filter_map(|e| {
490            let ws_id = workspace_of(e)?;
491            if open.contains(ws_id) {
492                return None;
493            }
494            let ws = store.get::<Workspace>(ws_id).ok().flatten()?;
495            let parked = parked_blocks(store, ws_id);
496            let snap = super::session_restore::snapshot_workspace(store, ws_id);
497            if snap.is_none() && parked.is_empty() {
498                return None;
499            }
500            let summary = snap.as_ref().and_then(|s| super::session_other_builds::summarize(s, "", "", 0));
501            let (parked_tabs, mut agents) = parked_summary(store, &parked);
502            // `summarize` says nothing of a window with only its default panes; with parked agents it is
503            // not that window, so its tabs and panes are counted as they are.
504            let (tabs, panes) = match (&summary, &snap) {
505                (Some(s), _) => (s.tabs, s.panes),
506                (None, Some(snap)) if !parked.is_empty() => snapshot_counts(snap),
507                _ => (0, 0),
508            };
509            if let Some(s) = &summary {
510                agents.splice(0..0, s.agents.iter().cloned());
511            }
512            let name = e
513                .get("window")
514                .and_then(|w| w.get("name"))
515                .and_then(|v| v.as_str())
516                .map(str::to_string)
517                .unwrap_or(ws.name);
518            Some(json!({
519                "workspaceid": ws_id,
520                "closed_at_ms": closed_at(e),
521                "name": name,
522                "tabs": tabs + parked_tabs,
523                "panes": panes + parked.len() as u32,
524                "agents": agents,
525                "running": parked.len(),
526            }))
527        })
528        .collect();
529    WebReturnType::success(Value::Array(list))
530}
531
532/// `window.TakeClosedWindow(workspaceId)`: reopen a closed window. Waits for
533/// its close to finish, puts its parked agents back in their tabs and returns where it was (`{workspaceid, x,
534/// y, width, height}`) for the host to open it there; its name and appearance
535/// wait for that window (`CreateWindow`). It stays listed until that window
536/// registers, so a window that fails to open can be reopened again and is
537/// still saved (#5359). Errors when it isn't a closed window any more.
538pub(crate) async fn handle_take_closed_window(state: &AppState, call: &WebCallType) -> WebReturnType {
539    let ws_id: String = match service::get_arg(&call.args, 0) {
540        Ok(v) => v,
541        Err(e) => return WebReturnType::error(e),
542    };
543    let _stopped = crate::sagas::close_pane::workspace_close_lock(&ws_id).await;
544    let store = &state.mstore;
545    if open_workspaces(store).contains(&ws_id) {
546        forget(store, &ws_id);
547        return WebReturnType::error("that window is open");
548    }
549    let Some(entry) = entries(store).into_iter().find(|e| workspace_of(e) == Some(ws_id.as_str())) else {
550        return WebReturnType::error("that window isn't among the closed windows any more");
551    };
552    if store.get::<Workspace>(&ws_id).ok().flatten().is_none() {
553        return WebReturnType::error("that window's contents are gone");
554    }
555    // Its agents kept running without it: back into their tabs before the window shows them.
556    let back = crate::sagas::park_agents::reattach_window_agents(state, &ws_id, &parked_of(&entry)).await;
557    if back > 0 {
558        tracing::info!(workspace_id = %ws_id, agents = back, "TakeClosedWindow: the window's agents are back in its tabs");
559    }
560    let window = entry.get("window").cloned().unwrap_or_else(|| json!({}));
561    let patch = super::session_windows::patch_of(&window);
562    if !patch.is_empty() {
563        let mut metas = serde_json::Map::new();
564        metas.insert(ws_id.clone(), Value::Object(patch));
565        super::session_windows::queue_restored_windows(store, Vec::new(), metas);
566    }
567    let mut out = json!({ "workspaceid": ws_id });
568    for key in ["x", "y", "width", "height"] {
569        if let Some(v) = window.get(key) {
570            out[key] = v.clone();
571        }
572    }
573    WebReturnType::success(out)
574}
575
576/// `window.DeleteClosedWindow(workspaceId)`: remove a closed window from the
577/// workspace without reopening it. Its contents are deleted; its agents stay
578/// in My Agents.
579pub(crate) async fn handle_delete_closed_window(state: &AppState, call: &WebCallType) -> WebReturnType {
580    let ws_id: String = match service::get_arg(&call.args, 0) {
581        Ok(v) => v,
582        Err(e) => return WebReturnType::error(e),
583    };
584    // A close still stopping its agents finishes first.
585    drop(crate::sagas::close_pane::workspace_close_lock(&ws_id).await);
586    let store = &state.mstore;
587    if open_workspaces(store).contains(&ws_id) {
588        return WebReturnType::error("that window is open");
589    }
590    if forget(store, &ws_id).is_none() {
591        return WebReturnType::error("that window isn't among the closed windows any more");
592    }
593    tracing::info!(workspace_id = %ws_id, "session_closed: removing a closed window from the workspace");
594    super::window_close::close_workspace(state, ws_id).await;
595    WebReturnType::success_empty()
596}
597
598/// `window.DiscardWorkspaceOnClose(windowId)`: remove an open window from the
599/// workspace. Its close, which the window starts next, deletes its contents
600/// instead of keeping them. The only open window can't be removed.
601pub(crate) fn handle_discard_workspace_on_close(state: &AppState, call: &WebCallType) -> WebReturnType {
602    let window_id: String = match service::get_arg(&call.args, 0) {
603        Ok(v) => v,
604        Err(e) => return WebReturnType::error(e),
605    };
606    if open_window_count(&state.mstore) <= 1 {
607        return WebReturnType::error("the last window can't be removed from the workspace");
608    }
609    mark_discard(&window_id);
610    tracing::info!(window_id = %window_id, "CloseWindow: removing the window from the workspace; its close deletes its contents");
611    WebReturnType::success_empty()
612}
613
614/// `window.WindowAgents(windowId)`: the agents running in the window, each
615/// `{block_id, name, working}` (`working`: mid-turn), for the close warning
616/// and the panel's delete.
617pub(crate) fn handle_window_agents(state: &AppState, call: &WebCallType) -> WebReturnType {
618    let window_id: String = match service::get_arg(&call.args, 0) {
619        Ok(v) => v,
620        Err(e) => return WebReturnType::error(e),
621    };
622    let store = &state.mstore;
623    let Some(window) = store.get::<Window>(&window_id).ok().flatten() else {
624        return WebReturnType::success(json!([]));
625    };
626    WebReturnType::success(Value::Array(agents_in(store, &window.workspaceid)))
627}
628
629/// The agents running in window contents `ws_id`, each `{block_id, name,
630/// working}` (`working`: mid-turn).
631pub(crate) fn agents_in(store: &Store, ws_id: &str) -> Vec<Value> {
632    super::window_close::store_block_ids(store, ws_id)
633        .into_iter()
634        .filter_map(|block_id| {
635            let (name, working) = agent_of(store, &block_id)?;
636            Some(json!({ "block_id": block_id, "name": name, "working": working }))
637        })
638        .collect()
639}
640
641/// The agent running in block `block_id`: its name, and whether it is mid-turn. `None` for a block
642/// that is not an agent's, or has no controller.
643pub(crate) fn agent_of(store: &Store, block_id: &str) -> Option<(String, bool)> {
644    let status = crate::backend::blockcontroller::get_controller(block_id)?.get_runtime_status();
645    if !status.is_agent_pane {
646        return None;
647    }
648    let block = store.get::<crate::backend::obj::Block>(block_id).ok().flatten();
649    let meta_str = |key: &str| {
650        block
651            .as_ref()
652            .and_then(|b| b.meta.get(key))
653            .and_then(|v| v.as_str())
654            .filter(|s| !s.is_empty())
655            .map(str::to_string)
656    };
657    let name = meta_str("agentName").or_else(|| meta_str("agentId")).unwrap_or_else(|| block_id.to_string());
658    Some((name, status.turn_active))
659}
660
661#[cfg(test)]
662#[path = "session_closed_tests.rs"]
663mod tests;
664
665#[cfg(test)]
666#[path = "session_closed_agents_tests.rs"]
667mod agent_tests;
668
669#[cfg(test)]
670#[path = "session_slots_tests.rs"]
671mod slots_tests;