Skip to main content

agentmux_srv/server/service/
user_workspace_switch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Several workspaces, one open at a time (docs/specs/SPEC_WORKSPACES_2026_10_23.md
5//! §3.2, §6): list them, make a new one, switch, delete one. Not the srv
6//! `Workspace` object, which is one window's contents.
7//!
8//! **Switching** (`workspace.SwitchUserWorkspace`, and the switch that ends
9//! `CreateUserWorkspace` and Import…), all in srv:
10//! 1. the open workspace is saved, then saves wait (`LayoutWrites::hold_saves`)
11//!    until the windows have moved, so no save stores a mix of the two;
12//! 2. its windows other than the one the user acted from close here: their
13//!    rows go, their contents stay, and their windows stay `open` in its
14//!    record. The host closes the OS windows afterwards (the reply names them);
15//! 3. the other workspace becomes the open one (`workspace:current`,
16//!    `workspace:name`, its `opened_at`), and the closed windows, the restored
17//!    windows waiting to open and the session record of the one before are
18//!    forgotten: its record holds them;
19//! 4. its record is restored as a cold start restores one
20//!    (`session_windows::restore_all`): contents still here are reused, those
21//!    that are gone are rebuilt from the record, its closed windows are listed
22//!    closed. A record with nothing to restore (a new workspace) gets the
23//!    default panes;
24//! 5. the window the user acted from shows the first window's contents, with
25//!    its name and appearance; the rest wait for that window to open them
26//!    (`TakeRestoredWindows`);
27//! 6. the contents the closed workspace showed have their shells stopped and
28//!    their agents parked (they keep running, `agents:always_available`; the
29//!    saved record names them, and switching back puts them in their tabs),
30//!    after the reply, one switch at a time. The next switch waits for that.
31//!
32//! The next launch opens the workspace that was open last: it is the one the
33//! client names.
34
35use std::sync::{Arc, LazyLock};
36
37use agentmux_common::ipc::{Command, Event};
38use agentmux_common::time::now_ms;
39use serde_json::{json, Value};
40
41use crate::backend::obj::{mux_obj_to_value, Client, MuxObjUpdate, Window};
42use crate::backend::service::{self, WebCallType, WebReturnType};
43use crate::backend::storage::store::Store;
44use crate::backend::storage::user_workspaces::UserWorkspaceRow;
45use crate::server::AppState;
46
47use super::reducer_helpers::{dispatch_to_reducer, publish_events};
48use super::user_workspace::{clean_name, current_id, Saved, CURRENT_META_KEY, NAME_META_KEY};
49
50/// One switch at a time, held until the closed workspace's agents have
51/// stopped: the next switch may reopen those contents.
52static SWITCH_LOCK: LazyLock<Arc<tokio::sync::Mutex<()>>> = LazyLock::new(Default::default);
53
54/// Wait until no switch is running, its agents' stop included.
55#[cfg(test)]
56pub(crate) async fn wait_for_switch() {
57    drop(SWITCH_LOCK.lock().await);
58}
59
60/// Holds saves for as long as it lives.
61struct SavesHeld<'a>(&'a Store);
62
63impl<'a> SavesHeld<'a> {
64    fn new(store: &'a Store) -> Self {
65        store.layout_writes().hold_saves(true);
66        SavesHeld(store)
67    }
68}
69
70impl Drop for SavesHeld<'_> {
71    fn drop(&mut self) {
72        self.0.layout_writes().hold_saves(false);
73    }
74}
75
76/// What a switch did, for the window that asked.
77#[derive(Debug, Clone)]
78pub(crate) struct Switched {
79    pub id: String,
80    pub name: String,
81    /// The windows that closed (`window_id`, host label), for the host to close.
82    pub closed: Vec<(String, String)>,
83    /// How many windows wait to open beside the one that asked.
84    pub beside: usize,
85}
86
87impl Switched {
88    pub(crate) fn to_json(&self) -> Value {
89        json!({
90            "id": self.id,
91            "name": self.name,
92            "closed": self.closed.iter().map(|(w, l)| json!({ "window_id": w, "label": l })).collect::<Vec<_>>(),
93            "beside": self.beside,
94        })
95    }
96}
97
98fn client(store: &Store) -> Option<Client> {
99    store.get_all::<Client>().ok()?.into_iter().next()
100}
101
102/// The client, whose meta names the open workspace, as an object update.
103pub(crate) fn client_update(store: &Store) -> Vec<MuxObjUpdate> {
104    client(store)
105        .map(|c| {
106            vec![MuxObjUpdate {
107                updatetype: "update".into(),
108                otype: "client".into(),
109                oid: c.oid.clone(),
110                obj: Some(mux_obj_to_value(&c)),
111            }]
112        })
113        .unwrap_or_default()
114}
115
116/// Apply `events` to the store and publish them; the first error the reducer
117/// returned, if any, instead.
118async fn apply(state: &AppState, events: &[Event]) -> Result<(), String> {
119    if let Some(err) = events.iter().find_map(|e| match e {
120        Event::Error { message, .. } => Some(message.clone()),
121        _ => None,
122    }) {
123        return Err(err);
124    }
125    for ev in events {
126        crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).map_err(|e| e.to_string())?;
127    }
128    publish_events(state, events);
129    Ok(())
130}
131
132/// Make `row` the open workspace: the client names it, and forgets what
133/// belonged to the one before (its closed windows, its restored windows
134/// waiting to open, the session record), which that one's record holds.
135fn set_current(store: &Store, row: &UserWorkspaceRow) -> Result<(), String> {
136    store
137        .with_tx(|tx| {
138            let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(()) };
139            client.meta.insert(CURRENT_META_KEY.to_string(), json!(row.id));
140            client.meta.insert(NAME_META_KEY.to_string(), json!(row.name));
141            client.meta.remove(super::session_closed::CLOSED_META_KEY);
142            client.meta.remove(super::session_slots::SLOTS_META_KEY);
143            super::session_windows::forget_restore_lists(&mut client.meta);
144            tx.update(&mut client)?;
145            Ok(())
146        })
147        .map_err(|e| e.to_string())?;
148    super::session_restore::clear_last_session_snapshot(store);
149    let _ = store.user_workspace_mark_opened(&row.id, now_ms());
150    Ok(())
151}
152
153/// The meta patch that makes a window the one a record entry describes: its
154/// name, theme and opacity, and none of the window's own where the entry has
155/// none.
156fn window_patch(waiting: serde_json::Map<String, Value>) -> Value {
157    let mut patch = serde_json::Map::new();
158    for key in std::iter::once("window:displayname").chain(super::window_inherit::INHERITED_KEYS.iter().copied()) {
159        patch.insert(key.to_string(), waiting.get(key).cloned().unwrap_or(Value::Null));
160    }
161    Value::Object(patch)
162}
163
164/// Switch to workspace `target_id`, reusing window `window_id` for its first
165/// window. See the module doc for the steps.
166pub(crate) async fn switch_to(state: &AppState, target_id: &str, window_id: &str) -> Result<Switched, String> {
167    let guard = SWITCH_LOCK.clone().lock_owned().await;
168    let store = &state.mstore;
169    let target = store
170        .user_workspace_get(target_id)
171        .map_err(|e| e.to_string())?
172        .ok_or_else(|| "that workspace doesn't exist any more".to_string())?;
173    if current_id(store).as_deref() == Some(target_id) {
174        return Err(format!("{} is open already", target.name));
175    }
176    let acting = store
177        .get::<Window>(window_id)
178        .map_err(|e| e.to_string())?
179        .filter(|w| client(store).is_some_and(|c| c.windowids.contains(&w.oid)))
180        .ok_or_else(|| "the window that asked isn't open".to_string())?;
181
182    // 1. Save the open workspace as it is now.
183    let saving = Arc::clone(store);
184    let saved = tokio::task::spawn_blocking(move || super::user_workspace::save_now(&saving))
185        .await
186        .map_err(|e| e.to_string())?;
187    match saved {
188        Saved::Written | Saved::Unchanged | Saved::NoWindow | Saved::NoWorkspace => {}
189        Saved::HeldForQuit => return Err("AgentMux is quitting".to_string()),
190        Saved::HeldForSwitch | Saved::Failed => return Err("the open workspace couldn't be saved".to_string()),
191    }
192    let held = SavesHeld::new(store);
193    let left = current_id(store);
194    let others: Vec<Window> =
195        super::session_windows::live_windows(store).into_iter().map(|(w, _)| w).filter(|w| w.oid != acting.oid).collect();
196
197    // 2. The other workspace is the open one, and the window that asked shows
198    // it. Until this has worked nothing else changes: a failure puts the
199    // client back as it was, so the open workspace stays the open one and its
200    // windows stay open (#5360).
201    let before = client_meta_of(store, &SWITCH_META_KEYS);
202    let main_ws = match open_target(state, &target, &acting).await {
203        Ok(ws) => ws,
204        Err(e) => {
205            restore_client_meta(store, before);
206            tracing::warn!(workspace = %target.id, error = %e, "user_workspace: the switch failed; the open workspace stays open");
207            return Err(e);
208        }
209    };
210    let mut leaving: Vec<String> = Vec::new();
211    if acting.workspaceid != main_ws {
212        leaving.push(acting.workspaceid.clone());
213    }
214
215    // 3. The other windows close; their contents stay.
216    let mut closed = Vec::new();
217    for w in others {
218        let label = w.meta.get("host:label").and_then(|v| v.as_str()).unwrap_or_default().to_string();
219        match super::window_close::detach_window(state, &w.oid).await {
220            Ok(Some(ws)) => leaving.push(ws),
221            Ok(None) => {}
222            Err(e) => tracing::warn!(window = %w.oid, error = %e, "user_workspace: a window of the closed workspace didn't detach"),
223        }
224        closed.push((w.oid.clone(), label));
225    }
226
227    drop(held);
228    let saving = Arc::clone(store);
229    let _ = tokio::task::spawn_blocking(move || super::user_workspace::save_now(&saving)).await;
230
231    // 4. The closed workspace's agents and shells stop, after the reply.
232    let st = state.clone();
233    tokio::spawn(async move {
234        for ws in leaving {
235            super::session_closed::keep_workspace(&st, ws, json!({}), true, left.as_deref()).await;
236        }
237        drop(guard);
238    });
239
240    let beside = super::session_windows::waiting_workspaces(store).len();
241    tracing::info!(workspace = %target.id, name = %target.name, closed = closed.len(), beside, "user_workspace: switched");
242    Ok(Switched { id: target.id, name: target.name, closed, beside })
243}
244
245/// A workspace by this name fails to open after it became the open one.
246#[cfg(test)]
247pub(crate) const FAIL_OPEN_NAME: &str = "fail-open (test)";
248
249/// The client meta keys a switch changes: the open workspace, its closed
250/// windows, the restored windows' queues and the quit's session record.
251const SWITCH_META_KEYS: [&str; 8] = [
252    CURRENT_META_KEY,
253    NAME_META_KEY,
254    super::session_closed::CLOSED_META_KEY,
255    super::session_slots::SLOTS_META_KEY,
256    super::session_windows::RESTORE_LIST_KEYS[0],
257    super::session_windows::RESTORE_LIST_KEYS[1],
258    super::session_windows::RESTORE_LIST_KEYS[2],
259    super::session_restore::SNAPSHOT_META_KEY,
260];
261
262fn client_meta_of(store: &Store, keys: &[&str]) -> Vec<(String, Option<Value>)> {
263    let meta = client(store).map(|c| c.meta).unwrap_or_default();
264    keys.iter().map(|k| (k.to_string(), meta.get(*k).cloned())).collect()
265}
266
267/// Put `saved` (from [`client_meta_of`]) back, in one transaction.
268fn restore_client_meta(store: &Store, saved: Vec<(String, Option<Value>)>) {
269    let result = store.with_tx(|tx| {
270        let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else { return Ok(()) };
271        for (key, value) in saved {
272            match value {
273                Some(v) => client.meta.insert(key, v),
274                None => client.meta.remove(&key),
275            };
276        }
277        tx.update(&mut client)?;
278        Ok(())
279    });
280    if let Err(e) = result {
281        tracing::warn!(error = %e, "user_workspace: couldn't put the open workspace back after a failed switch");
282    }
283}
284
285/// Make `target` the open workspace and show its first window in `acting`;
286/// returns that window's contents.
287async fn open_target(state: &AppState, target: &UserWorkspaceRow, acting: &Window) -> Result<String, String> {
288    let store = &state.mstore;
289    set_current(store, target)?;
290    #[cfg(test)]
291    if target.name == FAIL_OPEN_NAME {
292        return Err("a test failed this switch".into());
293    }
294
295    // Its windows come back, or the default panes for a new one.
296    let mut opened = None;
297    for (from, record) in super::user_workspace::launch_candidates(None, Some(&target)) {
298        super::session_slots::adopt(store, &record);
299        match super::session_windows::restore_all(state, &record).await {
300            Ok(Some(main)) => {
301                opened = Some((main, record, from));
302                break;
303            }
304            Ok(None) => tracing::warn!(copy = ?from, "user_workspace: nothing came back from a saved copy"),
305            Err(e) => tracing::warn!(copy = ?from, error = %e, "user_workspace: a saved copy didn't restore"),
306        }
307    }
308    let main_ws = match opened {
309        Some(((main_ws, events), record, from)) => {
310            publish_events(state, &events);
311            super::user_workspace::after_clean_load(store, &record, from);
312            main_ws
313        }
314        None => {
315            let (ws, events) = super::window_create::create_default_contents(state, None, None, false).await?;
316            publish_events(state, &events);
317            ws
318        }
319    };
320
321    // The window that asked shows its first window.
322    apply(state, &dispatch_to_reducer(state, Command::SwitchWorkspace { window_id: acting.oid.clone(), workspace_id: main_ws.clone() }).await)
323        .await?;
324    let patch = window_patch(super::session_windows::restored_window_meta(store, &main_ws));
325    match apply(state, &dispatch_to_reducer(state, Command::UpdateWindowMeta { window_id: acting.oid.clone(), meta_patch: patch }).await).await {
326        Ok(()) => {
327            super::session_windows::forget_restored_window_meta(store, &main_ws);
328        }
329        Err(e) => tracing::warn!(error = %e, "user_workspace: the window's name and appearance didn't follow the switch"),
330    }
331    super::session_windows::restored_window_opened(store, &main_ws);
332    super::session_closed::forget(store, &main_ws);
333    // The window that asked has no `CreateWindow` of its own here: it takes its slot now.
334    super::session_slots::place(store, std::slice::from_ref(&main_ws));
335    Ok(main_ws)
336}
337
338// ---- Service handlers ----
339
340fn arg_str(call: &WebCallType, i: usize) -> String {
341    service::get_arg::<String>(&call.args, i).unwrap_or_default()
342}
343
344fn reply(state: &AppState, result: Result<Switched, String>) -> WebReturnType {
345    match result {
346        Ok(switched) => WebReturnType::success_data_updates(switched.to_json(), client_update(&state.mstore)),
347        Err(e) => WebReturnType::error(e),
348    }
349}
350
351/// The windows a record holds, open and closed.
352fn window_counts(record: Option<&str>) -> (usize, usize) {
353    let Some(record) = record.and_then(|r| serde_json::from_str::<Value>(r).ok()) else { return (0, 0) };
354    let windows = super::session_windows::windows_of(&record);
355    let windows: Vec<&Value> = windows.iter().filter(|w| w.get("tabs").and_then(|t| t.as_array()).is_some_and(|t| !t.is_empty())).collect();
356    let closed = windows.iter().filter(|w| super::session_closed::is_closed(w)).count();
357    (windows.len() - closed, closed)
358}
359
360/// `workspace.ListUserWorkspaces`: every workspace, the most recently opened
361/// first, each `{id, name, current, opened_at, windows, closed}` (its open
362/// and closed windows, as last saved).
363pub(crate) fn handle_list(state: &AppState, _call: &WebCallType) -> WebReturnType {
364    let store = &state.mstore;
365    let current = current_id(store);
366    match store.user_workspace_list() {
367        Ok(rows) => WebReturnType::success(Value::Array(
368            rows.iter()
369                .map(|w| {
370                    let (windows, closed) = window_counts(w.record.as_deref());
371                    json!({
372                        "id": w.id,
373                        "name": w.name,
374                        "current": current.as_deref() == Some(w.id.as_str()),
375                        "opened_at": w.opened_at,
376                        "windows": windows,
377                        "closed": closed,
378                    })
379                })
380                .collect(),
381        )),
382        Err(e) => WebReturnType::error(e.to_string()),
383    }
384}
385
386/// `workspace.SwitchUserWorkspace(workspaceId, windowId)`: switch to another
387/// workspace from window `windowId`. Returns `{id, name, closed: [{window_id,
388/// label}], beside}`: the windows for the host to close, and how many wait to
389/// open beside this one (`TakeRestoredWindows`).
390pub(crate) async fn handle_switch(state: &AppState, call: &WebCallType) -> WebReturnType {
391    reply(state, switch_to(state, &arg_str(call, 0), &arg_str(call, 1)).await)
392}
393
394/// A new, empty workspace named `name`.
395pub(crate) fn insert_workspace(store: &Store, name: &str) -> Result<UserWorkspaceRow, String> {
396    let name = clean_name(name).ok_or_else(|| "a workspace needs a name".to_string())?;
397    let now = now_ms();
398    let row = UserWorkspaceRow {
399        id: uuid::Uuid::new_v4().to_string(),
400        name,
401        created_at: now,
402        updated_at: now,
403        ..Default::default()
404    };
405    store.user_workspace_insert(&row).map_err(|e| e.to_string())?;
406    Ok(row)
407}
408
409/// `workspace.CreateUserWorkspace(name, windowId)`: a new workspace, switched
410/// to at once; its first window shows the default panes. The same reply as
411/// `SwitchUserWorkspace`. A switch that fails leaves no workspace behind.
412pub(crate) async fn handle_create(state: &AppState, call: &WebCallType) -> WebReturnType {
413    let store = &state.mstore;
414    let row = match insert_workspace(store, &arg_str(call, 0)) {
415        Ok(row) => row,
416        Err(e) => return WebReturnType::error(e),
417    };
418    let result = switch_to(state, &row.id, &arg_str(call, 1)).await;
419    if result.is_err() {
420        let _ = store.user_workspace_delete(&row.id);
421    }
422    reply(state, result)
423}
424
425/// The window contents workspace `row` keeps (its record's), less any that a
426/// window shows, that the open workspace lists as closed, or that wait to open.
427fn kept_contents(store: &Store, row: &UserWorkspaceRow) -> Vec<String> {
428    let mut busy = super::session_closed::open_workspaces(store);
429    busy.extend(super::session_windows::waiting_workspaces(store));
430    busy.extend(
431        super::session_closed::closed_entries(store)
432            .iter()
433            .filter_map(|e| e.get("workspaceid").and_then(|v| v.as_str()).map(str::to_string)),
434    );
435    let mut out = Vec::new();
436    for text in [row.record.as_deref(), row.previous.as_deref()].into_iter().flatten() {
437        let Ok(record) = serde_json::from_str::<Value>(text) else { continue };
438        for w in super::session_windows::windows_of(&record) {
439            if let Some(ws) = w.get("workspaceid").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
440                if !busy.contains(ws) && !out.iter().any(|o| o == ws) {
441                    out.push(ws.to_string());
442                }
443            }
444        }
445    }
446    out
447}
448
449/// `workspace.DeleteUserWorkspace(workspaceId)`: delete a workspace that
450/// isn't open: its row, and the contents of its windows still kept here. Its
451/// agents stay in My Agents.
452pub(crate) async fn handle_delete(state: &AppState, call: &WebCallType) -> WebReturnType {
453    let store = &state.mstore;
454    let id = arg_str(call, 0);
455    if current_id(store).as_deref() == Some(id.as_str()) {
456        return WebReturnType::error("the open workspace can't be deleted; open another one first");
457    }
458    let row = match store.user_workspace_get(&id) {
459        Ok(Some(row)) => row,
460        Ok(None) => return WebReturnType::error("that workspace doesn't exist any more"),
461        Err(e) => return WebReturnType::error(e.to_string()),
462    };
463    // Its contents may still be stopping after the switch away from it.
464    let _switching = SWITCH_LOCK.lock().await;
465    let contents = kept_contents(store, &row);
466    if let Err(e) = store.user_workspace_delete(&id) {
467        return WebReturnType::error(e.to_string());
468    }
469    for ws in &contents {
470        if store.get::<crate::backend::obj::Workspace>(ws).ok().flatten().is_some() {
471            super::window_close::close_workspace(state, ws.clone()).await;
472        }
473    }
474    tracing::info!(workspace = %id, name = %row.name, contents = contents.len(), "user_workspace: deleted");
475    WebReturnType::success_empty()
476}
477
478/// `workspace.UserWorkspaceAgents()`: the agents running in the open
479/// workspace's windows, each `{block_id, name, working}`, for the warning
480/// before a switch closes it.
481pub(crate) fn handle_agents(state: &AppState, _call: &WebCallType) -> WebReturnType {
482    let store = &state.mstore;
483    let agents: Vec<Value> = super::session_windows::live_windows(store)
484        .iter()
485        .flat_map(|(_, ws)| super::session_closed::agents_in(store, ws))
486        .collect();
487    WebReturnType::success(Value::Array(agents))
488}
489
490#[cfg(test)]
491#[path = "user_workspace_switch_tests.rs"]
492pub(crate) mod tests;