Skip to main content

agentmux_srv_core/persist_subscriber/
parked.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Persisting a parked block: one in no tab (`Command::ParkBlock`, `Command::AttachBlock`).
5
6use crate::backend::obj::{Block, Tab};
7use crate::backend::wcore;
8use crate::backend::storage::store::Store;
9
10/// Block meta that marks a parked block, one in no tab (`Command::ParkBlock`): boot loads such a
11/// block into the reducer's state (`persist::bootstrap`) instead of dropping it as an orphan.
12pub const PARKED_META_KEY: &str = "agent:parked";
13
14/// Block meta on a parked block: the tab it was parked from, so a parked agent that spawns or opens
15/// panes puts them in its own tab, not the one the user happens to be looking at.
16pub const PARKED_FROM_TAB_META_KEY: &str = "agent:parkedFromTab";
17
18/// A parked block (`Command::ParkBlock`): out of the tab's `blockids`, its row and meta kept,
19/// its parent cleared and `agent:parked` set, which boot reads to load it (`persist::bootstrap`).
20pub(super) fn apply_block_parked(mstore: &Store, tab_id: &str, block_id: &str) -> Result<(), Box<dyn std::error::Error>> {
21    mstore.with_tx(|tx| {
22        if let Some(mut tab) = tx.get::<Tab>(tab_id)? {
23            let before = tab.blockids.len();
24            tab.blockids.retain(|id| id != block_id);
25            if tab.blockids.len() != before {
26                tx.update(&mut tab)?;
27            }
28        }
29        if let Some(mut block) = tx.get::<Block>(block_id)? {
30            block.parentoref = String::new();
31            block.meta.insert(PARKED_META_KEY.to_string(), serde_json::json!(true));
32            if !tab_id.is_empty() {
33                block.meta.insert(PARKED_FROM_TAB_META_KEY.to_string(), serde_json::json!(tab_id));
34            }
35            tx.update(&mut block)?;
36        }
37        Ok(())
38    })?;
39    Ok(())
40}
41
42/// A parked block put into a tab (`Command::AttachBlock`): in the tab's `blockids`, its parent
43/// set, the parked mark gone. Idempotent on re-delivery.
44pub(super) fn apply_block_attached(mstore: &Store, block_id: &str, dst_tab_id: &str, dst_index: u32) -> Result<(), Box<dyn std::error::Error>> {
45    mstore.with_tx(|tx| {
46        if let Some(mut tab) = tx.get::<Tab>(dst_tab_id)? {
47            if !tab.blockids.iter().any(|id| id == block_id) {
48                let at = (dst_index as usize).min(tab.blockids.len());
49                tab.blockids.insert(at, block_id.to_string());
50                tx.update(&mut tab)?;
51            }
52        }
53        if let Some(mut block) = tx.get::<Block>(block_id)? {
54            block.parentoref = format!("tab:{}", dst_tab_id);
55            block.meta.remove(PARKED_META_KEY);
56            block.meta.remove(PARKED_FROM_TAB_META_KEY);
57            tx.update(&mut block)?;
58        }
59        Ok(())
60    })?;
61    Ok(())
62}
63
64/// A deleted block: its row, and its place in its tab. A parked block was in no tab (`tab_id` is
65/// empty), so there is only the row. Idempotent.
66pub(super) fn apply_block_deleted(mstore: &Store, tab_id: &str, block_id: &str) -> Result<(), Box<dyn std::error::Error>> {
67    if mstore.get::<Block>(block_id)?.is_none() {
68        return Ok(()); // already gone
69    }
70    if tab_id.is_empty() {
71        return Ok(wcore::delete_parked_block(mstore, block_id)?);
72    }
73    match wcore::delete_block(mstore, tab_id, block_id) {
74        Ok(()) | Err(crate::backend::storage::StoreError::NotFound) => Ok(()),
75        Err(e) => Err(Box::new(e)),
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use crate::backend::wcore;
83    use agentmux_common::ipc::Event;
84
85    fn block_created(tab_id: &str, block_id: &str) -> Event {
86        Event::BlockCreated { tab_id: tab_id.into(), block_id: block_id.into(), meta: serde_json::json!({ "agentId": "ann" }), version: 1 }
87    }
88
89    /// Park keeps the row and its meta and only leaves the tab; attach puts it back in any tab.
90    #[test]
91    fn park_then_attach_moves_the_block_between_no_tab_and_a_tab_keeping_its_meta() {
92        let s = Store::open_in_memory().unwrap();
93        let ws = wcore::create_workspace(&s, "W").unwrap();
94        let (a, b) = (wcore::create_tab_with_opts(&s, &ws.oid, "a", false).unwrap(), wcore::create_tab_with_opts(&s, &ws.oid, "b", false).unwrap());
95        crate::persist_subscriber::apply_event_to_mstore(&block_created(&a.oid, "blk"), &s).unwrap();
96
97        apply_block_parked(&s, &a.oid, "blk").unwrap();
98        let block = s.get::<Block>("blk").unwrap().unwrap();
99        assert!(s.get::<Tab>(&a.oid).unwrap().unwrap().blockids.is_empty());
100        assert_eq!(block.parentoref, "");
101        assert_eq!(block.meta.get(PARKED_META_KEY), Some(&serde_json::json!(true)));
102        assert_eq!(block.meta.get(PARKED_FROM_TAB_META_KEY), Some(&serde_json::json!(a.oid)), "it remembers its tab");
103        assert_eq!(block.meta.get("agentId"), Some(&serde_json::json!("ann")), "its meta is kept");
104
105        apply_block_attached(&s, "blk", &b.oid, 0).unwrap();
106        apply_block_attached(&s, "blk", &b.oid, 0).unwrap();
107        let block = s.get::<Block>("blk").unwrap().unwrap();
108        assert_eq!(s.get::<Tab>(&b.oid).unwrap().unwrap().blockids, vec!["blk".to_string()], "once, however often delivered");
109        assert_eq!(block.parentoref, format!("tab:{}", b.oid));
110        assert!(!block.meta.contains_key(PARKED_META_KEY));
111        assert!(!block.meta.contains_key(PARKED_FROM_TAB_META_KEY), "a block in a tab has no tab to go back to");
112    }
113
114    /// A parked block was in no tab: its delete removes the row and touches no tab.
115    #[test]
116    fn deleting_a_parked_block_removes_its_row_and_leaves_the_tabs_alone() {
117        let s = Store::open_in_memory().unwrap();
118        let ws = wcore::create_workspace(&s, "W").unwrap();
119        let a = wcore::create_tab_with_opts(&s, &ws.oid, "a", false).unwrap();
120        crate::persist_subscriber::apply_event_to_mstore(&block_created(&a.oid, "blk"), &s).unwrap();
121        apply_block_parked(&s, &a.oid, "blk").unwrap();
122
123        let deleted = Event::BlockDeleted { tab_id: String::new(), block_id: "blk".into(), version: 3 };
124        crate::persist_subscriber::apply_event_to_mstore(&deleted, &s).unwrap();
125        crate::persist_subscriber::apply_event_to_mstore(&deleted, &s).unwrap();
126        assert!(s.get::<Block>("blk").unwrap().is_none());
127        assert!(s.get::<Tab>(&a.oid).unwrap().is_some());
128    }
129}