Skip to main content

agentmux_srv/server/service/
session_slots.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The window slots of the open workspace: the order its windows are listed in, open and closed alike, in
5//! the version pill's instance panel. Every window has a slot for good: closing one keeps it, reopening
6//! it returns to it, and a window that is opened for the first time takes the next one at the end. Only a
7//! window that is deleted (an open one removed from the workspace, a closed one removed from the list)
8//! gives its slot up, and the ones after it move up.
9//!
10//! The order is the client meta `workspace:window_slots`, the workspace ids in slot order. It is saved
11//! with the workspace's record (`window_slots`), so it survives a restart, an upgrade (the new version
12//! copies the record) and a switch of workspace (the record of the one opened brings its own). The panel
13//! asks [`handle_place_window_slots`] with the windows it shows; srv appends the ones it has no slot for
14//! and answers with the whole order, which every window's panel then follows.
15
16use serde_json::{json, Value};
17
18use crate::backend::obj::Client;
19use crate::backend::service::{self, WebCallType, WebReturnType};
20use crate::backend::storage::store::Store;
21use crate::server::AppState;
22
23/// The client meta key holding the order.
24pub(crate) const SLOTS_META_KEY: &str = "workspace:window_slots";
25/// Its key in a workspace's record.
26const RECORD_KEY: &str = "window_slots";
27/// Far more windows than a workspace holds; only here so a long-lived workspace can't grow the list
28/// without end. The oldest slots go first.
29const MAX_SLOTS: usize = 200;
30
31fn strings(v: Option<&Value>) -> Vec<String> {
32    v.and_then(|v| v.as_array())
33        .map(|a| a.iter().filter_map(|s| s.as_str().filter(|s| !s.is_empty()).map(str::to_string)).collect())
34        .unwrap_or_default()
35}
36
37/// The slots, in order.
38pub(crate) fn slots(store: &Store) -> Vec<String> {
39    store
40        .get_all::<Client>()
41        .ok()
42        .and_then(|cs| cs.into_iter().next())
43        .map(|c| strings(c.meta.get(SLOTS_META_KEY)))
44        .unwrap_or_default()
45}
46
47/// Change the slots in one transaction (a place and a forget can run together) and return them. A change
48/// counts as one to the workspace's windows, so the saver saves it.
49fn update(store: &Store, f: impl FnOnce(&mut Vec<String>)) -> Vec<String> {
50    let result = store.with_tx(|tx| {
51        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else {
52            return Ok((Vec::new(), false));
53        };
54        let before = strings(client.meta.get(SLOTS_META_KEY));
55        let mut list = before.clone();
56        f(&mut list);
57        let changed = list != before;
58        if changed {
59            if list.is_empty() {
60                client.meta.remove(SLOTS_META_KEY);
61            } else {
62                client.meta.insert(SLOTS_META_KEY.to_string(), json!(list));
63            }
64            tx.update(&mut client)?;
65        }
66        Ok((list, changed))
67    });
68    match result {
69        Ok((list, changed)) => {
70            if changed {
71                store.layout_writes().wrote("window");
72            }
73            list
74        }
75        Err(e) => {
76            tracing::warn!(error = %e, "session_slots: couldn't update the window slots");
77            slots(store)
78        }
79    }
80}
81
82/// Give each of `keys` that has no slot the next one at the end, in the order given, and return every slot.
83pub(crate) fn place(store: &Store, keys: &[String]) -> Vec<String> {
84    update(store, |list| {
85        for key in keys.iter().filter(|k| !k.is_empty()) {
86            if !list.contains(key) {
87                list.push(key.clone());
88            }
89        }
90        if list.len() > MAX_SLOTS {
91            let over = list.len() - MAX_SLOTS;
92            list.drain(..over);
93        }
94    })
95}
96
97/// A window's contents were deleted: its slot goes and the ones after it move up.
98pub(crate) fn forget(store: &Store, ws_id: &str) {
99    if slots(store).iter().any(|k| k == ws_id) {
100        update(store, |list| list.retain(|k| k != ws_id));
101    }
102}
103
104/// A window's contents were rebuilt under a new id: it keeps its slot.
105pub(crate) fn renamed(store: &Store, old: &str, new: &str) {
106    if old == new || !slots(store).iter().any(|k| k == old) {
107        return;
108    }
109    update(store, |list| {
110        if list.iter().any(|k| k == new) {
111            list.retain(|k| k != old);
112        } else if let Some(at) = list.iter().position(|k| k == old) {
113            list[at] = new.to_string();
114        }
115    });
116}
117
118/// Add the order to a workspace's record, so it is saved with it.
119pub(crate) fn into_record(store: &Store, record: &mut Value) {
120    let list = slots(store);
121    if list.is_empty() {
122        return;
123    }
124    if let Some(obj) = record.as_object_mut() {
125        obj.insert(RECORD_KEY.to_string(), json!(list));
126    }
127}
128
129/// A record was loaded (a start, a new version's first start, a switch of workspace): its order is the
130/// open workspace's. A record without one (an older version's) leaves the order as it is.
131pub(crate) fn adopt(store: &Store, record: &Value) {
132    let Some(saved) = record.get(RECORD_KEY).filter(|v| v.is_array()) else { return };
133    let saved = strings(Some(saved));
134    update(store, |list| *list = saved);
135}
136
137/// `window.PlaceWindowSlots(keys)`: the panel shows the windows `keys` (their workspace ids); the ones
138/// with no slot take the next ones. Answers with the whole order.
139pub(crate) fn handle_place_window_slots(state: &AppState, call: &WebCallType) -> WebReturnType {
140    let keys: Vec<String> = match service::get_arg(&call.args, 0) {
141        Ok(v) => v,
142        Err(e) => return WebReturnType::error(e),
143    };
144    WebReturnType::success(json!(place(&state.mstore, &keys)))
145}