1use 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
37pub(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
62fn 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
76fn 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
92pub(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
106pub(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
130pub(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
174fn 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
195async 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 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 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
239fn 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
251pub(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
291pub(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
320pub(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
334pub(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
345pub(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
355pub(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;