Skip to main content

agentmux_srv/server/service/
object_helpers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! AgentMux-object read/update/meta primitives used by the `object` service
5//! handler, plus the per-agent zoom mirror. `update_object_meta` and
6//! `schedule_agent_zoom_mirror` are re-exported crate-wide.
7
8use crate::backend::obj::*;
9use crate::backend::storage::store::Store;
10
11/// Resolve an "otype:oid" string to the corresponding wave object JSON.
12pub(super) fn get_object_by_oref(store: &Store, oref_str: &str) -> Result<serde_json::Value, String> {
13    let oref = crate::backend::ORef::parse(oref_str).map_err(|e| e.to_string())?;
14
15    // Validate otype is known
16    match oref.otype.as_str() {
17        OTYPE_CLIENT | OTYPE_WINDOW | OTYPE_WORKSPACE | OTYPE_TAB | OTYPE_LAYOUT | OTYPE_BLOCK => {}
18        _ => return Err(format!("unknown otype: {}", oref.otype)),
19    }
20
21    // Use raw JSON read to avoid strict struct deserialization issues
22    // (e.g. a layout row carrying fields the struct no longer has).
23    // This matches Go's generic map-based GetObject behavior.
24    store
25        .get_raw(&oref.otype, &oref.oid)
26        .map_err(|e| e.to_string())?
27        .ok_or_else(|| format!("not found: {}", oref_str))
28}
29
30/// Update a wave object by replacing it wholesale in the store.
31/// The incoming value must have `otype` and `oid` fields.
32/// Returns (otype, oid, updated_value_with_new_version) on success.
33///
34/// Only for objects the srv reducer doesn't own: a client row, or a layout
35/// row no tab references. Workspace/tab/block/window rows are refused —
36/// a whole-row write would overwrite reducer-owned fields behind its back.
37pub(super) fn update_object(
38    store: &Store,
39    mut value: serde_json::Value,
40) -> Result<(String, String, serde_json::Value), String> {
41    let otype = value
42        .get("otype")
43        .and_then(|v| v.as_str())
44        .ok_or_else(|| "UpdateObject: missing otype field".to_string())?
45        .to_string();
46    let oid = value
47        .get("oid")
48        .and_then(|v| v.as_str())
49        .ok_or_else(|| "UpdateObject: missing oid field".to_string())?
50        .to_string();
51
52    match otype.as_str() {
53        OTYPE_CLIENT => {}
54        // A whole tree written here would overwrite the reducer's
55        // (SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md §5).
56        OTYPE_LAYOUT => {
57            return Err(
58                "UpdateObject: a layout row changes through layout intents (layout.applyIntent), not a whole-row write"
59                    .to_string(),
60            )
61        }
62        OTYPE_WINDOW | OTYPE_WORKSPACE | OTYPE_TAB | OTYPE_BLOCK => {
63            return Err(format!(
64                "UpdateObject: {otype} objects are owned by the srv reducer; \
65                 use UpdateObjectMeta or the {otype}'s own RPCs"
66            ))
67        }
68        _ => return Err(format!("UpdateObject: unsupported otype: {}", otype)),
69    }
70
71    // Use raw JSON storage (matching Go's generic map-based UpdateObject).
72    // The frontend sends the full replacement object; strict Rust struct deserialization
73    // can fail on dynamic fields (e.g. layout rootnode with embedded BlockDefs).
74    let new_version = store
75        .update_raw(&otype, &oid, &value)
76        .map_err(|e| format!("UpdateObject: {}", e))?;
77
78    // Update version in the value for the returned update event
79    if let Some(obj) = value.as_object_mut() {
80        obj.insert("version".to_string(), serde_json::json!(new_version));
81    }
82
83    Ok((otype, oid, value))
84}
85
86pub(crate) use crate::backend::wcore::object_meta::update_object_meta;
87
88/// Mirror an agent block's `term:zoom` into the per-agent `ui:zoom` content
89/// blob immediately (no debounce) so the zoom survives pane close even if the
90/// user closes the pane right after zooming. `zoom = Some(z)` upserts;
91/// `zoom = None` (term:zoom reset to null / 1.0) deletes the row so a
92/// default agent stores nothing. Writes are off-thread so the WebSocket
93/// handler stays non-blocking; SQLite serializes concurrent writes via the
94/// store mutex. See SPEC_AGENT_ZOOM_PERSISTENCE §4.3.
95pub(crate) fn schedule_agent_zoom_mirror(
96    store: std::sync::Arc<crate::backend::storage::store::Store>,
97    agent_id: String,
98    zoom: Option<f64>,
99) {
100    tokio::spawn(async move {
101        let now = chrono::Utc::now().timestamp_millis();
102        let result = match zoom {
103            Some(z) => store.agent_content_set(
104                &crate::backend::storage::store::AgentContent {
105                    agent_id: agent_id.clone(),
106                    content_type: "ui:zoom".to_string(),
107                    content: format!("{}", z),
108                    updated_at: now,
109                },
110            ),
111            None => store.agent_content_delete(&agent_id, "ui:zoom").map(|_| ()),
112        };
113        if let Err(e) = result {
114            tracing::warn!(agent_id = %agent_id, error = %e, "[zoom] agent zoom mirror write failed");
115        }
116    });
117}
118
119#[cfg(test)]
120mod agent_zoom_mirror_tests {
121    use super::schedule_agent_zoom_mirror;
122    use crate::backend::storage::store::{AgentContent, AgentDefinition, Store};
123    use std::sync::Arc;
124
125    /// `db_agent_content.agent_id` has a FK to the agent-definitions table, so a
126    /// real mirror only ever fires for an existing agent (the def was loaded at
127    /// agent.open). Seed a minimal def so the test mirrors that invariant.
128    fn seed_agent_def(store: &Store, id: &str) {
129        let mut def: AgentDefinition = serde_json::from_value(serde_json::json!({
130            "id": id,
131            "name": id,
132            "icon": "wand-magic-sparkles",
133            "provider": "claude",
134            "description": "",
135            "created_at": 1,
136        }))
137        .expect("build minimal AgentDefinition");
138        store.agent_def_insert(&mut def).expect("insert agent def");
139    }
140
141    /// Each `term:zoom` change is written immediately; last write wins.
142    #[tokio::test]
143    async fn mirror_writes_each_zoom_immediately() {
144        let store = Arc::new(Store::open_in_memory().unwrap());
145        let agent = "agent-zoom-burst";
146        seed_agent_def(&store, agent);
147
148        schedule_agent_zoom_mirror(store.clone(), agent.into(), Some(1.1));
149        schedule_agent_zoom_mirror(store.clone(), agent.into(), Some(1.4));
150
151        // Give the spawned tasks a moment to complete.
152        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
153
154        let saved = store
155            .agent_content_get(agent, "ui:zoom")
156            .unwrap()
157            .expect("zoom persisted immediately");
158        // Last write wins.
159        assert_eq!(saved.content, "1.4", "last zoom value persists");
160    }
161
162    /// `term:zoom` reset to null/1.0 → `None` → delete the saved row so a
163    /// default agent stores nothing.
164    #[tokio::test]
165    async fn reset_to_default_deletes_saved_zoom() {
166        let store = Arc::new(Store::open_in_memory().unwrap());
167        let agent = "agent-zoom-reset";
168        seed_agent_def(&store, agent);
169        store
170            .agent_content_set(&AgentContent {
171                agent_id: agent.into(),
172                content_type: "ui:zoom".into(),
173                content: "1.5".into(),
174                updated_at: 1,
175            })
176            .unwrap();
177
178        schedule_agent_zoom_mirror(store.clone(), agent.into(), None);
179        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
180
181        assert!(
182            store.agent_content_get(agent, "ui:zoom").unwrap().is_none(),
183            "reset-to-default removes the persisted zoom"
184        );
185    }
186}