Skip to main content

agentmux_srv/server/service/
object_methods.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The `object` service's methods, one function each. A method answers `Ok` with its reply, or
5//! `Err` with the reply that ends the call early (a bad argument, a refusal).
6
7#![allow(clippy::result_large_err)]
8
9use agentmux_common::ipc::{Command, Event};
10
11use crate::backend::obj::*;
12use crate::backend::service::{self, WebCallType, WebReturnType};
13use crate::server::AppState;
14
15use super::super::object_helpers::{
16    get_object_by_oref, schedule_agent_zoom_mirror, update_object, update_object_meta,
17};
18use super::super::reducer_helpers::{compensate_via_reducer, dispatch_to_reducer, publish_events};
19
20type Reply = Result<WebReturnType, WebReturnType>;
21
22/// The argument at `idx`, or the reply that refuses the call for it.
23fn arg<T: serde::de::DeserializeOwned>(args: &[serde_json::Value], idx: usize) -> Result<T, WebReturnType> {
24    service::get_arg(args, idx).map_err(WebReturnType::error)
25}
26
27/// The message of the first `Error` event the reducer emitted, if any.
28fn reducer_error(events: &[Event]) -> Option<String> {
29    events.iter().find_map(|e| match e {
30        Event::Error { message, .. } => Some(message.clone()),
31        _ => None,
32    })
33}
34
35/// Writes each event the reducer emitted to the store, stopping at the first failure.
36fn apply_events(state: &AppState, events: &[Event]) -> Result<(), String> {
37    for ev in events {
38        crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).map_err(|e| e.to_string())?;
39    }
40    Ok(())
41}
42
43fn row_update(otype: &str, oid: &str, obj: serde_json::Value) -> MuxObjUpdate {
44    MuxObjUpdate { updatetype: "update".into(), otype: otype.to_string(), oid: oid.to_string(), obj: Some(obj) }
45}
46
47pub(super) fn get_object(state: &AppState, args: &[serde_json::Value]) -> Reply {
48    let oref_str: String = arg(args, 0)?;
49    match get_object_by_oref(&state.mstore, &oref_str) {
50        Ok(data) => Ok(WebReturnType::success(data)),
51        Err(e) => Ok(WebReturnType::error(e)),
52    }
53}
54
55pub(super) fn get_objects(state: &AppState, args: &[serde_json::Value]) -> Reply {
56    let orefs: Vec<String> = arg(args, 0)?;
57    let mut results = Vec::new();
58    for oref_str in &orefs {
59        match get_object_by_oref(&state.mstore, oref_str) {
60            Ok(data) => results.push(data),
61            Err(_) => results.push(serde_json::Value::Null),
62        }
63    }
64    Ok(WebReturnType::success(serde_json::json!(results)))
65}
66
67/// The tab a `CreateBlock` call targets: an explicit `tabId` argument, else the context's active tab.
68fn create_block_tab(call: &WebCallType) -> Result<String, WebReturnType> {
69    // Optional explicit tab_id at args[2] (args[1] is rtOpts).
70    // When present, overrides uicontext.active_tab_id — lets
71    // callers like applyTabPreset (frontend) target a specific
72    // tab without depending on which tab happens to be active
73    // when the RPC's uicontext is serialised. Eliminates the
74    // TOCTOU race where the user can switch tabs between the
75    // call site and the server-side handler.
76    //
77    // A *malformed* args[2] (e.g. non-string from a stale SDK)
78    // returns an error — silently falling back to uicontext
79    // would defeat the explicit-targeting contract and make
80    // wrong-tab routing hard to diagnose. Missing/null/empty
81    // is fine: treat as "no override" and use uicontext.
82    let explicit_tab_id: Option<String> = match service::get_optional_arg::<String>(&call.args, 2) {
83        Ok(opt) => opt.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()),
84        Err(e) => return Err(WebReturnType::error(format!("invalid tabId arg: {}", e))),
85    };
86    match explicit_tab_id {
87        Some(id) => Ok(id),
88        None => match call.uicontext.as_ref().map(|ctx| ctx.active_tab_id.clone()) {
89            Some(id) if !id.is_empty() => Ok(id),
90            _ => Err(WebReturnType::error("missing uicontext.activetabid")),
91        },
92    }
93}
94
95pub(super) async fn create_block(state: &AppState, call: &WebCallType) -> Reply {
96    let store = &state.mstore;
97    let mut block_def: BlockDef = arg(&call.args, 0)?;
98    crate::server::browser_owner::strip_srv_only_keys(&mut block_def.meta);
99    if let Err(e) = crate::server::browser_identity::check_new_tab(state, &block_def.meta) {
100        return Err(WebReturnType::error(e));
101    }
102    let tab_id = create_block_tab(call)?;
103    // Phase E.2c.4 — CreateBlock dispatches through the reducer
104    // (forward+compensate on SQLite failure). The reducer
105    // assigns the block_id; the persist subscriber's apply
106    // path writes the Block row with the caller's meta map.
107    let meta_value = serde_json::to_value(&block_def.meta).unwrap_or(serde_json::Value::Null);
108    let events = dispatch_to_reducer(state, Command::CreateBlock { tab_id: tab_id.clone(), meta: meta_value }).await;
109    // Surface reducer Error events (tab not found).
110    if let Some(err_msg) = reducer_error(&events) {
111        return Err(WebReturnType::error(err_msg));
112    }
113    let block_id = events.iter().find_map(|e| match e {
114        Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
115        _ => None,
116    });
117    if let Err(err) = apply_events(state, &events) {
118        if let Some(bid) = block_id.as_ref() {
119            compensate_via_reducer(
120                state,
121                Command::DeleteBlock { tab_id: tab_id.clone(), block_id: bid.clone() },
122                store,
123            )
124            .await;
125        }
126        return Err(WebReturnType::error(format!("CreateBlock: SQLite write failed: {}", err)));
127    }
128    publish_events(state, &events);
129    match block_id {
130        Some(bid) => {
131            let mut updates = vec![];
132            if let Ok(block) = store.must_get::<Block>(&bid) {
133                updates.push(row_update(OTYPE_BLOCK, &bid, mux_obj_to_value(&block)));
134            }
135            if let Ok(tab) = store.must_get::<Tab>(&tab_id) {
136                updates.push(row_update(OTYPE_TAB, &tab_id, mux_obj_to_value(&tab)));
137            }
138            Ok(WebReturnType::success_data_updates(serde_json::json!(bid), updates))
139        }
140        None => Err(WebReturnType::error("CreateBlock: reducer did not emit BlockCreated".to_string())),
141    }
142}
143
144// Phase E.5.7 (Step 5 PR 1) — DeleteBlock saga. The legacy
145// SQLite-first pattern (wcore::delete_block + reducer-sync
146// dispatch) is replaced by `sagas::delete_block::run`, which
147// routes through the reducer + persist subscriber. The saga
148// also handles the controller-kill cascade (matches the old
149// ordering: controller down → reducer dispatch → SQLite).
150pub(super) async fn delete_block(state: &AppState, args: &[serde_json::Value]) -> Reply {
151    let block_id: String = arg(args, 0)?;
152    // Look up the block's owning tab from server state rather than using
153    // uicontext.active_tab_id. Floating pane windows have their own tab
154    // context that differs from the block's owning tab, so using the
155    // uicontext tab always fails for floating-pane closes.
156    let tab_id = {
157        let s = state.srv_state.lock().await;
158        match s.blocks.get(&block_id) {
159            Some(rec) => rec.tab_id.clone(),
160            None => return Err(WebReturnType::error(format!("DeleteBlock: block not found: {}", block_id))),
161        }
162    };
163    if let Err(reason) = crate::sagas::delete_block::run(state, tab_id, block_id).await {
164        return Err(WebReturnType::error(reason));
165    }
166    Ok(WebReturnType::success_empty())
167}
168
169// `/shutdown` (`/quit`, `/exit`) and Shut down are the person's own choices, made in the window over its websocket
170// (`app_api::agent_quit`). A request on this route proves nothing about who made it, so it is handled as an agent's
171// `Agents stop` is: the person is shown who asked and can keep the agent running; nothing is recorded as their
172// own slash or menu action. The reply carries the pending request. (`ShutdownAgent`'s background-tasks answer is
173// the person's and is not taken from here.) What may be asked, and how often, is `stop_requests`.
174pub(super) fn quit_agent(state: &AppState, args: &[serde_json::Value], caller_uid: Option<&str>) -> Reply {
175    let block_id: String = arg(args, 0)?;
176    super::super::stop_requests::ask_the_person_to_stop(state, &block_id, caller_uid, "QuitAgent")
177}
178
179pub(super) fn shutdown_agent(state: &AppState, args: &[serde_json::Value], caller_uid: Option<&str>) -> Reply {
180    let block_id: String = arg(args, 0)?;
181    super::super::stop_requests::ask_the_person_to_stop(state, &block_id, caller_uid, "ShutdownAgent")
182}
183
184// What a shutdown would end, for the confirm; nothing is ended. A request carrying an agent's token is answered for
185// that agent's own pane only (`stop_requests::own_pane_only`).
186pub(super) async fn shutdown_preview(state: &AppState, args: &[serde_json::Value], caller_uid: Option<&str>) -> Reply {
187    let block_id: String = arg(args, 0)?;
188    super::super::stop_requests::own_pane_only(state, &block_id, caller_uid, "ShutdownPreview")?;
189    let preview = crate::sagas::self_quit::preview(state, &block_id).await;
190    Ok(WebReturnType::success(serde_json::to_value(&preview).unwrap_or_default()))
191}
192
193// A pane's × — every block in the pane's stack, stopped before its
194// records are deleted (SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md).
195// Closing one tab of a stack sends that one id; the saga keeps the
196// pane when other members survive.
197pub(super) async fn close_pane(state: &AppState, args: &[serde_json::Value]) -> Reply {
198    let block_ids: Vec<String> = arg(args, 0)?;
199    // Optional: the frontend kept the pane on screen to show the
200    // shutdown log (SPEC_AGENT_SELF_QUIT_2026_09_24.md §5.5), so srv
201    // removes it member by member. Absent = the historical flow.
202    let frontend_waits: bool = service::get_arg(args, 1).unwrap_or(false);
203    let opts = crate::sagas::close_pane::CloseOpts { frontend_waits, ..Default::default() };
204    if let Err(reason) = crate::sagas::close_pane::run_with(state, block_ids, opts).await {
205        return Err(WebReturnType::error(reason));
206    }
207    Ok(WebReturnType::success_empty())
208}
209
210// `layout.applyIntent` for callers outside a window's websocket (the
211// tools/tests harnesses): the same srv edit, the same stored row.
212pub(super) async fn apply_layout_intent(state: &AppState, args: &[serde_json::Value]) -> Reply {
213    let tab_id: String = arg(args, 0)?;
214    let intent: agentmux_common::LayoutIntent = arg(args, 1)?;
215    let action_id: String = arg(args, 2)?;
216    match super::super::layout_intents::apply_layout_intent(state, &tab_id, intent, &action_id, None).await {
217        Ok(outcome) => Ok(WebReturnType::success(serde_json::json!({
218            "applied": outcome.applied,
219            "error": outcome.error,
220            "version": outcome.version,
221        }))),
222        Err(e) => Ok(WebReturnType::error(e)),
223    }
224}
225
226pub(super) fn update_object_row(state: &AppState, args: &[serde_json::Value]) -> Reply {
227    let mux_obj_value: serde_json::Value = arg(args, 0)?;
228    // Whole-row replace, only for the client row: every other row is
229    // the reducer's (`update_object` says which RPCs change it).
230    match update_object(&state.mstore, mux_obj_value) {
231        Ok((otype, oid, obj_val)) => {
232            let update = MuxObjUpdate { updatetype: "update".into(), otype, oid, obj: Some(obj_val) };
233            Ok(WebReturnType::success_with_updates(vec![update]))
234        }
235        Err(e) => Ok(WebReturnType::error(e)),
236    }
237}
238
239/// The reducer command that patches the meta of the object `oref` names, or `None` for an object
240/// type the reducer doesn't own.
241fn meta_command(oref: &crate::backend::ORef, meta_value: serde_json::Value) -> Option<Command> {
242    Some(match oref.otype.as_str() {
243        t if t == OTYPE_WORKSPACE => Command::UpdateWorkspaceMeta { workspace_id: oref.oid.clone(), meta_patch: meta_value },
244        t if t == OTYPE_TAB => Command::UpdateTabMeta { tab_id: oref.oid.clone(), meta_patch: meta_value },
245        t if t == OTYPE_BLOCK => Command::UpdateBlockMeta { block_id: oref.oid.clone(), meta_patch: meta_value },
246        t if t == OTYPE_WINDOW => Command::UpdateWindowMeta { window_id: oref.oid.clone(), meta_patch: meta_value },
247        _ => return None,
248    })
249}
250
251/// Per-agent zoom persistence (SPEC_AGENT_ZOOM_PERSISTENCE): when an
252/// agent block's `term:zoom` changes, mirror it (debounced) into the
253/// agent's per-agent `ui:zoom` content so the zoom survives the block
254/// and is restored at `agent.open`. Only blocks carrying `agentId`
255/// (agent panes) participate; everything else is untouched. A `null`
256/// `term:zoom` (the frontend's reset-to-1.0 convention) deletes the
257/// saved value so a default agent stores nothing.
258fn mirror_agent_zoom(state: &AppState, oref: &crate::backend::ORef, meta_update: &MetaMapType) {
259    if oref.otype == OTYPE_BLOCK && meta_update.contains_key("term:zoom") {
260        if let Ok(block) = state.mstore.must_get::<Block>(&oref.oid) {
261            let agent_id = block.meta.get("agentId").and_then(|v| v.as_str()).unwrap_or("").to_string();
262            if !agent_id.is_empty() {
263                let zoom = meta_update.get("term:zoom").and_then(|v| v.as_f64());
264                schedule_agent_zoom_mirror(state.mstore.clone(), agent_id, zoom);
265            }
266        }
267    }
268}
269
270/// The reply that returns the updated block or tab so the frontend MOS cache stays in sync.
271fn updated_row_reply(state: &AppState, oref: &crate::backend::ORef) -> WebReturnType {
272    if oref.otype == OTYPE_BLOCK {
273        if let Ok(block) = state.mstore.must_get::<Block>(&oref.oid) {
274            return WebReturnType::success_with_updates(vec![row_update(OTYPE_BLOCK, &oref.oid, mux_obj_to_value(&block))]);
275        }
276    }
277    if oref.otype == OTYPE_TAB {
278        if let Ok(tab) = state.mstore.must_get::<Tab>(&oref.oid) {
279            return WebReturnType::success_with_updates(vec![row_update(OTYPE_TAB, &oref.oid, mux_obj_to_value(&tab))]);
280        }
281    }
282    WebReturnType::success_empty()
283}
284
285// Phase E.5.3 — UpdateObjectMeta migrated through the
286// reducer. Decomposes by otype to the typed Update*Meta
287// command. Reducer is pass-through (validates entity exists;
288// emits event); subscriber's apply_*_meta_updated does the
289// shallow merge against mstore.
290pub(super) async fn update_object_meta_patch(state: &AppState, args: &[serde_json::Value]) -> Reply {
291    let oref_str: String = arg(args, 0)?;
292    let meta_update: MetaMapType = arg(args, 1)?;
293    let oref = match crate::backend::ORef::parse(&oref_str) {
294        Ok(v) => v,
295        Err(e) => return Err(WebReturnType::error(e.to_string())),
296    };
297    if let Err(e) = crate::server::browser_owner::guard_client_meta_write(&oref_str, &meta_update) {
298        return Err(WebReturnType::error(e));
299    }
300    let meta_value = serde_json::to_value(&meta_update).unwrap_or(serde_json::Value::Null);
301    let Some(cmd) = meta_command(&oref, meta_value) else {
302        // Remaining otypes (Layout, Client, Temp) aren't
303        // meta-mutated via the reducer yet; fall back to
304        // wcore for forward-compat. They publish no event,
305        // so the MuxObjUpdate bridge can't see them — the
306        // frontend cache stays stale until next bootstrap
307        // (deemed acceptable since these aren't user-edited).
308        // Future Phase E.5.x migrations can add reducer arms
309        // for any of these following the OTYPE_WINDOW pattern
310        // in `meta_command` (per issue #855 retro).
311        return match update_object_meta(&state.mstore, &oref_str, &meta_update) {
312            Ok(()) => Ok(WebReturnType::success_empty()),
313            Err(e) => Ok(WebReturnType::error(format!(
314                "UpdateObjectMeta: unsupported otype {} via reducer; wcore fallback failed: {}",
315                oref.otype, e
316            ))),
317        };
318    };
319    let events = dispatch_to_reducer(state, cmd).await;
320    if let Some(err_msg) = reducer_error(&events) {
321        return Err(WebReturnType::error(err_msg));
322    }
323    if let Err(e) = apply_events(state, &events) {
324        return Err(WebReturnType::error(format!("UpdateObjectMeta: SQLite write failed: {}", e)));
325    }
326    publish_events(state, &events);
327    mirror_agent_zoom(state, &oref, &meta_update);
328    Ok(updated_row_reply(state, &oref))
329}
330
331// Phase E.5.3 — UpdateTabName migrated through the reducer.
332pub(super) async fn update_tab_name(state: &AppState, args: &[serde_json::Value]) -> Reply {
333    let tab_id: String = arg(args, 0)?;
334    let name: String = arg(args, 1)?;
335    let events = dispatch_to_reducer(state, Command::RenameTab { tab_id: tab_id.clone(), name }).await;
336    if let Some(err_msg) = reducer_error(&events) {
337        return Err(WebReturnType::error(err_msg));
338    }
339    if let Err(e) = apply_events(state, &events) {
340        return Err(WebReturnType::error(format!("UpdateTabName: SQLite write failed: {}", e)));
341    }
342    publish_events(state, &events);
343    if let Ok(updated_tab) = state.mstore.must_get::<Tab>(&tab_id) {
344        return Ok(WebReturnType::success_with_updates(vec![row_update(OTYPE_TAB, &tab_id, mux_obj_to_value(&updated_tab))]));
345    }
346    Ok(WebReturnType::success_empty())
347}