1use std::collections::{HashMap, HashSet};
32use std::sync::{LazyLock, Mutex};
33use std::time::{Duration, Instant};
34
35use agentmux_common::time::now_ms;
36use serde_json::{json, Value};
37
38use crate::backend::obj::{Block, Client, Window, Workspace};
39use crate::backend::service::{self, WebCallType, WebReturnType};
40use crate::backend::storage::store::Store;
41use crate::server::AppState;
42
43pub(crate) const CLOSED_META_KEY: &str = "workspace:closed_windows";
46
47pub(crate) const STATE_OPEN: &str = "open";
49pub(crate) const STATE_CLOSED: &str = "closed";
51
52const DISCARD_FOR: Duration = Duration::from_secs(60);
56
57static DISCARD: LazyLock<Mutex<HashMap<String, Instant>>> = LazyLock::new(Default::default);
58
59pub(crate) fn mark_discard(window_id: &str) {
61 let mut marks = DISCARD.lock().unwrap_or_else(|e| e.into_inner());
62 marks.retain(|_, at| at.elapsed() < DISCARD_FOR);
63 marks.insert(window_id.to_string(), Instant::now());
64}
65
66pub(crate) fn take_discard(window_id: &str) -> bool {
68 let mut marks = DISCARD.lock().unwrap_or_else(|e| e.into_inner());
69 marks.remove(window_id).is_some_and(|at| at.elapsed() < DISCARD_FOR)
70}
71
72pub(crate) fn placement_of(store: &Store, w: &Window) -> Value {
74 let mut window = json!({
75 "x": w.pos.x,
76 "y": w.pos.y,
77 "width": w.winsize.width,
78 "height": w.winsize.height,
79 });
80 if let Some(name) = super::session_windows::saved_name(store, w) {
81 window["name"] = json!(name);
82 }
83 let appearance = super::session_windows::saved_appearance(store, w);
84 if !appearance.is_empty() {
85 window["meta"] = Value::Object(appearance);
86 }
87 window
88}
89
90fn workspace_of(entry: &Value) -> Option<&str> {
91 entry.get("workspaceid").and_then(|v| v.as_str()).filter(|s| !s.is_empty())
92}
93
94fn closed_at(entry: &Value) -> i64 {
95 entry.get("closed_at_ms").and_then(|v| v.as_i64()).unwrap_or(0)
96}
97
98pub(crate) fn is_closed(entry: &Value) -> bool {
100 entry.get("state").and_then(|v| v.as_str()) == Some(STATE_CLOSED)
101}
102
103fn client(store: &Store) -> Option<Client> {
104 store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next())
105}
106
107fn entries(store: &Store) -> Vec<Value> {
108 client(store)
109 .and_then(|c| c.meta.get(CLOSED_META_KEY).and_then(|v| v.as_array()).cloned())
110 .unwrap_or_default()
111}
112
113fn update<R>(store: &Store, f: impl FnOnce(&mut Vec<Value>) -> R) -> Option<R> {
117 let result = store.with_tx(|tx| {
118 let Some(mut client) = tx.get_all::<Client>()?.into_iter().next() else {
119 return Ok(None);
120 };
121 let mut list = client.meta.get(CLOSED_META_KEY).and_then(|v| v.as_array()).cloned().unwrap_or_default();
122 let before = list.clone();
123 let out = f(&mut list);
124 let changed = list != before;
125 if changed {
126 if list.is_empty() {
127 client.meta.remove(CLOSED_META_KEY);
128 } else {
129 client.meta.insert(CLOSED_META_KEY.to_string(), Value::Array(list));
130 }
131 tx.update(&mut client)?;
132 }
133 Ok(Some((out, changed)))
134 });
135 match result {
136 Ok(Some((out, changed))) => {
137 if changed {
138 store.layout_writes().wrote("window");
139 }
140 Some(out)
141 }
142 Ok(None) => None,
143 Err(e) => {
144 tracing::warn!(error = %e, "session_closed: couldn't update the closed windows");
145 None
146 }
147 }
148}
149
150pub(crate) fn open_workspaces(store: &Store) -> HashSet<String> {
152 client(store)
153 .map(|c| c.windowids)
154 .unwrap_or_default()
155 .iter()
156 .filter_map(|id| store.get::<Window>(id).ok().flatten())
157 .map(|w| w.workspaceid)
158 .collect()
159}
160
161fn open_window_count(store: &Store) -> usize {
163 client(store)
164 .map(|c| c.windowids)
165 .unwrap_or_default()
166 .iter()
167 .filter_map(|id| store.get::<Window>(id).ok().flatten())
168 .filter(|w| w.kind.as_deref() != Some("subwindow"))
169 .count()
170}
171
172fn worth_keeping(store: &Store, ws_id: &str) -> bool {
175 super::session_restore::snapshot_workspace(store, ws_id)
176 .and_then(|snap| super::session_other_builds::summarize(&snap, "", "", 0))
177 .is_some()
178}
179
180fn remember(store: &Store, ws_id: &str, window: Value, closed_at_ms: i64) {
183 let entry = json!({
184 "workspaceid": ws_id,
185 "closed_at_ms": closed_at_ms,
186 "window": window,
187 });
188 update(store, |list| {
189 list.retain(|e| workspace_of(e) != Some(ws_id));
190 list.push(entry);
191 list.sort_by_key(|e| std::cmp::Reverse(closed_at(e)));
192 });
193}
194
195fn set_parked(store: &Store, ws_id: &str, parked: &[String]) {
197 if parked.is_empty() {
198 return;
199 }
200 update(store, |list| {
201 if let Some(entry) = list.iter_mut().find(|e| workspace_of(e) == Some(ws_id)) {
202 entry["parked"] = json!(parked);
203 }
204 });
205}
206
207fn mark_parked_in_record(store: &Store, row_id: &str, ws_id: &str, parked: &[String]) {
211 if parked.is_empty() {
212 return;
213 }
214 let Ok(Some(row)) = store.user_workspace_get(row_id) else { return };
215 let Some(mut record) = row.record.as_deref().and_then(|r| serde_json::from_str::<Value>(r).ok()) else { return };
216 let mut marked = false;
217 let mut mark = |window: &mut Value| {
218 if workspace_of(window) == Some(ws_id) {
219 window["parked"] = json!(parked);
220 marked = true;
221 }
222 };
223 match record.get_mut("windows").and_then(|v| v.as_array_mut()) {
224 Some(windows) if !windows.is_empty() => windows.iter_mut().for_each(&mut mark),
225 _ => mark(&mut record),
226 }
227 if !marked {
228 return;
229 }
230 if let Err(e) = store.user_workspace_save_record(row_id, &record.to_string(), now_ms()) {
231 tracing::warn!(error = %e, workspace_id = %ws_id, "session_closed: couldn't note the parked agents on the left workspace's record");
232 }
233}
234
235pub(crate) fn parked_of(entry: &Value) -> Vec<String> {
237 entry
238 .get("parked")
239 .and_then(|v| v.as_array())
240 .map(|ids| ids.iter().filter_map(|id| id.as_str().map(str::to_string)).collect())
241 .unwrap_or_default()
242}
243
244pub(crate) fn parked_blocks(store: &Store, ws_id: &str) -> Vec<(String, String)> {
247 use crate::persist_subscriber::parked::{PARKED_FROM_TAB_META_KEY, PARKED_META_KEY};
248 let Some(entry) = entries(store).into_iter().find(|e| workspace_of(e) == Some(ws_id)) else {
249 return Vec::new();
250 };
251 parked_of(&entry)
252 .into_iter()
253 .filter_map(|id| {
254 let block = store.get::<Block>(&id).ok().flatten()?;
255 if !crate::backend::obj::meta_get_bool(&block.meta, PARKED_META_KEY, false) {
256 return None;
257 }
258 let tab = crate::backend::obj::meta_get_string(&block.meta, PARKED_FROM_TAB_META_KEY, "");
259 (!tab.is_empty()).then_some((id, tab))
260 })
261 .collect()
262}
263
264pub(crate) fn forget(store: &Store, ws_id: &str) -> Option<Value> {
266 update(store, |list| {
267 let at = list.iter().position(|e| workspace_of(e) == Some(ws_id))?;
268 Some(list.remove(at))
269 })
270 .flatten()
271}
272
273pub(crate) fn quit_under_way(store: &Store) -> bool {
276 super::session_restore::load_last_session_snapshot(store)
277 .is_some_and(|r| super::session_windows::is_recent_quit_record(&r, now_ms()))
278}
279
280pub(crate) async fn keep_workspace(state: &AppState, ws_id: String, window: Value, unlisted: bool, left_for_switch: Option<&str>) {
295 if !worth_keeping(&state.mstore, &ws_id) {
296 super::window_close::close_workspace(state, ws_id).await;
297 return;
298 }
299 let guard = crate::sagas::close_pane::workspace_close_lock(&ws_id).await;
302 let listed = !unlisted && !quit_under_way(&state.mstore);
303 if listed {
304 remember(&state.mstore, &ws_id, window, now_ms());
305 }
306 let parks = listed || left_for_switch.is_some();
307 tracing::info!(
308 workspace_id = %ws_id,
309 listed,
310 "CloseWindow: keeping the window's contents (its agents {}; {})",
311 if parks { "keep running" } else { "stop" },
312 if listed { "a closed window of the workspace" } else { "it opens again with its workspace" }
313 );
314 let st = state.clone();
315 let left_for_switch = left_for_switch.map(str::to_string);
316 let done = crate::sagas::agent_teardown::detached(async move {
317 let _guard = guard;
318 let block_ids = super::window_close::store_block_ids(&st.mstore, &ws_id);
319 let parked = if parks { crate::sagas::park_agents::park_window_agents(&st, &ws_id, &block_ids).await } else { Vec::new() };
322 set_parked(&st.mstore, &ws_id, &parked);
323 if let Some(from) = &left_for_switch {
324 mark_parked_in_record(&st.mstore, from, &ws_id, &parked);
325 }
326 let stopping = crate::sagas::park_agents::not_parked(&block_ids, &parked);
327 crate::sagas::agent_teardown::run_many(&st, &stopping, crate::sagas::agent_teardown::Policy::close()).await;
328 for block_id in &block_ids {
330 crate::sagas::close_pane::finish_close(&st, block_id).await;
331 }
332 })
333 .await;
334 if done.is_none() {
335 tracing::warn!("CloseWindow: stopping a kept window's agents panicked");
336 }
337}
338
339pub(crate) fn closed_entries(store: &Store) -> Vec<Value> {
344 let open = open_workspaces(store);
345 entries(store)
346 .iter()
347 .filter_map(|e| {
348 let ws = workspace_of(e)?;
349 if open.contains(ws) {
350 return None;
351 }
352 let mut entry = match super::session_restore::snapshot_workspace(store, ws) {
353 Some(snap) => snap,
354 None if !parked_blocks(store, ws).is_empty() => json!({ "tabs": [], "active_tab_index": null }),
356 None => return None,
357 };
358 let parked = parked_of(e);
359 if !parked.is_empty() {
360 entry["parked"] = json!(parked);
361 }
362 entry["window"] = e.get("window").cloned().unwrap_or_else(|| json!({}));
363 entry["workspaceid"] = json!(ws);
364 entry["state"] = json!(STATE_CLOSED);
365 entry["closed_at_ms"] = json!(closed_at(e));
366 Some(entry)
367 })
368 .collect()
369}
370
371pub(crate) fn with_closed(store: &Store, mut record: Value) -> Value {
376 if !record.is_object() {
377 return record;
378 }
379 let mut windows = super::session_windows::windows_of(&record);
380 for w in &mut windows {
381 if w.get("state").is_none() {
382 w["state"] = json!(STATE_OPEN);
383 }
384 }
385 let held: HashSet<String> = windows.iter().filter_map(|w| workspace_of(w).map(str::to_string)).collect();
386 windows.extend(
387 closed_entries(store)
388 .into_iter()
389 .filter(|e| !matches!(workspace_of(e), Some(ws) if held.contains(ws))),
390 );
391 record["windows"] = Value::Array(windows);
392 record
393}
394
395pub(crate) async fn restore_closed(state: &AppState, record: &Value, main_ws: &str, skip: &HashSet<String>) -> usize {
403 let store = &state.mstore;
404 let mut busy = open_workspaces(store);
405 busy.extend(super::session_windows::waiting_workspaces(store));
406 busy.insert(main_ws.to_string());
407 let mut listed = 0usize;
408 let mut rebuilt = 0usize;
409 for entry in super::session_windows::windows_of(record).iter().filter(|w| is_closed(w)) {
410 if workspace_of(entry).is_some_and(|ws| skip.contains(ws)) {
411 continue;
412 }
413 let here = match workspace_of(entry).filter(|ws| !busy.contains(*ws)) {
414 Some(ws) => {
415 let known = state.srv_state.lock().await.workspaces.contains_key(ws);
416 (known && (super::session_restore::snapshot_workspace(store, ws).is_some() || !parked_of(entry).is_empty()))
417 .then(|| ws.to_string())
418 }
419 None => None,
420 };
421 let carried = if here.is_some() { parked_of(entry) } else { Vec::new() };
423 let ws_id = match here {
424 Some(ws) => ws,
425 None => match super::session_restore::restore_workspace(state, entry).await {
426 Ok(Some((ws, events))) => {
427 super::reducer_helpers::publish_events(state, &events);
428 rebuilt += 1;
429 ws
430 }
431 Ok(None) => {
432 tracing::warn!("session_closed: a closed window's tabs didn't come back; skipping it");
433 continue;
434 }
435 Err(e) => {
436 tracing::warn!(error = %e, "session_closed: a closed window didn't come back");
437 continue;
438 }
439 },
440 };
441 busy.insert(ws_id.clone());
442 let window = entry.get("window").cloned().unwrap_or_else(|| json!({}));
443 remember(store, &ws_id, window, closed_at(entry));
444 set_parked(store, &ws_id, &carried);
445 listed += 1;
446 }
447 if listed > 0 {
448 tracing::info!(listed, rebuilt, "session_closed: kept {} closed window(s) closed ({} rebuilt)", listed, rebuilt);
449 }
450 listed
451}
452
453fn snapshot_counts(snap: &Value) -> (u32, u32) {
455 let tabs = snap.get("tabs").and_then(|v| v.as_array()).cloned().unwrap_or_default();
456 let panes = tabs.iter().map(|t| t.get("blocks").and_then(|b| b.as_array()).map_or(0, |b| b.len())).sum::<usize>();
457 (tabs.len() as u32, panes as u32)
458}
459
460fn parked_summary(store: &Store, parked: &[(String, String)]) -> (u32, Vec<String>) {
462 use crate::backend::obj::{meta_get_string, Tab};
463 let mut alone = HashSet::new();
464 let mut names = Vec::new();
465 for (block_id, tab_id) in parked {
466 if store.get::<Tab>(tab_id).ok().flatten().is_some_and(|t| t.blockids.is_empty()) {
467 alone.insert(tab_id.clone());
468 }
469 if let Ok(Some(block)) = store.get::<Block>(block_id) {
470 let name = meta_get_string(&block.meta, "agentName", "");
471 let name = if name.is_empty() { meta_get_string(&block.meta, "agentId", "") } else { name };
472 if !name.is_empty() && !names.contains(&name) {
473 names.push(name);
474 }
475 }
476 }
477 (alone.len() as u32, names)
478}
479
480pub(crate) fn handle_list_closed_windows(state: &AppState, _call: &WebCallType) -> WebReturnType {
485 let store = &state.mstore;
486 let open = open_workspaces(store);
487 let list: Vec<Value> = entries(store)
488 .iter()
489 .filter_map(|e| {
490 let ws_id = workspace_of(e)?;
491 if open.contains(ws_id) {
492 return None;
493 }
494 let ws = store.get::<Workspace>(ws_id).ok().flatten()?;
495 let parked = parked_blocks(store, ws_id);
496 let snap = super::session_restore::snapshot_workspace(store, ws_id);
497 if snap.is_none() && parked.is_empty() {
498 return None;
499 }
500 let summary = snap.as_ref().and_then(|s| super::session_other_builds::summarize(s, "", "", 0));
501 let (parked_tabs, mut agents) = parked_summary(store, &parked);
502 let (tabs, panes) = match (&summary, &snap) {
505 (Some(s), _) => (s.tabs, s.panes),
506 (None, Some(snap)) if !parked.is_empty() => snapshot_counts(snap),
507 _ => (0, 0),
508 };
509 if let Some(s) = &summary {
510 agents.splice(0..0, s.agents.iter().cloned());
511 }
512 let name = e
513 .get("window")
514 .and_then(|w| w.get("name"))
515 .and_then(|v| v.as_str())
516 .map(str::to_string)
517 .unwrap_or(ws.name);
518 Some(json!({
519 "workspaceid": ws_id,
520 "closed_at_ms": closed_at(e),
521 "name": name,
522 "tabs": tabs + parked_tabs,
523 "panes": panes + parked.len() as u32,
524 "agents": agents,
525 "running": parked.len(),
526 }))
527 })
528 .collect();
529 WebReturnType::success(Value::Array(list))
530}
531
532pub(crate) async fn handle_take_closed_window(state: &AppState, call: &WebCallType) -> WebReturnType {
539 let ws_id: String = match service::get_arg(&call.args, 0) {
540 Ok(v) => v,
541 Err(e) => return WebReturnType::error(e),
542 };
543 let _stopped = crate::sagas::close_pane::workspace_close_lock(&ws_id).await;
544 let store = &state.mstore;
545 if open_workspaces(store).contains(&ws_id) {
546 forget(store, &ws_id);
547 return WebReturnType::error("that window is open");
548 }
549 let Some(entry) = entries(store).into_iter().find(|e| workspace_of(e) == Some(ws_id.as_str())) else {
550 return WebReturnType::error("that window isn't among the closed windows any more");
551 };
552 if store.get::<Workspace>(&ws_id).ok().flatten().is_none() {
553 return WebReturnType::error("that window's contents are gone");
554 }
555 let back = crate::sagas::park_agents::reattach_window_agents(state, &ws_id, &parked_of(&entry)).await;
557 if back > 0 {
558 tracing::info!(workspace_id = %ws_id, agents = back, "TakeClosedWindow: the window's agents are back in its tabs");
559 }
560 let window = entry.get("window").cloned().unwrap_or_else(|| json!({}));
561 let patch = super::session_windows::patch_of(&window);
562 if !patch.is_empty() {
563 let mut metas = serde_json::Map::new();
564 metas.insert(ws_id.clone(), Value::Object(patch));
565 super::session_windows::queue_restored_windows(store, Vec::new(), metas);
566 }
567 let mut out = json!({ "workspaceid": ws_id });
568 for key in ["x", "y", "width", "height"] {
569 if let Some(v) = window.get(key) {
570 out[key] = v.clone();
571 }
572 }
573 WebReturnType::success(out)
574}
575
576pub(crate) async fn handle_delete_closed_window(state: &AppState, call: &WebCallType) -> WebReturnType {
580 let ws_id: String = match service::get_arg(&call.args, 0) {
581 Ok(v) => v,
582 Err(e) => return WebReturnType::error(e),
583 };
584 drop(crate::sagas::close_pane::workspace_close_lock(&ws_id).await);
586 let store = &state.mstore;
587 if open_workspaces(store).contains(&ws_id) {
588 return WebReturnType::error("that window is open");
589 }
590 if forget(store, &ws_id).is_none() {
591 return WebReturnType::error("that window isn't among the closed windows any more");
592 }
593 tracing::info!(workspace_id = %ws_id, "session_closed: removing a closed window from the workspace");
594 super::window_close::close_workspace(state, ws_id).await;
595 WebReturnType::success_empty()
596}
597
598pub(crate) fn handle_discard_workspace_on_close(state: &AppState, call: &WebCallType) -> WebReturnType {
602 let window_id: String = match service::get_arg(&call.args, 0) {
603 Ok(v) => v,
604 Err(e) => return WebReturnType::error(e),
605 };
606 if open_window_count(&state.mstore) <= 1 {
607 return WebReturnType::error("the last window can't be removed from the workspace");
608 }
609 mark_discard(&window_id);
610 tracing::info!(window_id = %window_id, "CloseWindow: removing the window from the workspace; its close deletes its contents");
611 WebReturnType::success_empty()
612}
613
614pub(crate) fn handle_window_agents(state: &AppState, call: &WebCallType) -> WebReturnType {
618 let window_id: String = match service::get_arg(&call.args, 0) {
619 Ok(v) => v,
620 Err(e) => return WebReturnType::error(e),
621 };
622 let store = &state.mstore;
623 let Some(window) = store.get::<Window>(&window_id).ok().flatten() else {
624 return WebReturnType::success(json!([]));
625 };
626 WebReturnType::success(Value::Array(agents_in(store, &window.workspaceid)))
627}
628
629pub(crate) fn agents_in(store: &Store, ws_id: &str) -> Vec<Value> {
632 super::window_close::store_block_ids(store, ws_id)
633 .into_iter()
634 .filter_map(|block_id| {
635 let (name, working) = agent_of(store, &block_id)?;
636 Some(json!({ "block_id": block_id, "name": name, "working": working }))
637 })
638 .collect()
639}
640
641pub(crate) fn agent_of(store: &Store, block_id: &str) -> Option<(String, bool)> {
644 let status = crate::backend::blockcontroller::get_controller(block_id)?.get_runtime_status();
645 if !status.is_agent_pane {
646 return None;
647 }
648 let block = store.get::<crate::backend::obj::Block>(block_id).ok().flatten();
649 let meta_str = |key: &str| {
650 block
651 .as_ref()
652 .and_then(|b| b.meta.get(key))
653 .and_then(|v| v.as_str())
654 .filter(|s| !s.is_empty())
655 .map(str::to_string)
656 };
657 let name = meta_str("agentName").or_else(|| meta_str("agentId")).unwrap_or_else(|| block_id.to_string());
658 Some((name, status.turn_active))
659}
660
661#[cfg(test)]
662#[path = "session_closed_tests.rs"]
663mod tests;
664
665#[cfg(test)]
666#[path = "session_closed_agents_tests.rs"]
667mod agent_tests;
668
669#[cfg(test)]
670#[path = "session_slots_tests.rs"]
671mod slots_tests;