Skip to main content

agentmux_srv/server/service/
user_workspace_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A workspace as a file (docs/specs/SPEC_WORKSPACES_2026_10_23.md §3.2, §4.2):
5//! ☰ → Workspaces → Export… and Import….
6//!
7//! - **Export** writes the open workspace, every window of it with its name and
8//!   whether it is closed, as an `agentmux.layout` document with
9//!   `scope: "workspace"` (`layout_file::export_workspace`) to a
10//!   `*.agentmux-workspace.json` file the host's Save dialog picked. The same
11//!   per-view allowlist as a layout file: no session ids, and the
12//!   machine-local `resume` references only when asked for.
13//! - **Import** reads an exported workspace, or an older
14//!   `*.agentmux-layout.json`, as a new workspace and switches to it. It is
15//!   opened as a template, as Open layout… opened a layout: every pane is new,
16//!   each agent pane starts its agent afresh, and a terminal's command runs
17//!   only for a trusted file or when the user said so in the preview. The new
18//!   workspace's record holds the windows to build; the switch builds them
19//!   (`session_windows::restore_all`, as for a record whose contents are gone).
20
21use std::path::{Path, PathBuf};
22
23use agentmux_common::time::now_ms;
24use serde_json::{json, Value};
25
26use crate::backend::layout_file::{self, LayoutDoc, PlanOptions, WorkspacePlan, WorkspaceWindow};
27use crate::backend::obj::{self, Block, Tab, Workspace};
28use crate::backend::service::{self, WebCallType, WebReturnType};
29use crate::backend::storage::store::Store;
30use crate::server::app_api::agent_io::agent_panes_of;
31use crate::backend::rpc_types::{CommandWorkspaceImportUserWorkspaceData, WorkspaceClosedWindow, WorkspaceImportUserWorkspaceResult};
32use crate::server::AppState;
33
34use super::user_workspace::current_id;
35use super::user_workspace_switch::{insert_workspace, switch_to, Switched};
36
37/// What decides whether a file is trusted (layout files spec §3.5): saved by
38/// this install, in one of its own folders. Injected for tests.
39pub(crate) struct ImportTrust {
40    pub own_instance: Option<String>,
41    pub dirs: Vec<PathBuf>,
42    pub home: Option<PathBuf>,
43}
44
45impl ImportTrust {
46    pub(crate) fn live() -> Self {
47        let shared = crate::registry::shared_guard::shared_dir();
48        ImportTrust {
49            own_instance: crate::backend::storage::wan_identity::global()
50                .and_then(|w| w.instance_ensure(&crate::backend::reactive::registry::local_host_label()).ok())
51                .map(|i| i.instance_id),
52            dirs: shared.map(|s| vec![s.join("workspaces"), s.join("layouts")]).unwrap_or_default(),
53            home: dirs::home_dir(),
54        }
55    }
56
57    fn trusts(&self, doc: &LayoutDoc, path: &Path) -> bool {
58        self.dirs.iter().any(|d| layout_file::is_trusted(doc, path, self.own_instance.as_deref(), Some(d)))
59    }
60}
61
62/// Read a file Import… accepts: an exported workspace or a layout file.
63fn read_doc(path: &str) -> Result<(LayoutDoc, PathBuf), String> {
64    let path = PathBuf::from(path);
65    if !layout_file::is_workspace_path(&path) && !layout_file::is_layout_path(&path) {
66        return Err(format!(
67            "the path must be absolute and end in {} or {}",
68            layout_file::WORKSPACE_EXTENSION,
69            layout_file::LAYOUT_EXTENSION
70        ));
71    }
72    let doc = layout_file::read_layout_file(&path)?;
73    Ok((doc, path))
74}
75
76/// The name an imported workspace gets: the file's, else its file name.
77fn import_name(doc: &LayoutDoc, path: &Path) -> String {
78    let named = doc.name.trim();
79    if !named.is_empty() {
80        return named.to_string();
81    }
82    let file = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
83    let lower = file.to_ascii_lowercase();
84    let stem = [layout_file::WORKSPACE_EXTENSION, layout_file::LAYOUT_EXTENSION]
85        .iter()
86        .find(|ext| lower.ends_with(*ext))
87        .map_or(file, |ext| &file[..file.len() - ext.len()])
88        .trim();
89    if stem.is_empty() { "Imported workspace".to_string() } else { stem.to_string() }
90}
91
92/// `name`, or `name 2`, `name 3`, … when a workspace has it already.
93pub(crate) fn unique_name(store: &Store, name: &str) -> String {
94    let taken: Vec<String> =
95        store.user_workspace_list().unwrap_or_default().into_iter().map(|w| w.name.to_lowercase()).collect();
96    if !taken.contains(&name.to_lowercase()) {
97        return name.to_string();
98    }
99    (2..).map(|n| format!("{name} {n}")).find(|c| !taken.contains(&c.to_lowercase())).unwrap_or_default()
100}
101
102fn plan_of(store: &Store, doc: &LayoutDoc, trust: &ImportTrust, run_commands: bool) -> WorkspacePlan {
103    layout_file::plan_workspace(store, doc, &PlanOptions { home: trust.home.clone(), run_commands })
104}
105
106/// What Import… shows before it opens a file: `{name, trusted, windows,
107/// closed, tabs: [{name, panes}], commands, notes}`, the shape of a layout
108/// preview plus the windows.
109pub(crate) fn preview(store: &Store, path: &str, trust: &ImportTrust) -> Result<Value, String> {
110    let (doc, path) = read_doc(path)?;
111    let trusted = trust.trusts(&doc, &path);
112    let plan = plan_of(store, &doc, trust, trusted);
113    let tabs: Vec<Value> = plan
114        .windows
115        .iter()
116        .flat_map(|w| w.tabs.iter())
117        .map(|t| json!({ "name": t.name, "panes": t.summary }))
118        .collect();
119    Ok(json!({
120        "name": import_name(&doc, &path),
121        "trusted": trusted,
122        "windows": plan.windows.len(),
123        "closed": plan.windows.iter().filter(|w| w.closed).count(),
124        "tabs": tabs,
125        "commands": plan.commands,
126        "notes": plan.notes,
127    }))
128}
129
130/// The record a new workspace starts with: one entry per planned window, in
131/// the session record's shape without contents ids, so the switch builds each
132/// one (`session_restore::restore_workspace`). A plan with no open window
133/// opens its first.
134pub(crate) fn import_record(plan: &WorkspacePlan) -> Option<Value> {
135    let any_open = plan.windows.iter().any(|w| !w.closed);
136    let now = now_ms();
137    let entries: Vec<Value> = plan
138        .windows
139        .iter()
140        .enumerate()
141        .map(|(i, w)| {
142            let tabs: Vec<Value> = w
143                .tabs
144                .iter()
145                .map(|t| {
146                    json!({
147                        "name": t.name,
148                        "blocks": t.blocks.iter().map(|m| json!({ "meta": m })).collect::<Vec<_>>(),
149                        "rootnode": t.rootnode.as_ref().and_then(|n| serde_json::to_value(n).ok()),
150                        "focusednodeid": t.focused,
151                        "magnifiednodeid": t.magnified,
152                    })
153                })
154                .collect();
155            let closed = w.closed && (any_open || i > 0);
156            let mut entry = json!({
157                "tabs": tabs,
158                "state": if closed { layout_file::WINDOW_CLOSED } else { layout_file::WINDOW_OPEN },
159                "window": w.name.as_ref().map_or_else(|| json!({}), |n| json!({ "name": n })),
160            });
161            if let Some(active) = w.active_tab {
162                entry["active_tab_index"] = json!(active);
163            }
164            if closed {
165                entry["closed_at_ms"] = json!(now);
166            }
167            entry
168        })
169        .collect();
170    let first = entries.first()?.clone();
171    Some(json!({ "tabs": first["tabs"], "windows": entries, "saved_at_ms": now }))
172}
173
174/// The agent panes a layout's plan made in contents `ws_id`, waiting for their
175/// agent: `(tab, block, agent definition)`.
176fn agent_placeholders(store: &Store, ws_id: &str) -> Vec<(String, String, String)> {
177    let Some(ws) = store.get::<Workspace>(ws_id).ok().flatten() else { return Vec::new() };
178    ws.pinnedtabids
179        .iter()
180        .chain(ws.tabids.iter())
181        .filter_map(|t| store.get::<Tab>(t).ok().flatten())
182        .flat_map(|tab| {
183            tab.blockids
184                .iter()
185                .filter_map(|b| store.get::<Block>(b).ok().flatten())
186                .filter_map(|b| {
187                    let def = obj::meta_get_string(&b.meta, layout_file::META_LAYOUT_AGENT, "");
188                    (!def.is_empty()).then(|| (tab.oid.clone(), b.oid.clone(), def))
189                })
190                .collect::<Vec<_>>()
191        })
192        .collect()
193}
194
195/// Start each agent the shown windows' panes wait for (the window that asked,
196/// and those waiting to open beside it). Returns a note per agent that didn't.
197async fn start_agents(state: &AppState) -> Vec<String> {
198    let store = &state.mstore;
199    let mut shown = super::session_closed::open_workspaces(store);
200    shown.extend(super::session_windows::waiting_workspaces(store));
201    // The tabs the import is showing. A pane in a workspace that was closed
202    // (the one this import replaced) is saved contents, not a second pane: it
203    // only comes back by opening that workspace.
204    let shown_tabs: std::collections::HashSet<String> = shown
205        .iter()
206        .filter_map(|ws| store.get::<Workspace>(ws).ok().flatten())
207        .flat_map(|ws| ws.pinnedtabids.into_iter().chain(ws.tabids))
208        .collect();
209    let mut notes = Vec::new();
210    for ws in shown {
211        for (tab, block, def) in agent_placeholders(store, &ws) {
212            let name = || {
213                let in_pane = store.get::<Block>(&block).ok().flatten().map(|b| obj::meta_get_string(&b.meta, "agentName", "")).unwrap_or_default();
214                crate::server::app_api::agent_open::agent_label(store, &in_pane, &definition_id(store, &def))
215            };
216            // One pane per agent: an agent that already has a pane in the
217            // windows being shown (any tab, running or not), such as the same
218            // agent in two windows of the file, is not opened again here.
219            let open_elsewhere: Vec<_> = agent_panes_of(store, &definition_id(store, &def))
220                .into_iter()
221                .filter(|pane| pane.block_id != block && shown_tabs.contains(&pane.tab_id))
222                .collect();
223            if let Some(pane) = open_elsewhere.first() {
224                notes.push(format!(
225                    "An agent ({}) already has a pane, in \"{}\", so its pane here shows the agent picker.",
226                    name(),
227                    pane.tab_name
228                ));
229                continue;
230            }
231            if let Err(e) = crate::server::app_api::agent_open::open_agent_into_block(state, &def, &tab, &block).await {
232                notes.push(crate::server::app_api::agent_open::not_started_note(&name(), &e));
233            }
234        }
235    }
236    notes
237}
238
239/// The id of the agent definition a layout names (its id, or a user agent's
240/// name as `agent.open` reads it); what it names, as written, when none matches.
241fn definition_id(store: &Store, wanted: &str) -> String {
242    let agents = store.agent_def_list().unwrap_or_default();
243    let mut users = agents.iter().filter(|a| a.is_seeded == 0);
244    users
245        .clone()
246        .find(|a| a.id == wanted)
247        .or_else(|| users.find(|a| a.name.eq_ignore_ascii_case(wanted)))
248        .map_or_else(|| wanted.to_string(), |a| a.id.clone())
249}
250
251/// Import the file at `path` as a new workspace and switch to it from window
252/// `window_id`. `run_commands` `None` means "as trusted". Returns the switch
253/// and what the user should know.
254pub(crate) async fn import(
255    state: &AppState,
256    path: &str,
257    run_commands: Option<bool>,
258    window_id: &str,
259    trust: &ImportTrust,
260) -> Result<(Switched, Vec<String>), String> {
261    let store = &state.mstore;
262    let (doc, file) = read_doc(path)?;
263    let run = run_commands.unwrap_or_else(|| trust.trusts(&doc, &file));
264    let plan = plan_of(store, &doc, trust, run);
265    let record = import_record(&plan).ok_or_else(|| "the file has no windows that can be opened".to_string())?;
266    let row = insert_workspace(store, &unique_name(store, &import_name(&doc, &file)))?;
267    if let Err(e) = store.user_workspace_save_record(&row.id, &record.to_string(), now_ms()) {
268        let _ = store.user_workspace_delete(&row.id);
269        return Err(e.to_string());
270    }
271    let switched = match switch_to(state, &row.id, window_id).await {
272        Ok(s) => s,
273        Err(e) => {
274            let _ = store.user_workspace_delete(&row.id);
275            return Err(e);
276        }
277    };
278    let mut notes = plan.notes;
279    notes.extend(start_agents(state).await);
280    if plan.windows.iter().any(|w| w.closed && w.tabs.iter().any(|t| t.blocks.iter().any(has_agent))) {
281        notes.push("An agent pane in a closed window opens as the agent picker when you reopen it.".to_string());
282    }
283    tracing::info!(workspace = %switched.id, windows = plan.windows.len(), "user_workspace: imported {}", file.display());
284    Ok((switched, notes))
285}
286
287fn has_agent(meta: &Value) -> bool {
288    meta.get(layout_file::META_LAYOUT_AGENT).and_then(|v| v.as_str()).is_some_and(|s| !s.is_empty())
289}
290
291/// Export the open workspace to `path` (`*.agentmux-workspace.json`). Returns
292/// `{path, warnings}`: what the user should check before sharing it.
293pub(crate) fn export(store: &Store, path: &str, ctx: &layout_file::ExportContext) -> Result<Value, String> {
294    let path = PathBuf::from(path);
295    if !layout_file::is_workspace_path(&path) {
296        return Err(format!("the path must be absolute and end in {}", layout_file::WORKSPACE_EXTENSION));
297    }
298    let id = current_id(store).ok_or_else(|| "no workspace is open".to_string())?;
299    let name = store.user_workspace_get(&id).ok().flatten().map(|w| w.name).unwrap_or_default();
300    let mut windows: Vec<WorkspaceWindow> = super::session_windows::live_windows(store)
301        .into_iter()
302        .map(|(w, ws)| WorkspaceWindow {
303            workspace_id: ws,
304            name: super::session_windows::saved_name(store, &w),
305            closed: false,
306        })
307        .collect();
308    windows.extend(super::session_closed::closed_entries(store).iter().filter_map(|e| {
309        Some(WorkspaceWindow {
310            workspace_id: e.get("workspaceid")?.as_str()?.to_string(),
311            name: e.get("window").and_then(|w| w.get("name")).and_then(|v| v.as_str()).map(str::to_string),
312            closed: true,
313        })
314    }));
315    let exported = layout_file::export_workspace(store, &name, &windows, ctx)?;
316    layout_file::write_layout_file(&path, &exported.doc)?;
317    Ok(json!({ "path": path.to_string_lossy(), "warnings": exported.warnings }))
318}
319
320// ---- Service handlers ----
321
322/// `workspace.ExportUserWorkspace(path, includeResume)`.
323pub(crate) async fn handle_export(state: &AppState, call: &WebCallType) -> WebReturnType {
324    let path: String = service::get_arg(&call.args, 0).unwrap_or_default();
325    let include_resume: bool = service::get_optional_arg(&call.args, 1).ok().flatten().unwrap_or(false);
326    let store = state.mstore.clone();
327    match tokio::task::spawn_blocking(move || export(&store, &path, &layout_file::ExportContext::live(include_resume))).await {
328        Ok(Ok(v)) => WebReturnType::success(v),
329        Ok(Err(e)) => WebReturnType::error(e),
330        Err(e) => WebReturnType::error(e.to_string()),
331    }
332}
333
334/// `workspace.PreviewImport(path)`.
335pub(crate) async fn handle_preview(state: &AppState, call: &WebCallType) -> WebReturnType {
336    let path: String = service::get_arg(&call.args, 0).unwrap_or_default();
337    let store = state.mstore.clone();
338    match tokio::task::spawn_blocking(move || preview(&store, &path, &ImportTrust::live())).await {
339        Ok(Ok(v)) => WebReturnType::success(v),
340        Ok(Err(e)) => WebReturnType::error(e),
341        Err(e) => WebReturnType::error(e.to_string()),
342    }
343}
344
345/// `workspace.ImportUserWorkspace` on the HTTP service route: refused. Whether the file's commands run and its agents
346/// start is the person's answer in the preview, and this route cannot tell the person's window from any other caller, so
347/// the import is the websocket command `workspace.importuserworkspace`, which only the window may call.
348pub(crate) async fn handle_import(_state: &AppState, _call: &WebCallType) -> WebReturnType {
349    WebReturnType::error(
350        "FORBIDDEN: importing a workspace is the person's own action: ask the person to import the workspace file from the AgentMux window"
351            .to_string(),
352    )
353}
354
355/// `workspace.importuserworkspace`, after the caller was proven to be the person's window: the switch plus `notes`, and the
356/// client's new state sent to every window (the service route's reply carried it back to the caller itself).
357pub(crate) async fn import_for_window(state: &AppState, req: CommandWorkspaceImportUserWorkspaceData) -> Result<WorkspaceImportUserWorkspaceResult, String> {
358    let (switched, notes) = import(state, &req.path, req.run_commands, &req.window_id, &ImportTrust::live()).await?;
359    state.event_bus.broadcast_mux_obj_updates(&super::user_workspace_switch::client_update(&state.mstore));
360    Ok(WorkspaceImportUserWorkspaceResult {
361        id: switched.id,
362        name: switched.name,
363        closed: switched.closed.into_iter().map(|(window_id, label)| WorkspaceClosedWindow { window_id, label }).collect(),
364        beside: u32::try_from(switched.beside).unwrap_or(u32::MAX),
365        notes,
366    })
367}
368
369#[cfg(test)]
370#[path = "user_workspace_files_tests.rs"]
371mod tests;