Skip to main content

agentmux_srv_core/backend/
obj.rs

1// Copyright 2025, Command Line Inc.
2// Copyright 2025-2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! StoreObj types: Rust equivalents of Go structs from pkg/obj/wtype.go.
6//! All `#[serde(rename = "...")]` tags match Go JSON tags for wire compatibility.
7
8
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12use super::oref::ORef;
13
14// ---- Custom serde for MetaMapType ----
15// Go serializes nil maps as `null` and initialized maps as `{}`.
16// Rust's HashMap is always initialized (empty = `{}`), so we need
17// to serialize empty HashMap as `null` to match Go's wire format.
18// We also need to accept `null` on deserialization (from DB or network).
19fn serialize_meta_as_null_if_empty<S>(meta: &MetaMapType, serializer: S) -> Result<S::Ok, S::Error>
20where
21    S: serde::Serializer,
22{
23    if meta.is_empty() {
24        serializer.serialize_none()
25    } else {
26        meta.serialize(serializer)
27    }
28}
29
30fn deserialize_meta_or_null<'de, D>(deserializer: D) -> Result<MetaMapType, D::Error>
31where
32    D: serde::Deserializer<'de>,
33{
34    Option::<MetaMapType>::deserialize(deserializer).map(|opt| opt.unwrap_or_default())
35}
36
37// ---- OType constants (match Go's obj.OType_* constants) ----
38
39pub const OTYPE_CLIENT: &str = "client";
40pub const OTYPE_WINDOW: &str = "window";
41pub const OTYPE_WORKSPACE: &str = "workspace";
42pub const OTYPE_TAB: &str = "tab";
43pub const OTYPE_LAYOUT: &str = "layout";
44pub const OTYPE_BLOCK: &str = "block";
45pub const OTYPE_TEMP: &str = "temp";
46
47pub const VALID_OTYPES: &[&str] = &[
48    OTYPE_CLIENT,
49    OTYPE_WINDOW,
50    OTYPE_WORKSPACE,
51    OTYPE_TAB,
52    OTYPE_LAYOUT,
53    OTYPE_BLOCK,
54    OTYPE_TEMP,
55];
56
57// ---- MetaMapType ----
58
59/// Matches Go's `MetaMapType = map[string]any`.
60pub type MetaMapType = HashMap<String, serde_json::Value>;
61
62/// Merge `update` into `base`, matching Go's `MergeMeta` logic.
63/// - Keys ending in `:*` with truthy value clear the section.
64/// - `null` values delete the key.
65/// - If `merge_special` is false, keys starting with `display:` are skipped.
66pub fn merge_meta(base: &MetaMapType, update: &MetaMapType, merge_special: bool) -> MetaMapType {
67    let mut result = base.clone();
68
69    // First pass: handle "section:*" clear keys
70    for (k, v) in update {
71        if !k.ends_with(":*") {
72            continue;
73        }
74        // Check if value is truthy (bool true)
75        let is_true = matches!(v, serde_json::Value::Bool(true));
76        if !is_true {
77            continue;
78        }
79        let prefix = k.trim_end_matches(":*");
80        if prefix.is_empty() {
81            continue;
82        }
83        let prefix_colon = format!("{prefix}:");
84        result.retain(|k2, _| k2 != prefix && !k2.starts_with(&prefix_colon));
85    }
86
87    // Second pass: merge regular keys
88    for (k, v) in update {
89        if !merge_special && k.starts_with("display:") {
90            continue;
91        }
92        if k.ends_with(":*") {
93            continue;
94        }
95        if v.is_null() {
96            result.remove(k);
97            continue;
98        }
99        result.insert(k.clone(), v.clone());
100    }
101
102    result
103}
104
105/// Helper to get a string value from MetaMapType.
106pub fn meta_get_string(meta: &MetaMapType, key: &str, default: &str) -> String {
107    meta.get(key)
108        .and_then(|v| v.as_str())
109        .unwrap_or(default)
110        .to_string()
111}
112
113/// The agent id a block's meta names: `agentId`, else the legacy `agent:id`.
114/// Not trimmed; a string `agentId`, even an empty one, wins over the legacy key.
115pub fn block_meta_agent_id(meta: &MetaMapType) -> Option<&str> {
116    meta.get("agentId")
117        .and_then(|v| v.as_str())
118        .or_else(|| meta.get("agent:id").and_then(|v| v.as_str()))
119}
120
121/// The meta key of an agent's history reader: a `view: "agent"` block that carries the agent's id so
122/// the transcript can be read through it, and is never launched.
123pub const HISTORY_READER_META_KEY: &str = "agent:historyTabFor";
124
125/// Whether a block is an agent's history reader. It carries the agent's `agentId` like the agent's
126/// own pane, but it is not that pane: nothing that looks for "the agent's block" may take it.
127pub fn is_history_reader(meta: &MetaMapType) -> bool {
128    meta.get(HISTORY_READER_META_KEY).is_some_and(|v| v.as_str().is_some_and(|s| !s.is_empty()) || v.as_bool() == Some(true))
129}
130
131/// Helper to get a bool value from MetaMapType.
132pub fn meta_get_bool(meta: &MetaMapType, key: &str, default: bool) -> bool {
133    meta.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
134}
135
136// ---- StoreObj trait ----
137
138/// Rust equivalent of Go's `StoreObj` interface.
139/// Every wave object has an otype, an OID, a version, and metadata.
140pub trait StoreObj: Serialize + for<'de> Deserialize<'de> {
141    fn get_otype() -> &'static str;
142    fn get_oid(&self) -> &str;
143    #[allow(dead_code)]
144    fn set_oid(&mut self, oid: String);
145    #[allow(dead_code)]
146    fn get_version(&self) -> i64;
147    fn set_version(&mut self, version: i64);
148    #[allow(dead_code)]
149    fn get_meta(&self) -> &MetaMapType;
150    #[allow(dead_code)]
151    fn set_meta(&mut self, meta: MetaMapType);
152
153    #[allow(dead_code)]
154    fn oref(&self) -> ORef {
155        ORef::new(Self::get_otype(), self.get_oid())
156    }
157}
158
159/// Macro that implements `StoreObj` for a struct that has standard fields:
160/// `oid: String`, `version: i64`, `meta: MetaMapType`.
161macro_rules! impl_mux_obj {
162    ($ty:ty, $otype:expr) => {
163        impl StoreObj for $ty {
164            fn get_otype() -> &'static str {
165                $otype
166            }
167            fn get_oid(&self) -> &str {
168                &self.oid
169            }
170            fn set_oid(&mut self, oid: String) {
171                self.oid = oid;
172            }
173            fn get_version(&self) -> i64 {
174                self.version
175            }
176            fn set_version(&mut self, version: i64) {
177                self.version = version;
178            }
179            fn get_meta(&self) -> &MetaMapType {
180                &self.meta
181            }
182            fn set_meta(&mut self, meta: MetaMapType) {
183                self.meta = meta;
184            }
185        }
186    };
187}
188
189// ---- Update types ----
190
191pub const UPDATE_TYPE_UPDATE: &str = "update";
192#[allow(dead_code)]
193pub const UPDATE_TYPE_DELETE: &str = "delete";
194
195// ---- UIContext ----
196
197#[allow(dead_code)]
198#[derive(Debug, Clone, Serialize, Deserialize, Default)]
199pub struct UIContext {
200    #[serde(rename = "windowid")]
201    pub window_id: String,
202    #[serde(rename = "activetabid")]
203    pub active_tab_id: String,
204}
205
206// ---- Point / WinSize / TermSize ----
207
208#[derive(Debug, Clone, Serialize, Deserialize, Default)]
209pub struct Point {
210    pub x: i64,
211    pub y: i64,
212}
213
214#[derive(Debug, Clone, Serialize, Deserialize, Default)]
215pub struct WinSize {
216    pub width: i64,
217    pub height: i64,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize, Default)]
221pub struct TermSize {
222    pub rows: i64,
223    pub cols: i64,
224}
225
226// ---- RuntimeOpts ----
227
228#[derive(Debug, Clone, Serialize, Deserialize, Default)]
229pub struct RuntimeOpts {
230    #[serde(default, skip_serializing_if = "is_default_term_size")]
231    pub termsize: TermSize,
232    #[serde(default, skip_serializing_if = "is_default_win_size")]
233    pub winsize: WinSize,
234}
235
236fn is_default_term_size(ts: &TermSize) -> bool {
237    ts.rows == 0 && ts.cols == 0
238}
239fn is_default_win_size(ws: &WinSize) -> bool {
240    ws.width == 0 && ws.height == 0
241}
242
243// ---- FileDef / BlockDef ----
244
245#[derive(Debug, Clone, Serialize, Deserialize, Default)]
246pub struct FileDef {
247    #[serde(default, skip_serializing_if = "String::is_empty")]
248    pub content: String,
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub meta: Option<HashMap<String, serde_json::Value>>,
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize, Default)]
254pub struct BlockDef {
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub files: Option<HashMap<String, FileDef>>,
257    #[serde(default, skip_serializing_if = "MetaMapType::is_empty")]
258    pub meta: MetaMapType,
259}
260
261// ---- StickerType ----
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct StickerClickOpts {
265    #[serde(default, skip_serializing_if = "String::is_empty")]
266    pub sendinput: String,
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub createblock: Option<BlockDef>,
269}
270
271#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct StickerDisplayOpts {
273    #[serde(default)]
274    pub icon: String,
275    #[serde(default)]
276    pub imgsrc: String,
277    #[serde(default, skip_serializing_if = "String::is_empty")]
278    pub svgblob: String,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
282pub struct StickerType {
283    pub stickertype: String,
284    pub style: HashMap<String, serde_json::Value>,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub clickopts: Option<StickerClickOpts>,
287    pub display: StickerDisplayOpts,
288}
289
290// ---- LayoutActionData ----
291
292#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
293pub struct LayoutActionData {
294    pub actiontype: String,
295    pub actionid: String,
296    pub blockid: String,
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub nodesize: Option<u32>,
299    /// Split-only: the new node's desired size as a fraction (0.0-1.0) of the
300    /// TARGET node's current size, e.g. 0.5 for a 50/50 inner-direction drop,
301    /// 0.2 for an outer-direction drop (matches the ghost's `leaf/5` band).
302    /// The frontend applies this against the target's live `size` at split
303    /// time (`layoutTree.ts:splitHorizontal/splitVertical`), which the
304    /// backend cannot see. Takes precedence over `nodesize` when present.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub nodesizefraction: Option<f64>,
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub indexarr: Option<Vec<i32>>,
309    #[serde(default)]
310    pub focused: bool,
311    #[serde(default)]
312    pub magnified: bool,
313    #[serde(default)]
314    pub ephemeral: bool,
315    #[serde(default, skip_serializing_if = "String::is_empty")]
316    pub targetblockid: String,
317    #[serde(default, skip_serializing_if = "String::is_empty")]
318    pub position: String,
319    /// The node id srv gave the leaf it placed (insert and split), so the
320    /// frontend's mirror of the action builds the same tree.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub nodeid: Option<String>,
323    /// When srv put the action on a layout row's queue (ms since the epoch). Stamped at the queue,
324    /// not by the writers; an action without one was queued by an older srv.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub queuedat: Option<i64>,
327}
328
329// ====================================================================
330// Core StoreObj types — each matches the Go struct + JSON tags exactly
331// ====================================================================
332
333/// Go: `Client` in pkg/obj/wtype.go
334#[derive(Debug, Clone, Serialize, Deserialize, Default)]
335pub struct Client {
336    pub oid: String,
337    pub version: i64,
338    #[serde(default)]
339    pub windowids: Vec<String>,
340    #[serde(default, serialize_with = "serialize_meta_as_null_if_empty", deserialize_with = "deserialize_meta_or_null")]
341    pub meta: MetaMapType,
342    #[serde(default, skip_serializing_if = "is_zero_i64")]
343    pub tosagreed: i64,
344    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
345    pub hasoldhistory: bool,
346    #[serde(default, skip_serializing_if = "String::is_empty")]
347    pub tempoid: String,
348}
349
350impl_mux_obj!(Client, OTYPE_CLIENT);
351
352/// Go: `Window` in pkg/obj/wtype.go
353#[derive(Debug, Clone, Serialize, Deserialize, Default)]
354pub struct Window {
355    pub oid: String,
356    pub version: i64,
357    #[serde(default)]
358    pub workspaceid: String,
359    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
360    pub isnew: bool,
361    #[serde(default)]
362    pub pos: Point,
363    #[serde(default)]
364    pub winsize: WinSize,
365    #[serde(default)]
366    pub lastfocusts: i64,
367    /// SPEC_PILLAR1_STEP2 — the host's last-set opacity for this window
368    /// (`0.0..=1.0`), so a crashed/restarted host can restore it instead
369    /// of defaulting to fully opaque. `None` = never set / fully opaque.
370    /// Written only via the `SetWindowOpacity` RPC (a direct store
371    /// read-modify-write, not a reducer-dispatched Command — see
372    /// `server::service::window::handle_window_service`); the host is
373    /// the sole source of truth for the live value, this is a durable
374    /// mirror.
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub opacity: Option<f32>,
377    /// SPEC_PILLAR1_STEP3 — the window's kind (`"full_instance"` |
378    /// `"subwindow"`), durable so a reproject can tell which native-window
379    /// creation path to drive. `None` = unknown/legacy row; treat as
380    /// `full_instance` on read (matches today's implicit default — every
381    /// window was a full instance before this field existed). Written only
382    /// via the `SetWindowTopology` RPC (a direct store read-modify-write,
383    /// not reducer-dispatched — window kind/parent were never reducer
384    /// state, same rationale as `opacity` above).
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub kind: Option<String>,
387    /// SPEC_PILLAR1_STEP3 — the parent `Window.oid` for a `subwindow`;
388    /// `None` for a `full_instance` (or an unset/legacy row). A `subwindow`
389    /// with `parent_window_id: None` is a nonsensical state the
390    /// `SetWindowTopology` RPC rejects at write time.
391    #[serde(default, skip_serializing_if = "Option::is_none")]
392    pub parent_window_id: Option<String>,
393    #[serde(default, serialize_with = "serialize_meta_as_null_if_empty", deserialize_with = "deserialize_meta_or_null")]
394    pub meta: MetaMapType,
395}
396
397impl_mux_obj!(Window, OTYPE_WINDOW);
398
399/// Go: `Workspace` in pkg/obj/wtype.go
400#[derive(Debug, Clone, Serialize, Deserialize, Default)]
401pub struct Workspace {
402    pub oid: String,
403    pub version: i64,
404    #[serde(default, skip_serializing_if = "String::is_empty")]
405    pub name: String,
406    #[serde(default)]
407    pub tabids: Vec<String>,
408    #[serde(default)]
409    pub pinnedtabids: Vec<String>,
410    #[serde(default)]
411    pub activetabid: String,
412    /// Read only, never written: the hidden tab the pin band this replaced kept a window's pinned panes in. A row that
413    /// still has one is brought into `tabids` at boot (`persist::pins::adopt_stored_shelves`).
414    #[serde(default, skip_serializing)]
415    pub pinshelftabid: String,
416    /// The panes pinned to the window (`agentmux_common::pin`): each one's block is a pane of one of `tabids`.
417    #[serde(default, skip_serializing_if = "Vec::is_empty")]
418    pub pins: Vec<agentmux_common::PinRecord>,
419    #[serde(default, serialize_with = "serialize_meta_as_null_if_empty", deserialize_with = "deserialize_meta_or_null")]
420    pub meta: MetaMapType,
421}
422
423impl_mux_obj!(Workspace, OTYPE_WORKSPACE);
424
425/// Go: `WorkspaceListEntry` in pkg/obj/wtype.go
426/// Used by ListWorkspaces — returns just {workspaceid, windowid}, not full workspace objects.
427#[derive(Debug, Clone, Serialize, Deserialize)]
428pub struct WorkspaceListEntry {
429    pub workspaceid: String,
430    #[serde(default)]
431    pub windowid: String,
432}
433
434/// Go: `Tab` in pkg/obj/wtype.go
435#[derive(Debug, Clone, Serialize, Deserialize, Default)]
436pub struct Tab {
437    pub oid: String,
438    pub version: i64,
439    #[serde(default)]
440    pub name: String,
441    #[serde(default)]
442    pub layoutstate: String,
443    #[serde(default)]
444    pub blockids: Vec<String>,
445    #[serde(default, serialize_with = "serialize_meta_as_null_if_empty", deserialize_with = "deserialize_meta_or_null")]
446    pub meta: MetaMapType,
447}
448
449impl_mux_obj!(Tab, OTYPE_TAB);
450
451// ====================================================================
452// Phase E.4.B Phase 3 — LayoutNode, LayoutNodeData, FlexDirection now
453// live in agentmux-common so they can be referenced by ipc.rs Command/
454// Event variants without a circular dependency. Re-exported here so
455// all existing callers within agentmux-srv keep working unchanged.
456// ====================================================================
457pub use agentmux_common::{FlexDirection, LayoutNode, LayoutNodeData};
458
459/// Go: `LayoutState` in pkg/obj/wtype.go
460#[derive(Debug, Clone, Serialize, Deserialize, Default)]
461pub struct LayoutState {
462    pub oid: String,
463    pub version: i64,
464    /// Phase E.4.B Phase 2 — typed; was `Option<serde_json::Value>`.
465    /// Wire format unchanged (serde-compat with the prior JSON shape).
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub rootnode: Option<LayoutNode>,
468    #[serde(default, skip_serializing_if = "String::is_empty")]
469    pub magnifiednodeid: String,
470    #[serde(default, skip_serializing_if = "String::is_empty")]
471    pub focusednodeid: String,
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub pendingbackendactions: Option<Vec<LayoutActionData>>,
474    #[serde(default, skip_serializing_if = "Option::is_none")]
475    pub meta: Option<MetaMapType>,
476}
477
478// LayoutState has meta as Option<MetaMapType> (Go uses omitempty), so manual impl:
479impl StoreObj for LayoutState {
480    fn get_otype() -> &'static str {
481        OTYPE_LAYOUT
482    }
483    fn get_oid(&self) -> &str {
484        &self.oid
485    }
486    fn set_oid(&mut self, oid: String) {
487        self.oid = oid;
488    }
489    fn get_version(&self) -> i64 {
490        self.version
491    }
492    fn set_version(&mut self, version: i64) {
493        self.version = version;
494    }
495    fn get_meta(&self) -> &MetaMapType {
496        static EMPTY: std::sync::LazyLock<MetaMapType> = std::sync::LazyLock::new(MetaMapType::new);
497        self.meta.as_ref().unwrap_or(&EMPTY)
498    }
499    fn set_meta(&mut self, meta: MetaMapType) {
500        self.meta = Some(meta);
501    }
502}
503
504/// Go: `Block` in pkg/obj/wtype.go
505#[derive(Debug, Clone, Serialize, Deserialize, Default)]
506pub struct Block {
507    pub oid: String,
508    #[serde(default, skip_serializing_if = "String::is_empty")]
509    pub parentoref: String,
510    pub version: i64,
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub runtimeopts: Option<RuntimeOpts>,
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub stickers: Option<Vec<StickerType>>,
515    #[serde(default, serialize_with = "serialize_meta_as_null_if_empty", deserialize_with = "deserialize_meta_or_null")]
516    pub meta: MetaMapType,
517    #[serde(default, skip_serializing_if = "Option::is_none")]
518    pub subblockids: Option<Vec<String>>,
519}
520
521impl_mux_obj!(Block, OTYPE_BLOCK);
522
523// ---- MuxObjUpdate ----
524
525/// Represents an update notification for a wave object.
526/// Matches Go's `MuxObjUpdate`.
527#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
528#[ts(export, export_to = "../../../frontend/types/rpc/")]
529pub struct MuxObjUpdate {
530    pub updatetype: String,
531    pub otype: String,
532    pub oid: String,
533    /// The object, for an update; absent for a delete.
534    #[serde(default, skip_serializing_if = "Option::is_none")]
535    #[ts(optional, type = "MuxObj")]
536    pub obj: Option<serde_json::Value>,
537}
538
539/// The `waveobj:batchedupdates` payload: the updates of one atomic backend transition, in order.
540#[derive(Debug, Clone, Serialize, ts_rs::TS)]
541#[ts(export, export_to = "../../../frontend/types/rpc/")]
542pub struct MuxObjBatch(pub Vec<MuxObjUpdate>);
543
544// ---- Helpers ----
545
546use crate::backend::rpc_types::is_zero_i64;
547
548/// Serialize any StoreObj to JSON bytes, including the "otype" field.
549/// This matches Go's `obj.ToJson()`.
550pub fn mux_obj_to_json<T: StoreObj>(obj: &T) -> Result<Vec<u8>, serde_json::Error> {
551    let mut map = serde_json::to_value(obj)?;
552    if let Some(m) = map.as_object_mut() {
553        m.insert("otype".to_string(), serde_json::Value::String(T::get_otype().to_string()));
554    }
555    serde_json::to_vec(&map)
556}
557
558/// Serialize any StoreObj to a serde_json::Value, including the "otype" field.
559/// This matches Go's `obj.ToJsonMap()` — used by GetObject/GetObjects responses.
560pub fn mux_obj_to_value<T: StoreObj>(obj: &T) -> serde_json::Value {
561    let mut map = serde_json::to_value(obj).unwrap_or_default();
562    if let Some(m) = map.as_object_mut() {
563        m.insert("otype".to_string(), serde_json::Value::String(T::get_otype().to_string()));
564    }
565    map
566}
567
568/// Deserialize JSON bytes to a specific StoreObj type.
569/// Does NOT validate the otype field — caller should verify if needed.
570pub fn mux_obj_from_json<T: StoreObj>(data: &[u8]) -> Result<T, serde_json::Error> {
571    serde_json::from_slice(data)
572}
573
574// ====================================================================
575// Tests
576// ====================================================================
577
578#[cfg(test)]
579mod tests {
580    #[test]
581    fn block_meta_agent_id_prefers_agent_id_over_the_legacy_key() {
582        use super::{block_meta_agent_id, MetaMapType};
583        let meta = |pairs: &[(&str, serde_json::Value)]| -> MetaMapType {
584            pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
585        };
586        let both = meta(&[("agentId", "new".into()), ("agent:id", "old".into())]);
587        assert_eq!(block_meta_agent_id(&both), Some("new"));
588        let legacy = meta(&[("agent:id", "old".into())]);
589        assert_eq!(block_meta_agent_id(&legacy), Some("old"));
590        let non_string = meta(&[("agentId", 7.into()), ("agent:id", "old".into())]);
591        assert_eq!(block_meta_agent_id(&non_string), Some("old"));
592        let empty = meta(&[("agentId", "".into()), ("agent:id", "old".into())]);
593        assert_eq!(block_meta_agent_id(&empty), Some(""));
594        assert_eq!(block_meta_agent_id(&MetaMapType::new()), None);
595    }
596
597    /// This crate defines `BlockDef` and `FileDef` TWICE — here, and again in
598    /// `backend/wconfig/types.rs` for widgets. The pairs differ in Rust:
599    /// `obj` uses `Option<HashMap<..>>` / `Option<..>` where `wconfig` uses a
600    /// plain `HashMap`. They are nonetheless wire-identical, because every
601    /// field on both carries `skip_serializing_if`, so an absent map and an
602    /// empty one both vanish.
603    ///
604    /// That is worth pinning rather than assuming, for two reasons.
605    ///
606    /// The frontend has ONE hand-written contract for each
607    /// (`frontend/types/srv-types.d.ts`, `type BlockDef = { files?, meta? }`,
608    /// still tagged `// waveobj.BlockDef` from the Go original). Both Rust
609    /// structs currently satisfy it. If either drifts — someone drops a
610    /// `skip_serializing_if`, or makes a field required — one of them starts
611    /// lying to that contract and nothing else would say so.
612    ///
613    /// And when the `websocket.rs` commands are eventually typed, two structs
614    /// sharing a name would generate two `BlockDef` TypeScript files into the same
615    /// export directory, one silently overwriting the other. Knowing the shapes
616    /// agree is the precondition for merging them, or for choosing either as
617    /// canonical. This test does not fix the duplication; it stops it becoming
618    /// a divergence while nobody is looking.
619    #[test]
620    fn block_def_and_file_def_serialize_identically_in_both_modules() {
621        use crate::backend::wconfig::types as wc;
622
623        // Empty: both must omit every field, not emit nulls or empty maps.
624        let a = serde_json::to_string(&super::BlockDef::default()).unwrap();
625        let b = serde_json::to_string(&wc::BlockDef::default()).unwrap();
626        assert_eq!(a, "{}", "obj::BlockDef default must serialize to {{}}");
627        assert_eq!(a, b, "the two BlockDef structs disagree on the empty case");
628
629        let a = serde_json::to_string(&super::FileDef::default()).unwrap();
630        let b = serde_json::to_string(&wc::FileDef::default()).unwrap();
631        assert_eq!(a, "{}", "obj::FileDef default must serialize to {{}}");
632        assert_eq!(a, b, "the two FileDef structs disagree on the empty case");
633
634        // Populated: same keys, same shape. Content is the only always-present
635        // scalar, so it is enough to prove the field names line up.
636        let mut oa = super::FileDef::default();
637        oa.content = "x".into();
638        let mut ob = wc::FileDef::default();
639        ob.content = "x".into();
640        assert_eq!(
641            serde_json::to_string(&oa).unwrap(),
642            serde_json::to_string(&ob).unwrap(),
643            "the two FileDef structs disagree once populated"
644        );
645    }
646
647    use super::*;
648
649    #[test]
650    fn test_client_roundtrip() {
651        let client = Client {
652            oid: "550e8400-e29b-41d4-a716-446655440000".to_string(),
653            version: 3,
654            windowids: vec!["w1".to_string(), "w2".to_string()],
655            meta: MetaMapType::new(),
656            tosagreed: 1700000000000,
657            ..Default::default()
658        };
659        let json = mux_obj_to_json(&client).unwrap();
660        let parsed: Client = mux_obj_from_json(&json).unwrap();
661        assert_eq!(parsed.oid, client.oid);
662        assert_eq!(parsed.version, client.version);
663        assert_eq!(parsed.windowids, client.windowids);
664        assert_eq!(parsed.tosagreed, client.tosagreed);
665    }
666
667    #[test]
668    fn test_window_roundtrip() {
669        let window = Window {
670            oid: "550e8400-e29b-41d4-a716-446655440001".to_string(),
671            version: 1,
672            workspaceid: "ws-123".to_string(),
673            pos: Point { x: 100, y: 200 },
674            winsize: WinSize {
675                width: 1920,
676                height: 1080,
677            },
678            lastfocusts: 1700000000000,
679            meta: MetaMapType::new(),
680            ..Default::default()
681        };
682        let json = mux_obj_to_json(&window).unwrap();
683        let parsed: Window = mux_obj_from_json(&json).unwrap();
684        assert_eq!(parsed.workspaceid, "ws-123");
685        assert_eq!(parsed.pos.x, 100);
686        assert_eq!(parsed.winsize.width, 1920);
687    }
688
689    #[test]
690    fn test_workspace_roundtrip() {
691        let ws = Workspace {
692            oid: "ws-oid".to_string(),
693            version: 2,
694            name: "My Workspace".to_string(),
695            tabids: vec!["t1".to_string(), "t2".to_string()],
696            pinnedtabids: vec!["t0".to_string()],
697            activetabid: "t1".to_string(),
698            meta: MetaMapType::new(),
699            ..Default::default()
700        };
701        let json = mux_obj_to_json(&ws).unwrap();
702        let parsed: Workspace = mux_obj_from_json(&json).unwrap();
703        assert_eq!(parsed.name, "My Workspace");
704        assert_eq!(parsed.tabids.len(), 2);
705        assert_eq!(parsed.pinnedtabids, vec!["t0"]);
706    }
707
708    #[test]
709    fn test_tab_roundtrip() {
710        let tab = Tab {
711            oid: "tab-oid".to_string(),
712            version: 1,
713            name: "Tab 1".to_string(),
714            layoutstate: "ls-123".to_string(),
715            blockids: vec!["b1".to_string(), "b2".to_string()],
716            meta: MetaMapType::new(),
717        };
718        let json = mux_obj_to_json(&tab).unwrap();
719        let parsed: Tab = mux_obj_from_json(&json).unwrap();
720        assert_eq!(parsed.name, "Tab 1");
721        assert_eq!(parsed.blockids.len(), 2);
722    }
723
724    #[test]
725    fn test_layout_state_roundtrip() {
726        // Phase E.4.B Phase 2 — uses typed LayoutNode (was a junk JSON blob).
727        let ls = LayoutState {
728            oid: "ls-oid".to_string(),
729            version: 1,
730            rootnode: Some(LayoutNode {
731                id: "node-1".into(),
732                flex_direction: FlexDirection::Row,
733                size: 1.0,
734                children: Vec::new(),
735                data: None,
736                ..Default::default()
737            }),
738            magnifiednodeid: "node-1".to_string(),
739            ..Default::default()
740        };
741        let json = mux_obj_to_json(&ls).unwrap();
742        let parsed: LayoutState = mux_obj_from_json(&json).unwrap();
743        assert_eq!(parsed.magnifiednodeid, "node-1");
744        assert!(parsed.rootnode.is_some());
745        assert_eq!(parsed.rootnode.as_ref().unwrap().id, "node-1");
746    }
747
748    /// A row an older build wrote carries a `leaforder` array (since removed).
749    /// It must still load, and the next write must not bring it back.
750    #[test]
751    fn test_layout_state_row_with_leaforder_loads_and_resaves_without_it() {
752        let old_row = serde_json::json!({
753            "otype": "layout",
754            "oid": "ls-old",
755            "version": 3,
756            "focusednodeid": "node-1",
757            "leaforder": [{ "nodeid": "node-1", "blockid": "block-1" }],
758        });
759        let parsed: LayoutState = mux_obj_from_json(&serde_json::to_vec(&old_row).unwrap()).unwrap();
760        assert_eq!(parsed.focusednodeid, "node-1");
761        let rewritten = String::from_utf8(mux_obj_to_json(&parsed).unwrap()).unwrap();
762        assert!(!rewritten.contains("leaforder"), "resaved row: {rewritten}");
763    }
764
765    /// Phase E.4.B Phase 2 acceptance gate: deserializing the JSON shape
766    /// the frontend produces today MUST yield the typed LayoutNode, and
767    /// reserializing MUST produce equivalent JSON. The shapes here cover:
768    ///   1. Single-leaf root (dnd / tear-off shape)
769    ///   2. A multi-pane shape (deep nesting + mixed group/leaf nodes) —
770    ///      the former first-launch four-pane layout, see below
771    ///   3. Edge: missing `children` array for leaves
772    #[test]
773    fn test_layout_node_serde_compat_with_frontend_shapes() {
774        // Shape 1 — single leaf (the shape `wcore::single_leaf_tree` writes).
775        let leaf_json = serde_json::json!({
776            "id": "node-uuid-1",
777            "data": { "blockId": "block-uuid-1" },
778            "flexDirection": "row",
779            "size": 1
780        });
781        let leaf: LayoutNode = serde_json::from_value(leaf_json).unwrap();
782        assert_eq!(leaf.id, "node-uuid-1");
783        assert_eq!(leaf.flex_direction, FlexDirection::Row);
784        assert_eq!(leaf.size, 1.0);
785        assert!(leaf.children.is_empty());
786        assert_eq!(leaf.data.as_ref().unwrap().block_id, "block-uuid-1");
787        // Round-trip preserves shape.
788        let reserialized = serde_json::to_value(&leaf).unwrap();
789        let reparsed: LayoutNode = serde_json::from_value(reserialized).unwrap();
790        assert_eq!(leaf, reparsed);
791
792        // Shape 2 — a nested row/column tree with a multi-child right
793        // column. This was the first-launch four-pane layout when written;
794        // the default is now three panes (wcore::default_three_pane_tree),
795        // but the fixture is kept as-is: what it exercises is serde
796        // round-tripping of a nested LayoutNode, not the current default.
797        let four_pane_json = serde_json::json!({
798            "id": "root-id",
799            "flexDirection": "row",
800            "size": 10,
801            "children": [
802                {
803                    "id": "agent-id",
804                    "flexDirection": "column",
805                    "size": 5,
806                    "data": { "blockId": "agent-block" }
807                },
808                {
809                    "id": "right-col-id",
810                    "flexDirection": "column",
811                    "size": 5,
812                    "children": [
813                        {
814                            "id": "swarm-id",
815                            "flexDirection": "row",
816                            "size": 4,
817                            "data": { "blockId": "swarm-block" }
818                        },
819                        {
820                            "id": "memory-id",
821                            "flexDirection": "row",
822                            "size": 4,
823                            "data": { "blockId": "memory-block" }
824                        },
825                        {
826                            "id": "sysinfo-id",
827                            "flexDirection": "row",
828                            "size": 2,
829                            "data": { "blockId": "sysinfo-block" }
830                        }
831                    ]
832                }
833            ]
834        });
835        let root: LayoutNode = serde_json::from_value(four_pane_json).unwrap();
836        assert_eq!(root.id, "root-id");
837        assert_eq!(root.children.len(), 2);
838        assert_eq!(root.children[0].id, "agent-id");
839        assert_eq!(root.children[0].flex_direction, FlexDirection::Column);
840        assert_eq!(root.children[0].data.as_ref().unwrap().block_id, "agent-block");
841        let right_col = &root.children[1];
842        assert_eq!(right_col.children.len(), 3);
843        assert_eq!(right_col.data, None); // group node, no leaf data
844        assert_eq!(right_col.children[0].data.as_ref().unwrap().block_id, "swarm-block");
845        assert_eq!(right_col.children[1].data.as_ref().unwrap().block_id, "memory-block");
846        assert_eq!(right_col.children[2].data.as_ref().unwrap().block_id, "sysinfo-block");
847        let reserialized = serde_json::to_value(&root).unwrap();
848        let reparsed: LayoutNode = serde_json::from_value(reserialized).unwrap();
849        assert_eq!(root, reparsed);
850
851        // Shape 3 — leaf without `children` array (real on-disk blobs may
852        // or may not have `"children": []`; deserializer must tolerate either).
853        let leaf_no_children = serde_json::json!({
854            "id": "loner",
855            "flexDirection": "column",
856            "size": 5,
857            "data": { "blockId": "b" }
858        });
859        let parsed: LayoutNode = serde_json::from_value(leaf_no_children).unwrap();
860        assert!(parsed.children.is_empty());
861    }
862
863    /// Phase E.4.B Phase 2 — deserializing a node WITHOUT `flexDirection`
864    /// falls back to `Row` default. Defensive against older blobs.
865    #[test]
866    fn test_layout_node_defaults_flex_direction_to_row() {
867        let no_dir = serde_json::json!({"id": "x", "size": 1});
868        let parsed: LayoutNode = serde_json::from_value(no_dir).unwrap();
869        assert_eq!(parsed.flex_direction, FlexDirection::Row);
870    }
871
872    /// Phase E.4.B Phase 2 (reagent P2 PR #688) — whole-number sizes
873    /// serialize as integer JSON literals, not float (`10` not `10.0`).
874    /// This preserves byte-equal compatibility with the prior
875    /// `serde_json::json!()`-produced JSON which used integer literals.
876    #[test]
877    fn test_layout_node_size_serializes_as_integer_when_whole() {
878        let whole = LayoutNode {
879            id: "x".into(),
880            flex_direction: FlexDirection::Row,
881            size: 10.0,
882            children: Vec::new(),
883            data: None,
884            ..Default::default()
885        };
886        let json = serde_json::to_string(&whole).unwrap();
887        assert!(json.contains("\"size\":10"), "whole sizes should serialize as integer; got {}", json);
888        assert!(!json.contains("\"size\":10.0"), "whole sizes should NOT include the decimal; got {}", json);
889
890        // Fractional sizes still serialize with the decimal.
891        let frac = LayoutNode {
892            id: "y".into(),
893            flex_direction: FlexDirection::Row,
894            size: 5.5,
895            children: Vec::new(),
896            data: None,
897            ..Default::default()
898        };
899        let json = serde_json::to_string(&frac).unwrap();
900        assert!(json.contains("\"size\":5.5"), "fractional sizes preserve the decimal; got {}", json);
901
902        // Round-trip works either way.
903        let reparsed: LayoutNode = serde_json::from_str(&serde_json::to_string(&whole).unwrap()).unwrap();
904        assert_eq!(reparsed.size, 10.0);
905    }
906
907    /// Phase E.4.B Phase 2 — `data: None` serializes ABSENT (not `"data": null`).
908    /// Frontend tolerates either, but absent matches the pre-typed JSON shape.
909    #[test]
910    fn test_layout_node_data_skipped_when_none() {
911        let group = LayoutNode {
912            id: "g".into(),
913            flex_direction: FlexDirection::Row,
914            size: 1.0,
915            children: Vec::new(),
916            data: None,
917            ..Default::default()
918        };
919        let json = serde_json::to_value(&group).unwrap();
920        assert!(json.get("data").is_none(), "data: None must skip-serialize");
921    }
922
923    /// Regression test: unknown fields on LayoutNode and LayoutNodeData round-
924    /// trip via the `extra: HashMap` catch-all (codex P1 PR #688 + #689).
925    /// Without this, fields the frontend writes that we don't yet model would
926    /// be silently dropped on deserialize→serialize cycles — a regression vs
927    /// the prior `serde_json::Value` storage.
928    #[test]
929    fn test_layout_node_preserves_unknown_fields() {
930        let json_with_extras = serde_json::json!({
931            "id": "n",
932            "flexDirection": "row",
933            "size": 1,
934            "backendLayoutVersion": 7,
935            "data": {
936                "blockId": "b",
937                "renderHint": "compact"
938            }
939        });
940        let node: LayoutNode = serde_json::from_value(json_with_extras).unwrap();
941        assert_eq!(node.extra.get("backendLayoutVersion"), Some(&serde_json::json!(7)));
942        assert_eq!(
943            node.data.as_ref().unwrap().extra.get("renderHint"),
944            Some(&serde_json::json!("compact"))
945        );
946        // Round-trip preserves both.
947        let reserialized = serde_json::to_value(&node).unwrap();
948        assert_eq!(reserialized.get("backendLayoutVersion"), Some(&serde_json::json!(7)));
949        assert_eq!(
950            reserialized.get("data").and_then(|d| d.get("renderHint")),
951            Some(&serde_json::json!("compact"))
952        );
953        // Empty extra → no stray "extra" key on output.
954        let no_extras = LayoutNode {
955            id: "x".into(),
956            flex_direction: FlexDirection::Row,
957            size: 1.0,
958            ..Default::default()
959        };
960        let json = serde_json::to_value(&no_extras).unwrap();
961        assert!(json.get("extra").is_none());
962    }
963
964    /// Regression test (codex P1 PR #689): missing blockId in JSON must fail
965    /// deserialization rather than silently default to "". An empty
966    /// block_id would cause incorrect matching wherever code resolves a
967    /// layout node by block id (e.g. the reducer's
968    /// `find_node_id_by_block`/`LayoutDeleteNodeByBlock`).
969    #[test]
970    fn test_layout_node_data_missing_block_id_fails_deserialization() {
971        let missing_id = serde_json::json!({ "renderHint": "compact" });
972        let result = serde_json::from_value::<LayoutNodeData>(missing_id);
973        assert!(result.is_err(), "missing blockId must fail deserialization");
974    }
975
976    #[test]
977    fn test_block_roundtrip() {
978        let block = Block {
979            oid: "blk-oid".to_string(),
980            version: 5,
981            parentoref: "tab:parent-id".to_string(),
982            meta: {
983                let mut m = MetaMapType::new();
984                m.insert("view".to_string(), serde_json::json!("term"));
985                m
986            },
987            ..Default::default()
988        };
989        let json = mux_obj_to_json(&block).unwrap();
990        let parsed: Block = mux_obj_from_json(&json).unwrap();
991        assert_eq!(parsed.parentoref, "tab:parent-id");
992        assert_eq!(
993            parsed.meta.get("view").and_then(|v| v.as_str()),
994            Some("term")
995        );
996    }
997
998    #[test]
999    fn test_wire_compat_go_json_client() {
1000        // Hardcoded JSON from Go's encoding to verify wire compatibility
1001        let go_json = r#"{"oid":"abc-123","otype":"client","version":2,"windowids":["w1"],"meta":{"view":"term"},"tosagreed":1700000000000}"#;
1002        let client: Client = serde_json::from_str(go_json).unwrap();
1003        assert_eq!(client.oid, "abc-123");
1004        assert_eq!(client.version, 2);
1005        assert_eq!(client.windowids, vec!["w1"]);
1006        assert_eq!(client.tosagreed, 1700000000000);
1007    }
1008
1009    #[test]
1010    fn test_wire_compat_go_json_block() {
1011        let go_json = r#"{"oid":"blk-1","otype":"block","version":3,"parentoref":"tab:t1","meta":{"view":"term","cmd":"ls"}}"#;
1012        let block: Block = serde_json::from_str(go_json).unwrap();
1013        assert_eq!(block.oid, "blk-1");
1014        assert_eq!(block.parentoref, "tab:t1");
1015        assert_eq!(block.version, 3);
1016    }
1017
1018    #[test]
1019    fn test_wire_compat_go_json_tab() {
1020        let go_json = r#"{"oid":"tab-1","otype":"tab","version":1,"name":"Shell","layoutstate":"ls-1","blockids":["b1","b2"],"meta":{}}"#;
1021        let tab: Tab = serde_json::from_str(go_json).unwrap();
1022        assert_eq!(tab.name, "Shell");
1023        assert_eq!(tab.blockids, vec!["b1", "b2"]);
1024    }
1025
1026    #[test]
1027    fn test_mux_obj_to_json_includes_otype() {
1028        let client = Client {
1029            oid: "test".to_string(),
1030            version: 1,
1031            ..Default::default()
1032        };
1033        let json_bytes = mux_obj_to_json(&client).unwrap();
1034        let v: serde_json::Value = serde_json::from_slice(&json_bytes).unwrap();
1035        assert_eq!(v["otype"], "client");
1036    }
1037
1038    #[test]
1039    fn test_merge_meta_basic() {
1040        let mut base = MetaMapType::new();
1041        base.insert("view".into(), serde_json::json!("term"));
1042        base.insert("cmd".into(), serde_json::json!("ls"));
1043
1044        let mut update = MetaMapType::new();
1045        update.insert("cmd".into(), serde_json::json!("pwd"));
1046        update.insert("icon".into(), serde_json::json!("star"));
1047
1048        let result = merge_meta(&base, &update, true);
1049        assert_eq!(result["view"], "term");
1050        assert_eq!(result["cmd"], "pwd");
1051        assert_eq!(result["icon"], "star");
1052    }
1053
1054    #[test]
1055    fn test_merge_meta_null_deletes() {
1056        let mut base = MetaMapType::new();
1057        base.insert("view".into(), serde_json::json!("term"));
1058        base.insert("cmd".into(), serde_json::json!("ls"));
1059
1060        let mut update = MetaMapType::new();
1061        update.insert("cmd".into(), serde_json::Value::Null);
1062
1063        let result = merge_meta(&base, &update, true);
1064        assert_eq!(result.get("view").unwrap(), "term");
1065        assert!(!result.contains_key("cmd"));
1066    }
1067
1068    #[test]
1069    fn test_merge_meta_section_clear() {
1070        let mut base = MetaMapType::new();
1071        base.insert("frame".into(), serde_json::json!(true));
1072        base.insert("frame:title".into(), serde_json::json!("hello"));
1073        base.insert("frame:icon".into(), serde_json::json!("star"));
1074        base.insert("cmd".into(), serde_json::json!("ls"));
1075
1076        let mut update = MetaMapType::new();
1077        update.insert("frame:*".into(), serde_json::json!(true));
1078
1079        let result = merge_meta(&base, &update, true);
1080        assert!(!result.contains_key("frame"));
1081        assert!(!result.contains_key("frame:title"));
1082        assert!(!result.contains_key("frame:icon"));
1083        assert_eq!(result["cmd"], "ls"); // unrelated key preserved
1084    }
1085
1086    #[test]
1087    fn test_merge_meta_skip_display_when_not_special() {
1088        let base = MetaMapType::new();
1089        let mut update = MetaMapType::new();
1090        update.insert("display:name".into(), serde_json::json!("test"));
1091        update.insert("view".into(), serde_json::json!("term"));
1092
1093        let result = merge_meta(&base, &update, false);
1094        assert!(!result.contains_key("display:name"));
1095        assert_eq!(result["view"], "term");
1096    }
1097
1098    #[test]
1099    fn test_meta_get_string() {
1100        let mut meta = MetaMapType::new();
1101        meta.insert("view".into(), serde_json::json!("term"));
1102        assert_eq!(meta_get_string(&meta, "view", "default"), "term");
1103        assert_eq!(meta_get_string(&meta, "missing", "default"), "default");
1104    }
1105
1106    #[test]
1107    fn test_meta_get_bool() {
1108        let mut meta = MetaMapType::new();
1109        meta.insert("edit".into(), serde_json::json!(true));
1110        assert!(meta_get_bool(&meta, "edit", false));
1111        assert!(!meta_get_bool(&meta, "missing", false));
1112    }
1113}