Skip to main content

agentmux_srv/server/service/
reducer_helpers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Phase E.2c.2 reducer-dispatch helpers shared by the service handlers and
5//! (via `crate::server::service::…`) the sagas.
6
7use crate::backend::obj::Workspace;
8use crate::backend::storage::store::Store;
9use crate::backend::storage::StoreError;
10
11use super::super::AppState;
12
13/// Dispatch a command into the srv reducer and return the emitted
14/// events. Locks the reducer mutex briefly; the lock is released
15/// before any I/O (caller is responsible for publishing the events
16/// to the broadcast bus).
17pub(crate) async fn dispatch_to_reducer(
18    state: &AppState,
19    cmd: agentmux_common::ipc::Command,
20) -> Vec<agentmux_common::ipc::Event> {
21    dispatch_to_reducer_timed(state, cmd).await.0
22}
23
24/// Where a reducer dispatch spent its time: waiting for the reducer
25/// mutex (another command held it), and running the reducer itself.
26pub(crate) struct ReducerTiming {
27    pub lock_wait: std::time::Duration,
28    pub reducer: std::time::Duration,
29}
30
31/// [`dispatch_to_reducer`] that also says how long it waited for the
32/// reducer mutex and how long the reducer took. Used where a slow call
33/// has to be told apart as queue wait, reducer or persist (#47767).
34pub(crate) async fn dispatch_to_reducer_timed(
35    state: &AppState,
36    cmd: agentmux_common::ipc::Command,
37) -> (Vec<agentmux_common::ipc::Event>, ReducerTiming) {
38    let wait_start = std::time::Instant::now();
39    let mut s = state.srv_state.lock().await;
40    let lock_wait = wait_start.elapsed();
41    let ctx = crate::reducer::Ctx::new(None);
42    let run_start = std::time::Instant::now();
43    let events = crate::reducer::update(&mut s, cmd, &ctx);
44    let reducer = run_start.elapsed();
45    (events, ReducerTiming { lock_wait, reducer })
46}
47
48/// Publish each event on the srv broadcast bus. Failures (no
49/// subscribers) are non-fatal.
50pub(crate) fn publish_events(state: &AppState, events: &[agentmux_common::ipc::Event]) {
51    for event in events {
52        let _ = state.srv_events_tx.send(event.clone());
53    }
54}
55
56/// Run a command that creates a block and return the new block's id: the reducer's refusal is the error, the events
57/// are written to the store (a write that fails is logged and the open goes on, as every caller did) and published.
58/// Each caller keeps its own words: a refusal reads "`refused`: <the reducer's message>", a reducer that answered
59/// without a block "`missing` emitted no BlockCreated", and a failed write is logged as "`apply` mstore apply failed".
60pub(crate) async fn create_via_reducer(
61    state: &AppState,
62    cmd: agentmux_common::ipc::Command,
63    refused: &str,
64    missing: &str,
65    apply: &str,
66) -> Result<String, String> {
67    use agentmux_common::ipc::Event;
68    let events = dispatch_to_reducer(state, cmd).await;
69    if let Some(msg) = events.iter().find_map(|e| match e {
70        Event::Error { message, .. } => Some(message.clone()),
71        _ => None,
72    }) {
73        return Err(format!("{refused}: {msg}"));
74    }
75    let block_id = events
76        .iter()
77        .find_map(|e| match e {
78            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
79            _ => None,
80        })
81        .ok_or_else(|| format!("{missing} emitted no BlockCreated"))?;
82    for ev in &events {
83        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
84            tracing::warn!("{apply} mstore apply failed: {e}");
85        }
86    }
87    publish_events(state, &events);
88    Ok(block_id)
89}
90
91/// A new block in `tab_id` with `meta`, through the reducer (never the store alone: a block the reducer does not
92/// know cannot be torn off or redocked later). `caller` starts its messages ("pane.open", "agent.open"), followed by
93/// ": CreateBlock". The block has no place in the layout yet: placing it is the caller's next step.
94pub(crate) async fn create_block_in_tab(state: &AppState, tab_id: &str, meta: serde_json::Value, caller: &str) -> Result<String, String> {
95    let what = format!("{caller}: CreateBlock");
96    let cmd = agentmux_common::ipc::Command::CreateBlock { tab_id: tab_id.to_string(), meta };
97    create_via_reducer(state, cmd, &what, &what, &what).await
98}
99
100/// Compensation helper: dispatch a command into the reducer and
101/// apply its emitted events to mstore best-effort. Used when an
102/// earlier sync apply partially wrote SQLite and we need to undo
103/// the leaked rows. SQLite errors during compensation are logged
104/// but ignored — the caller is already returning an error to the
105/// client; throwing on the cleanup just hides the original cause.
106/// (codex P1 + reagent P2 #616 — partial-write cleanup.)
107pub(crate) async fn compensate_via_reducer(
108    state: &AppState,
109    cmd: agentmux_common::ipc::Command,
110    store: &Store,
111) {
112    let events = dispatch_to_reducer(state, cmd).await;
113    for ev in &events {
114        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
115            tracing::warn!(
116                "compensation: SQLite cleanup failed for event {:?}: {}",
117                std::mem::discriminant(ev),
118                e
119            );
120        }
121    }
122}
123
124/// SPEC_864 Phase 3 — single-writer layout seeding. Dispatch a
125/// `LayoutSetTree` (tree + focus as client slices) and persist
126/// it inside ONE hold of the reducer mutex, so persist order equals
127/// dispatch order — the same contract as `apply_layout_intent`
128/// (`layout_intents.rs`). Replaces the wcore-direct seeders
129/// (`write_default_three_pane_layout` post-bootstrap caller,
130/// `setup_torn_off_block_layout`): the reducer's `TabRecord.rootnode` is
131/// authoritative, and the persist subscriber is the sole `db_layout`
132/// writer on this path.
133///
134/// On SQLite apply failure the reducer is rolled back to an empty tree
135/// (the seed target is a fresh tab whose row was empty) inside the same
136/// lock hold. Publishes events on success. Requires the tab to be known
137/// to the reducer — true for every caller (all run after reducer-routed
138/// CreateTab / sagas); the pre-bootstrap first-launch seed
139/// (`ensure_initial_data` → `seed_default_layout`) deliberately stays
140/// store-direct because the reducer isn't hydrated yet (spec site #3).
141pub(crate) async fn seed_layout_via_reducer(
142    state: &AppState,
143    tab_id: &str,
144    new_tree: agentmux_common::LayoutNode,
145    focused_node_id: String,
146    magnified_node_id: String,
147) -> Result<(), String> {
148    let store = &state.mstore;
149    let slices = agentmux_common::LayoutClientSlices {
150        focused_node_id,
151        magnified_node_id,
152        // Fresh-tab seed: REPLACE semantics clear any stale queue.
153        pending_backend_actions: None,
154    };
155    let cmd = agentmux_common::ipc::Command::LayoutSetTree {
156        tab_id: tab_id.to_string(),
157        new_tree: Some(new_tree),
158        correlation_id: String::new(),
159        slices: Some(slices),
160    };
161
162    let mut apply_err: Option<String> = None;
163    let events = {
164        let mut s = state.srv_state.lock().await;
165        let ctx = crate::reducer::Ctx::new(None);
166        let events = crate::reducer::update(&mut s, cmd, &ctx);
167        let has_error = events
168            .iter()
169            .any(|e| matches!(e, agentmux_common::ipc::Event::Error { .. }));
170        if !has_error {
171            for ev in &events {
172                if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
173                    apply_err = Some(e.to_string());
174                    break;
175                }
176            }
177            if apply_err.is_some() {
178                // Roll the reducer back to the empty pre-seed tree inside
179                // the same lock hold; best-effort SQLite mirror.
180                let rollback = agentmux_common::ipc::Command::LayoutSetTree {
181                    tab_id: tab_id.to_string(),
182                    new_tree: None,
183                    correlation_id: String::new(),
184                    slices: Some(agentmux_common::LayoutClientSlices::default()),
185                };
186                let rb_events = crate::reducer::update(&mut s, rollback, &ctx);
187                for ev in &rb_events {
188                    if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
189                        tracing::warn!(
190                            error = %e,
191                            "seed_layout_via_reducer: rollback SQLite mirror failed"
192                        );
193                    }
194                }
195            }
196        }
197        events
198    };
199
200    if let Some(err_msg) = events.iter().find_map(|e| match e {
201        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
202        _ => None,
203    }) {
204        return Err(err_msg);
205    }
206    if let Some(err) = apply_err {
207        return Err(format!("layout seed SQLite write failed: {}", err));
208    }
209    publish_events(state, &events);
210    Ok(())
211}
212
213/// SPEC_864 Phase 4 — single-writer queue append. Dispatch a
214/// `LayoutQueueBackendActions` and persist the resulting
215/// `LayoutBackendActionsQueued` inside ONE hold of the reducer mutex
216/// (same critical-section contract as `seed_layout_via_reducer`), so
217/// queue writes land in dispatch order. Replaces the five
218/// store-direct `pendingbackendactions` writers (`layout_helpers`'
219/// insert/split/delete queuers + the two inline app_api sites).
220///
221/// The reducer does not model the queue in `TabRecord` (pass-through
222/// validation only).
223///
224/// `actions` must be non-empty; the reducer rejects an empty array.
225pub(crate) async fn queue_layout_actions_via_reducer(
226    state: &AppState,
227    tab_id: &str,
228    actions: Vec<crate::backend::obj::LayoutActionData>,
229) -> Result<(), String> {
230    let store = &state.mstore;
231    let actions_json = serde_json::to_value(&actions)
232        .map_err(|e| format!("queue actions serialize failed: {}", e))?;
233    let cmd = agentmux_common::ipc::Command::LayoutQueueBackendActions {
234        tab_id: tab_id.to_string(),
235        actions: actions_json,
236        correlation_id: String::new(),
237    };
238
239    let mut apply_err: Option<String> = None;
240    let events = {
241        let mut s = state.srv_state.lock().await;
242        let ctx = crate::reducer::Ctx::new(None);
243        let events = crate::reducer::update(&mut s, cmd, &ctx);
244        let has_error = events
245            .iter()
246            .any(|e| matches!(e, agentmux_common::ipc::Event::Error { .. }));
247        if !has_error {
248            for ev in &events {
249                if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
250                    apply_err = Some(e.to_string());
251                    break;
252                }
253            }
254        }
255        events
256    };
257
258    if let Some(err_msg) = events.iter().find_map(|e| match e {
259        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
260        _ => None,
261    }) {
262        return Err(err_msg);
263    }
264    if let Some(err) = apply_err {
265        return Err(format!("queue append SQLite write failed: {}", err));
266    }
267    publish_events(state, &events);
268    Ok(())
269}
270
271/// Existence check used by `DeleteWorkspace` to decide whether to
272/// run the wcore delete path. Propagates `StoreError` so the caller
273/// can surface real I/O / corruption failures instead of
274/// misclassifying them as "not found" (codex P2 #615 carryover —
275/// the prior `bool` return collapsed `Err(_)` into `false`, which
276/// led to silent successes when SQLite was unhealthy: reducer would
277/// delete its own copy and report success while the disk row was
278/// never touched).
279pub(crate) fn mstore_workspace_exists(
280    store: &Store,
281    workspace_id: &str,
282) -> Result<bool, StoreError> {
283    Ok(store.get::<Workspace>(workspace_id)?.is_some())
284}
285
286// `build_workspace_from_state` removed in E.2c.2. The reducer's
287// WorkspaceRecord can't faithfully render a Workspace during the
288// migration window (no pinnedtabids; tabids/activetabid go stale
289// vs wcore-direct tab ops). It will be reintroduced in E.2c.3
290// when tabs migrate into the reducer and pinned/active state is
291// authoritative there. (reagent + codex P1 #615.)