1use std::collections::{BTreeMap, HashMap};
26use std::path::{Path, PathBuf};
27
28use serde::{Deserialize, Serialize};
29use serde_json::{Map, Value};
30
31use agentmux_common::layout_types::LayoutNode;
32
33use crate::backend::obj::{Block, LayoutState, MetaMapType, Tab, Window, Workspace};
34use crate::backend::storage::store::Store;
35
36pub const LAYOUT_FORMAT: &str = "agentmux.layout";
38pub const LAYOUT_VERSION: u32 = 1;
40pub const LAYOUT_EXTENSION: &str = ".agentmux-layout.json";
43pub const WORKSPACE_EXTENSION: &str = ".agentmux-workspace.json";
45pub const SCOPE_WORKSPACE: &str = "workspace";
47pub const WINDOW_OPEN: &str = "open";
49pub const WINDOW_CLOSED: &str = "closed";
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct LayoutDoc {
55 pub format: String,
56 pub version: u32,
57 #[serde(default)]
58 pub name: String,
59 #[serde(default, skip_serializing_if = "String::is_empty")]
60 pub saved_at: String,
61 #[serde(default)]
62 pub saved_by: SavedBy,
63 #[serde(default)]
64 pub scope: String,
65 #[serde(default)]
66 pub windows: Vec<LayoutWindow>,
67 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
68 pub extra: Map<String, Value>,
69}
70
71#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
72pub struct SavedBy {
73 #[serde(default)]
74 pub app: String,
75 #[serde(default)]
76 pub app_version: String,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub instance: Option<String>,
81 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
82 pub extra: Map<String, Value>,
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
86pub struct LayoutWindow {
87 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub name: Option<String>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub state: Option<String>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub active_tab: Option<usize>,
95 #[serde(default)]
96 pub tabs: Vec<LayoutTab>,
97 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
98 pub extra: Map<String, Value>,
99}
100
101#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
102pub struct LayoutTab {
103 #[serde(default)]
104 pub name: String,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub focused: Option<String>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub magnified: Option<String>,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub root: Option<TreeNode>,
111 #[serde(default)]
113 pub panes: BTreeMap<String, LayoutPane>,
114 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
115 pub extra: Map<String, Value>,
116}
117
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120#[serde(untagged)]
121pub enum TreeNode {
122 Split {
123 split: String,
125 children: Vec<TreeChild>,
126 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
127 extra: Map<String, Value>,
128 },
129 Leaf {
130 pane: String,
131 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
132 extra: Map<String, Value>,
133 },
134}
135
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct TreeChild {
138 pub ratio: f64,
140 pub node: TreeNode,
141}
142
143#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
144pub struct LayoutPane {
145 pub views: Vec<LayoutView>,
147 #[serde(default)]
149 pub active: usize,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub minimized: Option<bool>,
152 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
153 pub extra: Map<String, Value>,
154}
155
156#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
157pub struct LayoutView {
158 #[serde(rename = "type")]
159 pub view_type: String,
160 #[serde(default, skip_serializing_if = "Map::is_empty")]
161 pub config: Map<String, Value>,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub resume: Option<Map<String, Value>>,
166 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
167 pub extra: Map<String, Value>,
168}
169
170pub struct ExportContext {
175 pub home: Option<PathBuf>,
177 pub app_version: String,
178 pub instance: Option<String>,
179 pub saved_at: String,
181 pub include_resume: bool,
183}
184
185impl ExportContext {
186 pub fn live(include_resume: bool) -> Self {
189 Self {
190 home: dirs::home_dir(),
191 app_version: env!("CARGO_PKG_VERSION").to_string(),
192 instance: crate::backend::storage::wan_identity::global()
193 .and_then(|w| w.instance_ensure(&crate::backend::reactive::registry::local_host_label()).ok())
194 .map(|i| i.instance_id),
195 saved_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
196 include_resume,
197 }
198 }
199}
200
201#[derive(Debug, Clone, PartialEq)]
204pub struct Exported {
205 pub doc: LayoutDoc,
206 pub warnings: Vec<String>,
207}
208
209pub fn export_window(store: &Store, window_id: &str, name: &str, ctx: &ExportContext) -> Result<Exported, String> {
211 let window = store
212 .get::<Window>(window_id)
213 .map_err(|e| format!("could not read window {window_id}: {e}"))?
214 .ok_or_else(|| format!("no such window: {window_id}"))?;
215 let mut warnings = Vec::new();
216 let exported = export_contents(store, &window.workspaceid, ctx, &mut warnings)?
217 .ok_or_else(|| "the window has no tabs with panes to save".to_string())?;
218 Ok(Exported { doc: envelope(name, "window", vec![exported], ctx), warnings })
219}
220
221fn envelope(name: &str, scope: &str, windows: Vec<LayoutWindow>, ctx: &ExportContext) -> LayoutDoc {
222 LayoutDoc {
223 format: LAYOUT_FORMAT.to_string(),
224 version: LAYOUT_VERSION,
225 name: name.to_string(),
226 saved_at: ctx.saved_at.clone(),
227 saved_by: SavedBy {
228 app: "agentmux".to_string(),
229 app_version: ctx.app_version.clone(),
230 instance: ctx.instance.clone(),
231 extra: Map::new(),
232 },
233 scope: scope.to_string(),
234 windows,
235 extra: Map::new(),
236 }
237}
238
239fn export_contents(
242 store: &Store,
243 workspace_id: &str,
244 ctx: &ExportContext,
245 warnings: &mut Vec<String>,
246) -> Result<Option<LayoutWindow>, String> {
247 let workspace = store
248 .get::<Workspace>(workspace_id)
249 .map_err(|e| format!("could not read the window's workspace: {e}"))?
250 .ok_or_else(|| "the window has no workspace".to_string())?;
251 let mut tabs = Vec::new();
252 let mut active_tab = None;
253 for tab_id in workspace.pinnedtabids.iter().chain(workspace.tabids.iter()) {
256 let Some(tab) = store.get::<Tab>(tab_id).ok().flatten() else { continue };
257 let Some(exported) = export_tab(store, &tab, ctx, warnings) else { continue };
258 if tab_id == &workspace.activetabid {
259 active_tab = Some(tabs.len());
260 }
261 tabs.push(exported);
262 }
263 Ok((!tabs.is_empty()).then(|| LayoutWindow { active_tab, tabs, ..Default::default() }))
264}
265
266pub struct WorkspaceWindow {
269 pub workspace_id: String,
270 pub name: Option<String>,
271 pub closed: bool,
272}
273
274pub fn export_workspace(
278 store: &Store,
279 name: &str,
280 windows: &[WorkspaceWindow],
281 ctx: &ExportContext,
282) -> Result<Exported, String> {
283 let mut warnings = Vec::new();
284 let mut out = Vec::new();
285 for w in windows {
286 let Some(mut exported) = export_contents(store, &w.workspace_id, ctx, &mut warnings)? else { continue };
287 exported.name = w.name.clone().filter(|n| !n.trim().is_empty());
288 exported.state = Some(if w.closed { WINDOW_CLOSED } else { WINDOW_OPEN }.to_string());
289 out.push(exported);
290 }
291 if out.is_empty() {
292 return Err("the workspace has no windows with panes to export".to_string());
293 }
294 Ok(Exported { doc: envelope(name, SCOPE_WORKSPACE, out, ctx), warnings })
295}
296
297struct TabBuilder<'a> {
300 store: &'a Store,
301 ctx: &'a ExportContext,
302 blocks: HashMap<String, Block>,
303 panes: BTreeMap<String, LayoutPane>,
304 pane_by_node: HashMap<String, String>,
305 warnings: &'a mut Vec<String>,
306}
307
308fn export_tab(store: &Store, tab: &Tab, ctx: &ExportContext, warnings: &mut Vec<String>) -> Option<LayoutTab> {
309 let layout = if tab.layoutstate.is_empty() {
310 None
311 } else {
312 store.get::<LayoutState>(&tab.layoutstate).ok().flatten()
313 };
314 let rootnode = layout.as_ref().and_then(|l| l.rootnode.clone())?;
315 let blocks = tab
316 .blockids
317 .iter()
318 .filter_map(|id| store.get::<Block>(id).ok().flatten().map(|b| (id.clone(), b)))
319 .collect();
320 let mut builder = TabBuilder {
321 store,
322 ctx,
323 blocks,
324 panes: BTreeMap::new(),
325 pane_by_node: HashMap::new(),
326 warnings,
327 };
328 let root = builder.node(&rootnode)?;
329 let layout = layout?;
330 let focused = builder.pane_by_node.get(&layout.focusednodeid).cloned();
331 let magnified = builder.pane_by_node.get(&layout.magnifiednodeid).cloned();
332 Some(LayoutTab {
333 name: tab.name.clone(),
334 focused,
335 magnified,
336 root: Some(root),
337 panes: builder.panes,
338 extra: Map::new(),
339 })
340}
341
342impl TabBuilder<'_> {
343 fn node(&mut self, node: &LayoutNode) -> Option<TreeNode> {
346 if node.children.is_empty() {
347 return self.leaf(node);
348 }
349 let mut kept: Vec<(f64, TreeNode)> = Vec::new();
350 for child in &node.children {
351 if let Some(converted) = self.node(child) {
352 kept.push((f64::from(child.size.max(0.0)), converted));
353 }
354 }
355 match kept.len() {
356 0 => None,
357 1 => kept.pop().map(|(_, n)| n),
359 _ => Some(TreeNode::Split {
360 split: match node.flex_direction {
361 agentmux_common::layout_types::FlexDirection::Column => "column",
362 _ => "row",
363 }
364 .to_string(),
365 children: ratios(&kept.iter().map(|(s, _)| *s).collect::<Vec<_>>())
366 .into_iter()
367 .zip(kept.into_iter().map(|(_, n)| n))
368 .map(|(ratio, node)| TreeChild { ratio, node })
369 .collect(),
370 extra: Map::new(),
371 }),
372 }
373 }
374
375 fn leaf(&mut self, node: &LayoutNode) -> Option<TreeNode> {
376 let data = node.data.as_ref()?;
377 let stack: Vec<&String> = if data.block_stack.is_empty() {
378 vec![&data.block_id]
379 } else {
380 data.block_stack.iter().collect()
381 };
382 let active_block = if data.active_block_id.is_empty() { &data.block_id } else { &data.active_block_id };
383 let mut views = Vec::new();
384 let mut active = 0;
385 for block_id in stack {
386 let Some(block) = self.blocks.get(block_id) else { continue };
387 if block_id == active_block {
388 active = views.len();
389 }
390 views.push(view_from_block(self.store, &block.meta, self.ctx, self.warnings));
391 }
392 if views.is_empty() {
393 return None;
394 }
395 let pane_id = format!("p{}", self.panes.len() + 1);
396 self.pane_by_node.insert(node.id.clone(), pane_id.clone());
397 self.panes.insert(
398 pane_id.clone(),
399 LayoutPane {
400 views,
401 active,
402 minimized: node.minimized.then_some(true),
403 extra: Map::new(),
404 },
405 );
406 Some(TreeNode::Leaf { pane: pane_id, extra: Map::new() })
407 }
408}
409
410fn ratios(sizes: &[f64]) -> Vec<f64> {
414 let total: f64 = sizes.iter().sum();
415 let n = sizes.len();
416 let raw: Vec<f64> = if total > 0.0 {
417 sizes.iter().map(|s| s / total).collect()
418 } else {
419 vec![1.0 / n as f64; n]
420 };
421 let mut out: Vec<f64> = raw.iter().map(|r| (r * 10_000.0).round() / 10_000.0).collect();
422 if let Some(last) = out.last_mut() {
423 let rest: f64 = raw.iter().take(n - 1).map(|r| (r * 10_000.0).round() / 10_000.0).sum();
424 *last = ((1.0 - rest) * 10_000.0).round() / 10_000.0;
425 }
426 out
427}
428
429fn armory_target(section: Option<&str>, subsection: Option<&str>) -> (&'static str, &'static str) {
434 match section {
435 Some("mcp") => ("connectors", "mcp"),
436 Some("memory") if subsection == Some("personal") => ("memory", "personal"),
437 Some("memory") => ("memory", "global"),
438 Some("native_memory") => ("memory", "personal"),
439 Some("skills") => ("memory", "skills"),
440 Some("bundles") => ("memory", "bundles"),
441 _ => ("connectors", "accounts"),
442 }
443}
444
445fn meta_str<'a>(meta: &'a MetaMapType, key: &str) -> Option<&'a str> {
446 meta.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
447}
448
449fn home_relative(path: &str, home: Option<&Path>) -> String {
451 let Some(home) = home.and_then(|h| h.to_str()) else { return path.to_string() };
452 let home = home.trim_end_matches(['/', '\\']);
453 let (Some(prefix), Some(rest)) = (path.get(..home.len()), path.get(home.len()..)) else {
457 return path.to_string();
458 };
459 let matches_prefix = if cfg!(windows) { prefix.eq_ignore_ascii_case(home) } else { prefix == home };
460 if !matches_prefix {
461 return path.to_string();
462 }
463 if rest.is_empty() {
464 return "~".to_string();
465 }
466 if !rest.starts_with(['/', '\\']) {
467 return path.to_string(); }
469 format!("~{}", rest.replace('\\', "/"))
470}
471
472fn strip_query(url: &str) -> String {
475 url.split(['?', '#']).next().unwrap_or("").to_string()
476}
477
478fn view_from_block(store: &Store, meta: &MetaMapType, ctx: &ExportContext, warnings: &mut Vec<String>) -> LayoutView {
483 let mut view_type = meta_str(meta, "view").unwrap_or("unknown").to_string();
484 let home = ctx.home.as_deref();
485 let mut config = Map::new();
486 let mut resume = None;
487 if matches!(view_type.as_str(), "armory" | "trust") {
490 let (pane, section) = armory_target(meta_str(meta, "armory:section"), meta_str(meta, "armory:memory:subsection"));
491 view_type = pane.to_string();
492 config.insert("section".into(), Value::String(section.to_string()));
493 }
494 if view_type == "knowledge" {
497 view_type = "memory".to_string();
498 if let Some(section) = meta_str(meta, "memory:section").or_else(|| meta_str(meta, "knowledge:section")) {
499 config.insert("section".into(), Value::String(section.to_string()));
500 }
501 }
502 if view_type == "remotes" {
504 view_type = "connectors".to_string();
505 config.insert("section".into(), Value::String("remotes".to_string()));
506 }
507 fold_moved_panes(&mut view_type, &mut config, meta);
508 match view_type.as_str() {
509 "agent" => {
510 let def = meta_str(meta, "agentId").and_then(|id| store.agent_def_get(id).ok().flatten());
512 let slug = def.as_ref().map(|d| d.slug.clone()).filter(|s| !s.is_empty());
513 let name = def
514 .as_ref()
515 .map(|d| d.name.clone())
516 .filter(|s| !s.is_empty())
517 .or_else(|| meta_str(meta, "agentName").map(str::to_string));
518 let provider = def
519 .as_ref()
520 .map(|d| d.provider.clone())
521 .filter(|s| !s.is_empty())
522 .or_else(|| meta_str(meta, "agentProvider").map(str::to_string));
523 if let Some(slug) = slug {
524 config.insert("agent".into(), Value::String(slug));
525 }
526 if let Some(name) = name {
527 config.insert("name".into(), Value::String(name));
528 }
529 if let Some(provider) = provider {
530 config.insert("provider".into(), Value::String(provider));
531 }
532 if ctx.include_resume {
533 if let Some(session) = meta_str(meta, "agent:sessionid") {
534 let mut r = Map::new();
535 r.insert("session_id".into(), Value::String(session.to_string()));
536 resume = Some(r);
537 }
538 }
539 }
540 "term" => {
541 if let Some(cwd) = meta_str(meta, "cmd:cwd") {
542 config.insert("cwd".into(), Value::String(home_relative(cwd, home)));
543 }
544 if let Some(cmd) = meta_str(meta, "cmd") {
545 let args: Vec<String> = meta
546 .get("cmd:args")
547 .and_then(Value::as_array)
548 .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
549 .unwrap_or_default();
550 let full = std::iter::once(cmd.to_string()).chain(args.iter().cloned()).collect::<Vec<_>>().join(" ");
551 if crate::backend::reactive::sanitize::is_sensitive_message(&full) {
552 warnings.push(format!(
553 "A terminal command looks like it may contain a credential or a destructive operation: `{}` — check the file before sharing it.",
554 crate::backend::reactive::sanitize::sanitize_message(&full)
555 ));
556 }
557 config.insert("command".into(), Value::String(cmd.to_string()));
558 if !args.is_empty() {
559 config.insert("args".into(), Value::Array(args.into_iter().map(Value::String).collect()));
560 }
561 }
562 }
563 "browser" => {
564 if let Some(url) = meta_str(meta, "url") {
565 config.insert("url".into(), Value::String(strip_query(url)));
566 }
567 }
568 "editor" | "codeeditor" | "preview" => {
569 if let Some(file) = meta_str(meta, "file") {
570 config.insert("file".into(), Value::String(home_relative(file, home)));
571 }
572 }
573 "media" => {
574 if let Some(path) = meta_str(meta, "media:path") {
575 config.insert("path".into(), Value::String(home_relative(path, home)));
576 }
577 }
578 "files" => {
579 if let Some(path) = meta_str(meta, "files:path") {
580 config.insert("path".into(), Value::String(home_relative(path, home)));
581 }
582 }
583 "sysinfo" => {
584 if let Some(kind) = meta_str(meta, "sysinfo:type") {
585 config.insert("sysinfo_type".into(), Value::String(kind.to_string()));
586 }
587 if let Some(area) = meta_str(meta, "sysinfo:focus") {
588 config.insert("sysinfo_focus".into(), Value::String(area.to_string()));
589 }
590 if let Some(secs) = meta.get("graph:windowsecs").and_then(Value::as_u64).filter(|&s| s > 0) {
591 config.insert("window_secs".into(), Value::from(secs));
592 }
593 if let Some(shown) = meta.get("sysinfo:showcontrols").and_then(Value::as_bool) {
594 config.insert("show_controls".into(), Value::Bool(shown));
595 }
596 }
597 "connectors" | "memory" | "warden" | "settings" | "vault" => {
598 let own = meta_str(meta, &format!("{view_type}:section"));
599 if let Some(section) = own.or(if view_type == "warden" { Some("jobs") } else { None }) {
600 config.insert("section".into(), Value::String(section.to_string()));
601 }
602 }
603 _ => {}
606 }
607 LayoutView { view_type, config, resume, extra: Map::new() }
608}
609
610pub fn is_layout_path(path: &Path) -> bool {
615 has_extension(path, LAYOUT_EXTENSION)
616}
617
618pub fn is_workspace_path(path: &Path) -> bool {
621 has_extension(path, WORKSPACE_EXTENSION)
622}
623
624fn has_extension(path: &Path, extension: &str) -> bool {
625 path.is_absolute()
626 && path
627 .file_name()
628 .and_then(|n| n.to_str())
629 .is_some_and(|n| n.to_ascii_lowercase().ends_with(extension) && n.len() > extension.len())
630}
631
632pub fn write_layout_file(path: &Path, doc: &LayoutDoc) -> Result<(), String> {
635 if !is_layout_path(path) && !is_workspace_path(path) {
636 return Err(format!(
637 "a layout must be saved to an absolute path ending in {LAYOUT_EXTENSION} or {WORKSPACE_EXTENSION}: {}",
638 path.display()
639 ));
640 }
641 let dir = path.parent().ok_or_else(|| format!("no parent directory: {}", path.display()))?;
642 std::fs::create_dir_all(dir).map_err(|e| format!("could not create {}: {e}", dir.display()))?;
643 let mut json = serde_json::to_string_pretty(doc).map_err(|e| format!("could not encode the layout: {e}"))?;
644 json.push('\n');
645 let tmp = dir.join(format!(".{}.tmp-{}", path.file_name().and_then(|n| n.to_str()).unwrap_or("layout"), uuid::Uuid::new_v4()));
646 std::fs::write(&tmp, json).map_err(|e| format!("could not write {}: {e}", tmp.display()))?;
647 std::fs::rename(&tmp, path).map_err(|e| {
648 let _ = std::fs::remove_file(&tmp);
649 format!("could not save {}: {e}", path.display())
650 })
651}
652
653pub fn parse_layout(json: &str) -> Result<LayoutDoc, String> {
656 let doc: LayoutDoc = serde_json::from_str(json).map_err(|e| format!("not a layout file: {e}"))?;
657 if doc.format != LAYOUT_FORMAT {
658 return Err(format!("not an AgentMux layout (format is \"{}\")", doc.format));
659 }
660 if doc.version > LAYOUT_VERSION {
661 return Err(format!(
662 "this layout was saved by a newer AgentMux (format version {}; this build reads up to {LAYOUT_VERSION})",
663 doc.version
664 ));
665 }
666 Ok(doc)
667}
668
669pub const META_LAYOUT_AGENT: &str = "layout:agent";
675
676pub const MAX_LAYOUT_FILE_BYTES: u64 = 1024 * 1024;
678const MAX_TABS: usize = 50;
679const MAX_WINDOWS: usize = 20;
681const MAX_PANES_PER_TAB: usize = 64;
682const MAX_TREE_DEPTH: usize = 32;
683
684const PLAIN_VIEWS: &[&str] = &[
686 "swarm", "kanban", "help", "drone", "workflows", "toolchain", "launcher", "shortcuts", "identity", "tower", "atlas",
687];
688
689const AUDIT_SECTIONS: &[&str] = &["events", "conversations", "typed", "storage"];
691
692fn warden_section_pane(section: Option<&str>) -> Option<&'static str> {
697 match section.unwrap_or("") {
698 "jobs" => None,
699 "vault" => Some("vault"),
700 "history" => Some("history"),
701 "host" => Some("swarm"),
702 "kanban" => Some("kanban"),
703 _ => Some("audit"),
704 }
705}
706
707pub struct PlanOptions {
709 pub home: Option<PathBuf>,
711 pub run_commands: bool,
714}
715
716#[derive(Debug, Clone)]
719pub struct PlanTab {
720 pub name: String,
721 pub blocks: Vec<Value>,
722 pub rootnode: Option<LayoutNode>,
723 pub focused: String,
724 pub magnified: String,
725 pub summary: Vec<String>,
727}
728
729#[derive(Debug, Clone, Default)]
732pub struct ApplyPlan {
733 pub name: String,
734 pub tabs: Vec<PlanTab>,
735 pub active_tab: Option<usize>,
736 pub commands: Vec<String>,
738 pub notes: Vec<String>,
740}
741
742pub fn read_layout_file(path: &Path) -> Result<LayoutDoc, String> {
744 let meta = std::fs::metadata(path).map_err(|e| format!("could not read {}: {e}", path.display()))?;
745 if meta.len() > MAX_LAYOUT_FILE_BYTES {
746 return Err(format!("{} is too large to be a layout file", path.display()));
747 }
748 let text = std::fs::read_to_string(path).map_err(|e| format!("could not read {}: {e}", path.display()))?;
749 parse_layout(&text)
750}
751
752fn expand_home(path: &str, home: Option<&Path>) -> PathBuf {
754 match (path.strip_prefix('~'), home) {
755 (Some(""), Some(h)) => h.to_path_buf(),
756 (Some(rest), Some(h)) if rest.starts_with(['/', '\\']) => h.join(rest.trim_start_matches(['/', '\\'])),
757 _ => PathBuf::from(path),
758 }
759}
760
761fn cfg_str<'a>(view: &'a LayoutView, key: &str) -> Option<&'a str> {
762 view.config.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
763}
764
765fn resolve_agent<'a>(
769 agents: &'a [crate::backend::storage::agents::AgentDefinition],
770 slug: Option<&str>,
771 name: Option<&str>,
772) -> Option<&'a crate::backend::storage::agents::AgentDefinition> {
773 fn unique<'a, T>(mut it: impl Iterator<Item = &'a T>) -> Option<&'a T> {
774 let first = it.next()?;
775 it.next().is_none().then_some(first)
776 }
777 let users = || agents.iter().filter(|a| a.is_seeded == 0);
778 slug.and_then(|s| unique(users().filter(|a| a.slug.eq_ignore_ascii_case(s))))
779 .or_else(|| name.and_then(|n| unique(users().filter(|a| a.name.eq_ignore_ascii_case(n)))))
780}
781
782pub fn plan_from_doc(store: &Store, doc: &LayoutDoc, opts: &PlanOptions) -> ApplyPlan {
784 let agents = store.agent_def_list().unwrap_or_default();
785 let mut plan = ApplyPlan { name: doc.name.clone(), ..Default::default() };
786 let Some(window) = doc.windows.first() else {
787 plan.notes.push("The file has no windows.".to_string());
788 return plan;
789 };
790 if doc.windows.len() > 1 {
791 plan.notes.push(format!("The file has {} windows; only the first is opened.", doc.windows.len()));
792 }
793 let (tabs, active_tab) = plan_window(&agents, window, opts, &mut plan.commands, &mut plan.notes);
794 plan.tabs = tabs;
795 plan.active_tab = active_tab;
796 plan
797}
798
799#[derive(Debug, Clone, Default)]
801pub struct WindowPlan {
802 pub name: Option<String>,
803 pub closed: bool,
804 pub tabs: Vec<PlanTab>,
805 pub active_tab: Option<usize>,
806}
807
808#[derive(Debug, Clone, Default)]
812pub struct WorkspacePlan {
813 pub windows: Vec<WindowPlan>,
815 pub commands: Vec<String>,
816 pub notes: Vec<String>,
817}
818
819pub fn plan_workspace(store: &Store, doc: &LayoutDoc, opts: &PlanOptions) -> WorkspacePlan {
822 let agents = store.agent_def_list().unwrap_or_default();
823 let mut plan = WorkspacePlan::default();
824 if doc.windows.is_empty() {
825 plan.notes.push("The file has no windows.".to_string());
826 }
827 if doc.windows.len() > MAX_WINDOWS {
828 plan.notes.push(format!("Only the first {MAX_WINDOWS} of {} windows are opened.", doc.windows.len()));
829 }
830 for (i, window) in doc.windows.iter().take(MAX_WINDOWS).enumerate() {
831 let (tabs, active_tab) = plan_window(&agents, window, opts, &mut plan.commands, &mut plan.notes);
832 if tabs.is_empty() {
833 plan.notes.push(format!("Window {} has no panes that can be opened, so it is skipped.", i + 1));
834 continue;
835 }
836 plan.windows.push(WindowPlan {
837 name: window.name.clone().map(|n| n.trim().to_string()).filter(|n| !n.is_empty()),
838 closed: window.state.as_deref() == Some(WINDOW_CLOSED),
839 tabs,
840 active_tab,
841 });
842 }
843 plan
844}
845
846fn plan_window(
848 agents: &[crate::backend::storage::agents::AgentDefinition],
849 window: &LayoutWindow,
850 opts: &PlanOptions,
851 commands: &mut Vec<String>,
852 notes: &mut Vec<String>,
853) -> (Vec<PlanTab>, Option<usize>) {
854 let mut tabs = Vec::new();
855 let mut active_tab = None;
856 if window.tabs.len() > MAX_TABS {
857 notes.push(format!("Only the first {MAX_TABS} of {} tabs are opened.", window.tabs.len()));
858 }
859 for (i, tab) in window.tabs.iter().take(MAX_TABS).enumerate() {
860 let mut builder = PlanBuilder {
861 doc_tab: tab,
862 agents,
863 opts,
864 blocks: Vec::new(),
865 summary: Vec::new(),
866 node_by_pane: HashMap::new(),
867 panes_used: 0,
868 truncated: Vec::new(),
869 commands,
870 notes,
871 };
872 let rootnode = tab.root.as_ref().and_then(|root| builder.node(root, 100.0, 0));
873 let (blocks, summary, node_by_pane) = (builder.blocks, builder.summary, builder.node_by_pane);
874 if blocks.is_empty() {
875 notes.push(format!("Tab “{}” has no panes that can be opened, so it is skipped.", tab.name));
876 continue;
877 }
878 if window.active_tab == Some(i) {
879 active_tab = Some(tabs.len());
880 }
881 let node_for = |pane: &Option<String>| pane.as_ref().and_then(|p| node_by_pane.get(p)).cloned().unwrap_or_default();
882 tabs.push(PlanTab {
883 name: tab.name.clone(),
884 blocks,
885 rootnode,
886 focused: node_for(&tab.focused),
887 magnified: node_for(&tab.magnified),
888 summary,
889 });
890 }
891 (tabs, active_tab)
892}
893
894struct PlanBuilder<'a> {
895 doc_tab: &'a LayoutTab,
896 agents: &'a [crate::backend::storage::agents::AgentDefinition],
897 opts: &'a PlanOptions,
898 blocks: Vec<Value>,
899 summary: Vec<String>,
900 node_by_pane: HashMap<String, String>,
901 panes_used: usize,
902 truncated: Vec<Truncated>,
903 commands: &'a mut Vec<String>,
904 notes: &'a mut Vec<String>,
905}
906
907#[derive(PartialEq)]
910enum Truncated {
911 Depth,
912 Panes,
913}
914
915impl PlanBuilder<'_> {
916 fn note_once(&mut self, what: Truncated) {
917 if self.truncated.contains(&what) {
918 return;
919 }
920 let tab = &self.doc_tab.name;
921 self.notes.push(match what {
922 Truncated::Depth => format!("Tab “{tab}” nests too deeply; the rest is skipped."),
923 Truncated::Panes => format!("Tab “{tab}” has more than {MAX_PANES_PER_TAB} panes; only the first {MAX_PANES_PER_TAB} are opened."),
924 });
925 self.truncated.push(what);
926 }
927
928 fn node(&mut self, node: &TreeNode, size: f64, depth: usize) -> Option<LayoutNode> {
929 if depth > MAX_TREE_DEPTH {
930 self.note_once(Truncated::Depth);
931 return None;
932 }
933 match node {
934 TreeNode::Split { split, children, .. } => {
935 let kids: Vec<LayoutNode> = children
936 .iter()
937 .filter_map(|c| self.node(&c.node, c.ratio.clamp(0.0, 1.0) * 100.0, depth + 1))
938 .collect();
939 match kids.len() {
940 0 => None,
941 1 => kids.into_iter().next().map(|mut only| {
942 only.size = size as f32;
943 only
944 }),
945 _ => Some(LayoutNode {
946 id: uuid::Uuid::new_v4().to_string(),
947 flex_direction: if split == "column" {
948 agentmux_common::layout_types::FlexDirection::Column
949 } else {
950 agentmux_common::layout_types::FlexDirection::Row
951 },
952 size: size as f32,
953 children: kids,
954 ..Default::default()
955 }),
956 }
957 }
958 TreeNode::Leaf { pane, .. } => {
959 if self.panes_used >= MAX_PANES_PER_TAB {
960 self.note_once(Truncated::Panes);
961 return None;
962 }
963 let tab = &self.doc_tab.name;
964 let Some(doc_pane) = self.doc_tab.panes.get(pane) else {
965 self.notes.push(format!("Tab “{tab}” refers to a pane “{pane}” the file doesn't define; it's left out."));
966 return None;
967 };
968 if doc_pane.views.is_empty() {
969 self.notes.push(format!("Pane “{pane}” in tab “{tab}” has nothing to show; it's left out."));
970 return None;
971 }
972 let mut placeholders = Vec::new();
973 for view in &doc_pane.views {
974 let meta = self.view_meta(view);
975 placeholders.push(placeholder(self.blocks.len()));
976 self.blocks.push(meta);
977 }
978 self.panes_used += 1;
979 let active = placeholders[doc_pane.active.min(placeholders.len() - 1)].clone();
980 let id = uuid::Uuid::new_v4().to_string();
981 self.node_by_pane.insert(pane.clone(), id.clone());
982 let multi = placeholders.len() > 1;
983 Some(LayoutNode {
984 id,
985 size: size as f32,
986 data: Some(agentmux_common::layout_types::LayoutNodeData {
987 block_id: active.clone(),
988 block_stack: if multi { placeholders } else { Vec::new() },
989 active_block_id: if multi { active } else { String::new() },
990 ..Default::default()
991 }),
992 minimized: doc_pane.minimized == Some(true),
993 ..Default::default()
994 })
995 }
996 }
997 }
998
999 fn view_meta(&mut self, view: &LayoutView) -> Value {
1001 let home = self.opts.home.as_deref();
1002 let mut meta = Map::new();
1003 let kind = view.view_type.as_str();
1004 match kind {
1005 "agent" => {
1006 meta.insert("view".into(), "agent".into());
1007 let slug = cfg_str(view, "agent");
1008 let name = cfg_str(view, "name");
1009 let label = name.or(slug).unwrap_or("agent");
1010 match resolve_agent(self.agents, slug, name) {
1011 Some(def) => {
1012 meta.insert(META_LAYOUT_AGENT.into(), Value::String(def.id.clone()));
1013 self.summary.push(format!("Agent: {}", def.name));
1014 }
1015 None if slug.is_none() && name.is_none() => self.summary.push("Agent picker".to_string()),
1017 None => {
1018 self.notes.push(format!("There's no agent “{label}” here — its pane opens the agent picker."));
1019 self.summary.push(format!("Agent: {label} (not found — picker)"));
1020 }
1021 }
1022 }
1023 "term" => {
1024 meta.insert("view".into(), "term".into());
1025 let cwd = cfg_str(view, "cwd").map(|c| expand_home(c, home));
1026 let mut where_ = String::new();
1027 if let Some(cwd) = cwd {
1028 if cwd.is_dir() {
1029 where_ = format!(" in {}", cwd.display());
1030 meta.insert("cmd:cwd".into(), Value::String(cwd.to_string_lossy().to_string()));
1031 } else {
1032 self.notes.push(format!("Folder {} doesn't exist here — that terminal starts in the default folder.", cwd.display()));
1033 }
1034 }
1035 let command = cfg_str(view, "command").map(|c| {
1036 let args: Vec<String> = view
1037 .config
1038 .get("args")
1039 .and_then(Value::as_array)
1040 .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
1041 .unwrap_or_default();
1042 (c.to_string(), args)
1043 });
1044 match command {
1045 Some((cmd, args)) => {
1046 let full = std::iter::once(cmd.clone()).chain(args.iter().cloned()).collect::<Vec<_>>().join(" ");
1047 self.commands.push(full.clone());
1048 if self.opts.run_commands {
1049 meta.insert("controller".into(), "cmd".into());
1050 meta.insert("cmd".into(), Value::String(cmd));
1051 if !args.is_empty() {
1052 meta.insert("cmd:args".into(), Value::Array(args.into_iter().map(Value::String).collect()));
1053 }
1054 self.summary.push(format!("Terminal{where_}: runs `{full}`"));
1055 } else {
1056 meta.insert("controller".into(), "shell".into());
1057 self.summary.push(format!("Terminal{where_} (command not run: `{full}`)"));
1058 }
1059 }
1060 None => {
1061 meta.insert("controller".into(), "shell".into());
1062 self.summary.push(format!("Terminal{where_}"));
1063 }
1064 }
1065 }
1066 "browser" => {
1067 meta.insert("view".into(), "browser".into());
1068 match cfg_str(view, "url") {
1069 Some(url) if url.starts_with("https://") || url.starts_with("http://") => {
1070 meta.insert("url".into(), Value::String(url.to_string()));
1071 self.summary.push(format!("Browser: {url}"));
1072 }
1073 Some(url) => {
1074 self.notes.push(format!("Skipped a browser address that isn't http(s): {url}"));
1075 self.summary.push("Browser".to_string());
1076 }
1077 None => self.summary.push("Browser".to_string()),
1078 }
1079 }
1080 "editor" | "codeeditor" | "preview" => {
1081 meta.insert("view".into(), "editor".into());
1082 match cfg_str(view, "file").map(|f| expand_home(f, home)) {
1083 Some(file) => {
1084 if !file.exists() {
1085 self.notes.push(format!("File {} doesn't exist here.", file.display()));
1086 }
1087 self.summary.push(format!("Editor: {}", file.display()));
1088 meta.insert("file".into(), Value::String(file.to_string_lossy().to_string()));
1089 }
1090 None => {
1091 meta.insert("editor:scratch".into(), Value::Bool(true));
1092 self.summary.push("Editor".to_string());
1093 }
1094 }
1095 }
1096 "media" => {
1100 meta.insert("view".into(), "editor".into());
1101 if let Some(path) = cfg_str(view, "path").map(|p| expand_home(p, home)) {
1102 self.summary.push(format!("Editor: {}", path.display()));
1103 meta.insert("file".into(), Value::String(path.to_string_lossy().to_string()));
1104 meta.insert("editor:follow_folder".into(), Value::Bool(true));
1105 } else {
1106 meta.insert("editor:scratch".into(), Value::Bool(true));
1107 self.summary.push("Editor".to_string());
1108 }
1109 }
1110 "files" => {
1111 meta.insert("view".into(), "files".into());
1112 if let Some(path) = cfg_str(view, "path").map(|p| expand_home(p, home)) {
1113 self.summary.push(format!("Files: {}", path.display()));
1114 meta.insert("files:path".into(), Value::String(path.to_string_lossy().to_string()));
1115 } else {
1116 self.summary.push("Files".to_string());
1117 }
1118 }
1119 "sysinfo" => {
1120 meta.insert("view".into(), "sysinfo".into());
1121 if let Some(k) = cfg_str(view, "sysinfo_type") {
1122 meta.insert("sysinfo:type".into(), Value::String(k.to_string()));
1123 }
1124 if let Some(area) = cfg_str(view, "sysinfo_focus") {
1125 meta.insert("sysinfo:focus".into(), Value::String(area.to_string()));
1126 }
1127 let secs = view.config.get("window_secs").and_then(Value::as_u64);
1129 if let Some(secs) = secs.filter(|&s| s > 0 && s <= 86_400) {
1130 meta.insert("graph:windowsecs".into(), Value::from(secs));
1131 }
1132 if let Some(shown) = view.config.get("show_controls").and_then(Value::as_bool) {
1133 meta.insert("sysinfo:showcontrols".into(), Value::Bool(shown));
1134 }
1135 self.summary.push("System info".to_string());
1136 }
1137 "connectors" | "memory" | "knowledge" | "armory" | "remotes" => {
1141 let (pane, section) = match kind {
1142 "armory" => {
1143 let (pane, section) = armory_target(cfg_str(view, "section"), None);
1144 (pane, Some(section))
1145 }
1146 "knowledge" => ("memory", cfg_str(view, "section")),
1147 "remotes" => ("connectors", Some("remotes")),
1148 pane => (pane, cfg_str(view, "section")),
1149 };
1150 meta.insert("view".into(), pane.into());
1151 if let Some(s) = section {
1152 meta.insert(format!("{pane}:section"), Value::String(s.to_string()));
1153 }
1154 self.summary.push(if pane == "connectors" { "Connectors" } else { "Memory" }.to_string());
1155 }
1156 "warden" | "settings" | "vault" => {
1159 let section = cfg_str(view, "section");
1160 let (pane, section, sub) = pane_section_for(kind, section);
1161 meta.insert("view".into(), pane.into());
1162 if let Some(s) = section {
1163 meta.insert(format!("{pane}:section"), Value::String(s.to_string()));
1164 }
1165 if let Some(sub) = sub {
1166 meta.insert("vault:section".into(), Value::String(sub.to_string()));
1167 }
1168 self.summary.push(pane.to_string());
1169 }
1170 "reviews" => fold_reviews_meta(view, &mut meta, &mut self.summary),
1171 "history" | "audit" => fold_audit_meta(kind == "history", view, &mut meta, &mut self.summary),
1173 k if PLAIN_VIEWS.contains(&k) => {
1174 meta.insert("view".into(), Value::String(k.to_string()));
1175 self.summary.push(k.to_string());
1176 }
1177 other => {
1178 let shown: String = other.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(40).collect();
1181 self.notes.push(format!("Pane type “{shown}” isn't known to this version — it opens as an empty pane."));
1182 meta.insert("view".into(), Value::String(shown.clone()));
1183 self.summary.push(format!("{shown} (unknown)"));
1184 }
1185 }
1186 Value::Object(meta)
1187 }
1188}
1189
1190fn pane_section_for<'a>(kind: &'a str, section: Option<&'a str>) -> (&'a str, Option<&'a str>, Option<&'a str>) {
1194 match kind {
1195 "warden" => {
1196 let (id, sub) = match section.map(|s| s.split_once('/').unwrap_or((s, ""))) {
1197 Some((id, sub)) => (Some(id), Some(sub).filter(|s| !s.is_empty())),
1198 None => (None, None),
1199 };
1200 match warden_section_pane(id) {
1201 None => ("warden", id, None),
1202 Some("vault") => ("vault", None, sub),
1203 Some("history") => ("audit", Some("conversations"), None),
1204 Some(pane) => (pane, None, None),
1205 }
1206 }
1207 "vault" => ("vault", None, section),
1208 pane => (pane, section, None),
1209 }
1210}
1211
1212fn fold_audit_meta(history: bool, view: &LayoutView, meta: &mut Map<String, Value>, summary: &mut Vec<String>) {
1215 meta.insert("view".into(), Value::String("audit".to_string()));
1216 let section = if history { Some("conversations") } else { cfg_str(view, "section").filter(|s| AUDIT_SECTIONS.contains(s)) };
1217 if let Some(section) = section {
1218 meta.insert("audit:section".into(), Value::String(section.to_string()));
1219 }
1220 summary.push("audit".to_string());
1221}
1222
1223fn fold_moved_panes(view_type: &mut String, config: &mut Map<String, Value>, meta: &MetaMapType) {
1229 if view_type == "warden" {
1230 if let Some(pane) = warden_section_pane(Some(meta_str(meta, "warden:section").unwrap_or("jobs"))) {
1231 *view_type = pane.to_string();
1232 }
1233 }
1234 if view_type == "history" {
1235 *view_type = "audit".to_string();
1236 config.insert("section".into(), Value::String("conversations".to_string()));
1237 }
1238 if view_type == "audit" && !config.contains_key("section") {
1239 if let Some(section) = meta_str(meta, "audit:section").filter(|s| AUDIT_SECTIONS.contains(s)) {
1240 config.insert("section".into(), Value::String(section.to_string()));
1241 }
1242 }
1243}
1244
1245fn fold_reviews_meta(view: &LayoutView, meta: &mut serde_json::Map<String, Value>, summary: &mut Vec<String>) {
1248 summary.push("kanban".to_string());
1249 meta.insert("view".into(), Value::String("kanban".to_string()));
1250 meta.insert("kanban:waits".into(), Value::String("open".to_string()));
1251 if let Some(task) = cfg_str(view, "task") {
1252 meta.insert("kanban:open".into(), Value::String(task.to_string()));
1253 }
1254}
1255
1256pub fn is_trusted(doc: &LayoutDoc, path: &Path, own_instance: Option<&str>, layouts_dir: Option<&Path>) -> bool {
1260 let saved_here = own_instance.is_some_and(|own| doc.saved_by.instance.as_deref() == Some(own));
1261 let in_folder = layouts_dir.is_some_and(|dir| path.parent().is_some_and(|p| p == dir));
1262 saved_here && in_folder
1263}
1264
1265pub fn placeholder(idx: usize) -> String {
1267 format!("__snap_block_{idx}__")
1268}
1269
1270pub fn placeholder_idx(s: &str) -> Option<usize> {
1271 s.strip_prefix("__snap_block_")?.strip_suffix("__")?.parse().ok()
1272}
1273
1274#[cfg(test)]
1275mod tests;