Skip to main content

agentmux_srv_core/persist_subscriber/
layout_queue.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The backend-to-frontend layout action queue of a layout row.
5
6use crate::backend::obj::{LayoutActionData, LayoutState as PersistedLayoutState, Tab};
7use crate::backend::storage::store::Store;
8
9/// How many queued layout actions a row keeps: more than a window ever has
10/// left to mirror at once.
11pub(super) const QUEUE_LIMIT: usize = 32;
12
13/// How long a queued action stays: a window mirrors it within seconds of the change, and one
14/// that was asleep longer shows srv's stored tree (it compares that tree with its own whenever
15/// it is quiet), so an older action is only dead weight on every layout update.
16pub(super) const QUEUE_MAX_AGE_MS: i64 = 10 * 60 * 1000;
17
18/// Drop the actions that are older than `QUEUE_MAX_AGE_MS` at `now_ms`, and any with no queue
19/// time (queued by an older srv, so of unknown age). Returns whether it dropped any.
20pub(super) fn prune_stale(queue: &mut Vec<LayoutActionData>, now_ms: i64) -> bool {
21    let before = queue.len();
22    queue.retain(|a| a.queuedat.is_some_and(|at| now_ms.saturating_sub(at) <= QUEUE_MAX_AGE_MS));
23    queue.len() != before
24}
25
26/// A queue as a layout edit stores it: without its stale actions, and none when nothing is left.
27/// A layout edit rewrites the row, so an old queue clears the next time its tab is touched.
28pub(super) fn without_stale(queue: Option<Vec<LayoutActionData>>) -> Option<Vec<LayoutActionData>> {
29    queue
30        .map(|mut queue| {
31            prune_stale(&mut queue, agentmux_common::time::now_ms());
32            queue
33        })
34        .filter(|queue| !queue.is_empty())
35}
36
37/// SPEC_864 Phase 4 — apply a `LayoutBackendActionsQueued` event:
38/// APPEND the reducer-validated actions to
39/// `LayoutState.pendingbackendactions`, keeping the latest `QUEUE_LIMIT`.
40/// The queue only tells a window what srv already did to the tree (every
41/// queued action is applied in srv first), so the oldest can go: a window that
42/// missed one shows srv's stored tree anyway. Each action is stamped when it is queued and
43/// `prune_stale` drops the old ones, here and whenever a layout edit rewrites the row.
44///
45/// Idempotency: the event is applied twice on the happy path (sync in
46/// `queue_layout_actions_via_reducer`, again by the subscriber task
47/// consuming the broadcast), so actions whose `actionid` is already in
48/// the queue are skipped. Every writer stamps a fresh UUID per action;
49/// an (out-of-contract) empty `actionid` dedupes against other empties,
50/// which is the safe direction — skip rather than duplicate.
51pub(super) fn apply_layout_backend_actions_queued(
52    mstore: &Store,
53    tab_id: &str,
54    actions: &serde_json::Value,
55) -> Result<(), Box<dyn std::error::Error>> {
56    let Some(tab) = mstore.get::<Tab>(tab_id)? else {
57        return Ok(());
58    };
59    if tab.layoutstate.is_empty() {
60        return Ok(());
61    }
62    let Some(mut layout) = mstore.get::<PersistedLayoutState>(&tab.layoutstate)? else {
63        return Ok(());
64    };
65    let incoming: Vec<LayoutActionData> = serde_json::from_value(actions.clone())?;
66    let mut pending = layout.pendingbackendactions.take().unwrap_or_default();
67    let now = agentmux_common::time::now_ms();
68    let pruned = prune_stale(&mut pending, now);
69    let before = pending.len();
70    for mut action in incoming {
71        if !pending.iter().any(|p| p.actionid == action.actionid) {
72            action.queuedat = Some(now);
73            pending.push(action);
74        }
75    }
76    if pending.len() == before && !pruned {
77        return Ok(()); // a double-apply: no version churn
78    }
79    let excess = pending.len().saturating_sub(QUEUE_LIMIT);
80    pending.drain(..excess);
81    layout.pendingbackendactions = Some(pending).filter(|queue| !queue.is_empty());
82    mstore.update(&mut layout)?;
83    Ok(())
84}
85
86#[cfg(test)]
87mod tests {
88    use agentmux_common::ipc::Event;
89
90    use super::*;
91    use crate::persist_subscriber::apply_event_to_mstore;
92
93    fn action(id: &str, queuedat: Option<i64>) -> LayoutActionData {
94        LayoutActionData { actiontype: "delete".into(), actionid: id.into(), blockid: "b".into(), queuedat, ..Default::default() }
95    }
96
97    #[test]
98    fn prune_stale_drops_old_and_undated_actions_and_keeps_fresh_ones() {
99        let now = 10_000_000;
100        let mut queue = vec![
101            action("old", Some(now - QUEUE_MAX_AGE_MS - 1)),
102            action("undated", None),
103            action("edge", Some(now - QUEUE_MAX_AGE_MS)),
104            action("fresh", Some(now - 1000)),
105        ];
106        assert!(prune_stale(&mut queue, now));
107        let ids: Vec<&str> = queue.iter().map(|a| a.actionid.as_str()).collect();
108        assert_eq!(ids, ["edge", "fresh"]);
109        assert!(!prune_stale(&mut queue, now), "nothing left to drop");
110    }
111
112    #[test]
113    fn a_queued_action_is_stamped_and_the_legacy_ones_go() {
114        let s = Store::open_in_memory().expect("in-memory mstore");
115        apply_event_to_mstore(&Event::WorkspaceCreated { workspace_id: "ws".into(), name: "W".into(), version: 1 }, &s).unwrap();
116        apply_event_to_mstore(&Event::TabCreated { workspace_id: "ws".into(), tab_id: "tab".into(), name: "T".into(), version: 2 }, &s).unwrap();
117        // A queue an older srv left: undated, and never drained.
118        let tab = s.get::<Tab>("tab").unwrap().unwrap();
119        let mut layout = s.get::<PersistedLayoutState>(&tab.layoutstate).unwrap().unwrap();
120        layout.pendingbackendactions = Some((0..QUEUE_LIMIT).map(|i| action(&format!("legacy{i}"), None)).collect());
121        s.update(&mut layout).unwrap();
122
123        let ev = Event::LayoutBackendActionsQueued {
124            tab_id: "tab".into(),
125            actions: serde_json::to_value(vec![action("new", None)]).unwrap(),
126            correlation_id: String::new(),
127            version: 3,
128        };
129        apply_event_to_mstore(&ev, &s).unwrap();
130        let queue = s.get::<PersistedLayoutState>(&tab.layoutstate).unwrap().unwrap().pendingbackendactions.unwrap();
131        assert_eq!(queue.len(), 1, "the undated legacy queue is gone");
132        assert_eq!(queue[0].actionid, "new");
133        assert!(queue[0].queuedat.is_some(), "srv stamps the action when it queues it");
134    }
135
136    #[test]
137    fn a_layout_edit_drops_the_stale_actions_and_keeps_the_fresh_ones() {
138        let s = Store::open_in_memory().expect("in-memory mstore");
139        apply_event_to_mstore(&Event::WorkspaceCreated { workspace_id: "ws".into(), name: "W".into(), version: 1 }, &s).unwrap();
140        apply_event_to_mstore(&Event::TabCreated { workspace_id: "ws".into(), tab_id: "tab".into(), name: "T".into(), version: 2 }, &s).unwrap();
141        let tab = s.get::<Tab>("tab").unwrap().unwrap();
142        let now = agentmux_common::time::now_ms();
143        let mut layout = s.get::<PersistedLayoutState>(&tab.layoutstate).unwrap().unwrap();
144        layout.pendingbackendactions =
145            Some(vec![action("legacy", None), action("old", Some(now - QUEUE_MAX_AGE_MS - 1000)), action("fresh", Some(now))]);
146        s.update(&mut layout).unwrap();
147
148        // A tree-only edit rewrites the row (slices: None), and its queue with it.
149        let edit = Event::LayoutTreeReplaced {
150            tab_id: "tab".into(),
151            new_tree: Some(agentmux_common::LayoutNode { id: "n1".into(), ..Default::default() }),
152            correlation_id: "c".into(),
153            slices: None,
154            version: 3,
155        };
156        apply_event_to_mstore(&edit, &s).unwrap();
157        let queue = s.get::<PersistedLayoutState>(&tab.layoutstate).unwrap().unwrap().pendingbackendactions.unwrap();
158        assert_eq!(queue.iter().map(|a| a.actionid.as_str()).collect::<Vec<_>>(), ["fresh"]);
159    }
160
161    #[test]
162    fn without_stale_stores_an_emptied_queue_as_none() {
163        assert_eq!(without_stale(Some(vec![action("undated", None)])), None);
164        assert_eq!(without_stale(None), None);
165    }
166
167    #[test]
168    fn the_queue_keeps_the_latest_actions() {
169        let s = Store::open_in_memory().expect("in-memory mstore");
170        apply_event_to_mstore(&Event::WorkspaceCreated { workspace_id: "ws".into(), name: "W".into(), version: 1 }, &s).unwrap();
171        let created = Event::TabCreated { workspace_id: "ws".into(), tab_id: "tab".into(), name: "T".into(), version: 2 };
172        apply_event_to_mstore(&created, &s).unwrap();
173        for i in 0..QUEUE_LIMIT + 8 {
174            let action = LayoutActionData { actiontype: "delete".into(), actionid: format!("a{i}"), blockid: "b".into(), ..Default::default() };
175            let ev = Event::LayoutBackendActionsQueued {
176                tab_id: "tab".into(),
177                actions: serde_json::to_value(vec![action]).unwrap(),
178                correlation_id: String::new(),
179                version: 3 + i as u64,
180            };
181            apply_event_to_mstore(&ev, &s).unwrap();
182        }
183        let tab = s.get::<Tab>("tab").unwrap().unwrap();
184        let queue = s.get::<PersistedLayoutState>(&tab.layoutstate).unwrap().unwrap().pendingbackendactions.unwrap();
185        assert_eq!(queue.len(), QUEUE_LIMIT);
186        assert_eq!(queue.first().map(|a| a.actionid.as_str()), Some("a8"));
187        assert_eq!(queue.last().map(|a| a.actionid.as_str()), Some(format!("a{}", QUEUE_LIMIT + 7).as_str()));
188    }
189}