weave-contracts 0.9.0

WebSocket protocol types shared between edge-agent and weave-server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! WebSocket protocol types shared between `edge-agent` and `weave-server`.
//!
//! Wire format: JSON text frames. Each frame is a single `ServerToEdge` or
//! `EdgeToServer` value serialized as JSON. The runtime binds to a LAN IP
//! and performs no authentication.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use uuid::Uuid;

/// Frames sent from `weave-server` to an `edge-agent`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerToEdge {
    /// Full config snapshot. Sent on (re)connect and on bulk reload.
    ConfigFull { config: EdgeConfig },
    /// Incremental mapping change.
    ConfigPatch {
        mapping_id: Uuid,
        op: PatchOp,
        mapping: Option<Mapping>,
    },
    /// Server-initiated active-target switch for an existing mapping.
    TargetSwitch {
        mapping_id: Uuid,
        service_target: String,
    },
    /// Replace the edge's glyph set. Sent after any glyph CRUD on the server.
    GlyphsUpdate { glyphs: Vec<Glyph> },
    /// Render a glyph on a specific device immediately. Used by the
    /// weave-web "Test LED" affordance to verify a device's display path
    /// without waiting for a service-state event.
    DisplayGlyph {
        device_type: String,
        device_id: String,
        /// 9-line ASCII grid (`*` = on, anything else = off). Matches
        /// the `Glyph::pattern` shape used in `GlyphsUpdate`.
        pattern: String,
        /// Brightness 0.0..=1.0. Defaults to 1.0 when absent.
        #[serde(skip_serializing_if = "Option::is_none")]
        brightness: Option<f32>,
        /// Auto-clear timeout in milliseconds. Defaults to a short value
        /// when absent so test renders don't linger.
        #[serde(skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u32>,
        /// Transition kind (`"immediate"` or `"cross_fade"`). Defaults to
        /// cross-fade when absent.
        #[serde(skip_serializing_if = "Option::is_none")]
        transition: Option<String>,
    },
    /// Server-initiated request to (re)connect a specific device. Idempotent
    /// — already-connected devices are a no-op aside from clearing any
    /// "paused" state that previously suppressed reconnect attempts.
    DeviceConnect {
        device_type: String,
        device_id: String,
    },
    /// Server-initiated request to disconnect a specific device. Sets a
    /// paused flag so the auto-reconnect loop does not immediately
    /// re-establish the link.
    DeviceDisconnect {
        device_type: String,
        device_id: String,
    },
    /// Periodic keepalive to keep NAT/proxies open and detect half-open TCP.
    Ping,
}

/// Frames sent from an `edge-agent` to `weave-server`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EdgeToServer {
    /// First frame after connect. Declares identity and adapter capabilities.
    Hello {
        edge_id: String,
        version: String,
        capabilities: Vec<String>,
    },
    /// State update for a service target (e.g. Roon zone playback / volume).
    State {
        service_type: String,
        target: String,
        property: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_id: Option<String>,
        value: serde_json::Value,
    },
    /// State update for a device (battery, RSSI, connected).
    DeviceState {
        device_type: String,
        device_id: String,
        property: String,
        value: serde_json::Value,
    },
    /// Reply to server `Ping`.
    Pong,
    /// The edge committed a target switch via on-device selection mode.
    /// Server replies by calling the same code path as `POST
    /// /api/mappings/:id/target`: persist the new `service_target`, then
    /// broadcast a `ConfigPatch` upsert back to all edges (including the
    /// sender) and a `MappingChanged` to UI subscribers.
    SwitchTarget {
        mapping_id: Uuid,
        service_target: String,
    },
    /// A command that the edge's adapter emitted to an external service
    /// (Roon MOO RPC, Hue REST, …). One frame per `adapter.send_intent`
    /// call, carrying the outcome and measured latency so the UI live
    /// stream can show "sent → ok (42ms)" rows alongside input and
    /// state-echo rows.
    Command {
        service_type: String,
        target: String,
        /// Snake-case intent name (`volume_change`, `play_pause`, …).
        intent: String,
        /// Intent parameters serialized as JSON. Shape matches the
        /// `weave-engine::Intent` discriminant's payload.
        #[serde(default)]
        params: serde_json::Value,
        result: CommandResult,
        #[serde(skip_serializing_if = "Option::is_none")]
        latency_ms: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_id: Option<String>,
    },
    /// Adapter-level or routing-level error not tied to a specific
    /// command (bridge disconnect, auth token expired, pairing lost).
    /// Command-level failures use `Command { result: Err { .. } }`
    /// instead — `Error` is for ambient conditions.
    Error {
        context: String,
        message: String,
        severity: ErrorSeverity,
    },
    /// Periodic edge-side metrics. Emitted on a fixed cadence (typically
    /// every 10 s) so the server can surface edge health in `/ws/ui`
    /// dashboards. Server-side latency is measured separately from
    /// `Ping`/`Pong` round trips and is not carried here.
    EdgeStatus {
        /// Wifi signal strength normalized to 0..=100 percent. `None`
        /// when the platform doesn't expose a signal-strength API to
        /// user code, when the host has no wifi adapter, or when the
        /// API call failed (entitlement missing, permission denied).
        #[serde(skip_serializing_if = "Option::is_none")]
        wifi: Option<u8>,
    },
}

/// Outcome of an `EdgeToServer::Command`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CommandResult {
    Ok,
    Err { message: String },
}

/// Severity classification for `EdgeToServer::Error` and `UiFrame::Error`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorSeverity {
    Warn,
    Error,
    Fatal,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PatchOp {
    Upsert,
    Delete,
}

/// Complete config for one edge, pushed as a `ConfigFull` frame.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EdgeConfig {
    pub edge_id: String,
    pub mappings: Vec<Mapping>,
    /// Named glyph patterns the edge should use when rendering feedback.
    /// Consumers look up by `name`. Entries with `builtin == true` have an
    /// empty `pattern` and are expected to be rendered programmatically by
    /// the consumer (e.g. `volume_bar` scales with percentage).
    #[serde(default)]
    pub glyphs: Vec<Glyph>,
}

/// A named Nuimo LED glyph. `pattern` is a 9x9 ASCII grid compatible with
/// `nuimo::Glyph::from_str` (`*` = LED on, anything else = off, rows
/// separated by `\n`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Glyph {
    pub name: String,
    #[serde(default)]
    pub pattern: String,
    #[serde(default)]
    pub builtin: bool,
}

/// Frames sent from `weave-server` to a Web UI client on `/ws/ui`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UiFrame {
    /// Initial full snapshot, pushed once on connect.
    Snapshot { snapshot: UiSnapshot },
    /// An edge completed its `Hello` handshake or has otherwise come online.
    EdgeOnline { edge: EdgeInfo },
    /// An edge has disconnected (ws closed).
    EdgeOffline { edge_id: String },
    /// One service-state update from a connected edge.
    ServiceState {
        edge_id: String,
        service_type: String,
        target: String,
        property: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_id: Option<String>,
        value: serde_json::Value,
    },
    /// One device-state update from a connected edge (battery, RSSI, etc.).
    DeviceState {
        edge_id: String,
        device_type: String,
        device_id: String,
        property: String,
        value: serde_json::Value,
    },
    /// Mapping CRUD happened on the server. UIs replace their copy.
    MappingChanged {
        mapping_id: Uuid,
        op: PatchOp,
        mapping: Option<Mapping>,
    },
    /// The glyph set changed. UIs refresh their registry.
    GlyphsChanged { glyphs: Vec<Glyph> },
    /// Fan-out of an edge-emitted `Command`. Transient — never stored in
    /// `UiSnapshot`; dashboards that open after the fact will not see it.
    Command {
        edge_id: String,
        service_type: String,
        target: String,
        intent: String,
        #[serde(default)]
        params: serde_json::Value,
        result: CommandResult,
        #[serde(skip_serializing_if = "Option::is_none")]
        latency_ms: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_id: Option<String>,
        /// RFC3339 timestamp assigned by the server on fan-out.
        at: String,
    },
    /// Fan-out of an edge-emitted `Error`. Transient.
    Error {
        edge_id: String,
        context: String,
        message: String,
        severity: ErrorSeverity,
        /// RFC3339 timestamp assigned by the server on fan-out.
        at: String,
    },
    /// Periodic edge metrics. Carries the latest known wifi signal
    /// strength (edge-reported) and round-trip latency (server-measured
    /// from `Ping`/`Pong`). Each field is `None` when unknown:
    /// either because no measurement has arrived yet, or because the
    /// edge cannot read the value on its platform. Emitted whenever
    /// either field changes; UIs apply it as a partial update on the
    /// matching `edge_id` row.
    EdgeStatus {
        edge_id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        wifi: Option<u8>,
        #[serde(skip_serializing_if = "Option::is_none")]
        latency_ms: Option<u32>,
    },
}

/// Initial full state sent on `/ws/ui` connect. Subsequent changes arrive
/// as `UiFrame` variants.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiSnapshot {
    pub edges: Vec<EdgeInfo>,
    pub service_states: Vec<ServiceStateEntry>,
    pub device_states: Vec<DeviceStateEntry>,
    pub mappings: Vec<Mapping>,
    pub glyphs: Vec<Glyph>,
}

/// Identity + status for one connected (or previously-seen) edge.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EdgeInfo {
    pub edge_id: String,
    pub online: bool,
    pub version: String,
    pub capabilities: Vec<String>,
    /// RFC3339 timestamp.
    pub last_seen: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceStateEntry {
    pub edge_id: String,
    pub service_type: String,
    pub target: String,
    pub property: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_id: Option<String>,
    pub value: serde_json::Value,
    /// RFC3339 timestamp of last update.
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceStateEntry {
    pub edge_id: String,
    pub device_type: String,
    pub device_id: String,
    pub property: String,
    pub value: serde_json::Value,
    pub updated_at: String,
}

/// A device-to-service mapping. Mirrors the structure already used by
/// `weave-server`'s REST API. `edge_id` is new; all other fields retain
/// their existing semantics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Mapping {
    pub mapping_id: Uuid,
    pub edge_id: String,
    pub device_type: String,
    pub device_id: String,
    pub service_type: String,
    pub service_target: String,
    pub routes: Vec<Route>,
    #[serde(default)]
    pub feedback: Vec<FeedbackRule>,
    #[serde(default = "default_true")]
    pub active: bool,
    /// Ordered list of candidate `service_target` values the edge can cycle
    /// through at runtime. Empty = switching disabled.
    #[serde(default)]
    pub target_candidates: Vec<TargetCandidate>,
    /// Input primitive (snake-case `InputType` name, e.g. `"long_press"`)
    /// that enters selection mode on the device. `None` = feature disabled
    /// for this mapping, regardless of `target_candidates`.
    ///
    /// MVP constraint (not enforced in-schema): at most one mapping per
    /// `(edge_id, device_id)` should set this; the edge router picks the
    /// first encountered if multiple are set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_switch_on: Option<String>,
}

/// One entry in `Mapping::target_candidates`. During selection mode the
/// device displays `glyph` and, on confirm, the mapping's `service_target`
/// is replaced with `target`.
///
/// Optional `service_type` and `routes` overrides let a single mapping's
/// candidates straddle services — e.g. `long_press` cycles between a Roon
/// zone (rotate→volume_change) and a Hue light (rotate→brightness_change),
/// each with its own route table. When absent, the candidate inherits the
/// mapping's `service_type` / `routes`, which matches pre-override behavior
/// so historical mappings deserialize unchanged.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TargetCandidate {
    /// The `service_target` value to switch to (e.g. a Roon zone ID).
    pub target: String,
    /// Human-readable label for the UI only — the edge does not need it.
    #[serde(default)]
    pub label: String,
    /// Name of a glyph in the edge's glyph registry to display while this
    /// candidate is highlighted in selection mode.
    pub glyph: String,
    /// Override the mapping's `service_type` when this candidate is active.
    /// `None` = inherit from the parent `Mapping::service_type`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_type: Option<String>,
    /// Override the mapping's `routes` when this candidate is active. Required
    /// in practice whenever `service_type` differs from the mapping's, because
    /// intents are service-specific (Roon `volume_change` won't work against
    /// a Hue target). `None` = inherit from the parent `Mapping::routes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub routes: Option<Vec<Route>>,
}

impl Mapping {
    /// Resolve the effective `(service_type, routes)` for a given target.
    /// If `target` matches a `target_candidates` entry with overrides,
    /// those win; otherwise the mapping's own fields are returned.
    ///
    /// Callers on the routing hot path should pass the currently active
    /// `service_target` to get the right adapter + intent table for the
    /// next emitted `RoutedIntent`.
    pub fn effective_for<'a>(&'a self, target: &str) -> (&'a str, &'a [Route]) {
        let candidate = self.target_candidates.iter().find(|c| c.target == target);
        let service_type = candidate
            .and_then(|c| c.service_type.as_deref())
            .unwrap_or(self.service_type.as_str());
        let routes = candidate
            .and_then(|c| c.routes.as_deref())
            .unwrap_or(self.routes.as_slice());
        (service_type, routes)
    }
}

fn default_true() -> bool {
    true
}

/// One input-to-intent route inside a mapping.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Route {
    pub input: String,
    pub intent: String,
    #[serde(default)]
    pub params: BTreeMap<String, serde_json::Value>,
}

/// Feedback rule: service state → device visual feedback.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeedbackRule {
    pub state: String,
    pub feedback_type: String,
    pub mapping: serde_json::Value,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn server_to_edge_config_full_roundtrip() {
        let msg = ServerToEdge::ConfigFull {
            config: EdgeConfig {
                edge_id: "living-room".into(),
                mappings: vec![Mapping {
                    mapping_id: Uuid::nil(),
                    edge_id: "living-room".into(),
                    device_type: "nuimo".into(),
                    device_id: "C3:81:DF:4E:FF:6A".into(),
                    service_type: "roon".into(),
                    service_target: "zone-1".into(),
                    routes: vec![Route {
                        input: "rotate".into(),
                        intent: "volume_change".into(),
                        params: BTreeMap::from([("damping".into(), serde_json::json!(80))]),
                    }],
                    feedback: vec![],
                    active: true,
                    target_candidates: vec![],
                    target_switch_on: None,
                }],
                glyphs: vec![Glyph {
                    name: "play".into(),
                    pattern: "    *    \n     **  ".into(),
                    builtin: false,
                }],
            },
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains("\"type\":\"config_full\""));
        assert!(json.contains("\"edge_id\":\"living-room\""));

        let parsed: ServerToEdge = serde_json::from_str(&json).unwrap();
        match parsed {
            ServerToEdge::ConfigFull { config } => {
                assert_eq!(config.edge_id, "living-room");
                assert_eq!(config.mappings.len(), 1);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn server_to_edge_display_glyph_roundtrip() {
        let msg = ServerToEdge::DisplayGlyph {
            device_type: "nuimo".into(),
            device_id: "C3:81:DF:4E:FF:6A".into(),
            pattern: "    *    \n  *****  ".into(),
            brightness: Some(0.5),
            timeout_ms: Some(2000),
            transition: Some("cross_fade".into()),
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains("\"type\":\"display_glyph\""));
        assert!(json.contains("\"device_type\":\"nuimo\""));
        assert!(json.contains("\"brightness\":0.5"));

        let parsed: ServerToEdge = serde_json::from_str(&json).unwrap();
        match parsed {
            ServerToEdge::DisplayGlyph {
                device_type,
                device_id,
                pattern,
                brightness,
                timeout_ms,
                transition,
            } => {
                assert_eq!(device_type, "nuimo");
                assert_eq!(device_id, "C3:81:DF:4E:FF:6A");
                assert!(pattern.contains('*'));
                assert_eq!(brightness, Some(0.5));
                assert_eq!(timeout_ms, Some(2000));
                assert_eq!(transition.as_deref(), Some("cross_fade"));
            }
            _ => panic!("wrong variant"),
        }

        // Optional fields elided when None.
        let minimal = ServerToEdge::DisplayGlyph {
            device_type: "nuimo".into(),
            device_id: "dev-1".into(),
            pattern: "*".into(),
            brightness: None,
            timeout_ms: None,
            transition: None,
        };
        let json = serde_json::to_string(&minimal).unwrap();
        assert!(!json.contains("brightness"));
        assert!(!json.contains("timeout_ms"));
        assert!(!json.contains("transition"));
    }

    #[test]
    fn server_to_edge_device_connect_disconnect_roundtrip() {
        let connect = ServerToEdge::DeviceConnect {
            device_type: "nuimo".into(),
            device_id: "dev-1".into(),
        };
        let json = serde_json::to_string(&connect).unwrap();
        assert!(json.contains("\"type\":\"device_connect\""));
        let parsed: ServerToEdge = serde_json::from_str(&json).unwrap();
        match parsed {
            ServerToEdge::DeviceConnect {
                device_type,
                device_id,
            } => {
                assert_eq!(device_type, "nuimo");
                assert_eq!(device_id, "dev-1");
            }
            _ => panic!("wrong variant"),
        }

        let disconnect = ServerToEdge::DeviceDisconnect {
            device_type: "nuimo".into(),
            device_id: "dev-1".into(),
        };
        let json = serde_json::to_string(&disconnect).unwrap();
        assert!(json.contains("\"type\":\"device_disconnect\""));
        let parsed: ServerToEdge = serde_json::from_str(&json).unwrap();
        match parsed {
            ServerToEdge::DeviceDisconnect {
                device_type,
                device_id,
            } => {
                assert_eq!(device_type, "nuimo");
                assert_eq!(device_id, "dev-1");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn edge_to_server_command_roundtrip() {
        let ok = EdgeToServer::Command {
            service_type: "roon".into(),
            target: "zone-1".into(),
            intent: "volume_change".into(),
            params: serde_json::json!({"delta": 3}),
            result: CommandResult::Ok,
            latency_ms: Some(42),
            output_id: None,
        };
        let json = serde_json::to_string(&ok).unwrap();
        assert!(json.contains("\"type\":\"command\""));
        assert!(json.contains("\"kind\":\"ok\""));
        assert!(json.contains("\"latency_ms\":42"));
        assert!(!json.contains("output_id"));
        let parsed: EdgeToServer = serde_json::from_str(&json).unwrap();
        match parsed {
            EdgeToServer::Command { intent, result, .. } => {
                assert_eq!(intent, "volume_change");
                assert!(matches!(result, CommandResult::Ok));
            }
            _ => panic!("wrong variant"),
        }

        let err = EdgeToServer::Command {
            service_type: "hue".into(),
            target: "light-1".into(),
            intent: "on_off".into(),
            params: serde_json::json!({"on": true}),
            result: CommandResult::Err {
                message: "bridge timeout".into(),
            },
            latency_ms: None,
            output_id: None,
        };
        let json = serde_json::to_string(&err).unwrap();
        assert!(json.contains("\"kind\":\"err\""));
        assert!(json.contains("\"message\":\"bridge timeout\""));
    }

    #[test]
    fn edge_to_server_error_roundtrip() {
        let msg = EdgeToServer::Error {
            context: "hue.bridge".into(),
            message: "connection refused".into(),
            severity: ErrorSeverity::Error,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains("\"type\":\"error\""));
        assert!(json.contains("\"severity\":\"error\""));
    }

    #[test]
    fn ui_frame_edge_status_roundtrip() {
        let full = UiFrame::EdgeStatus {
            edge_id: "air".into(),
            wifi: Some(82),
            latency_ms: Some(15),
        };
        let json = serde_json::to_string(&full).unwrap();
        assert!(json.contains("\"type\":\"edge_status\""));
        assert!(json.contains("\"wifi\":82"));
        assert!(json.contains("\"latency_ms\":15"));
        let parsed: UiFrame = serde_json::from_str(&json).unwrap();
        match parsed {
            UiFrame::EdgeStatus {
                edge_id,
                wifi,
                latency_ms,
            } => {
                assert_eq!(edge_id, "air");
                assert_eq!(wifi, Some(82));
                assert_eq!(latency_ms, Some(15));
            }
            _ => panic!("wrong variant"),
        }

        // Both metrics absent → only edge_id on the wire.
        let empty = UiFrame::EdgeStatus {
            edge_id: "air".into(),
            wifi: None,
            latency_ms: None,
        };
        let json = serde_json::to_string(&empty).unwrap();
        assert!(json.contains("\"edge_id\":\"air\""));
        assert!(!json.contains("wifi"));
        assert!(!json.contains("latency_ms"));
    }

    #[test]
    fn ui_frame_command_and_error_roundtrip() {
        let cmd = UiFrame::Command {
            edge_id: "air".into(),
            service_type: "roon".into(),
            target: "zone-1".into(),
            intent: "play_pause".into(),
            params: serde_json::json!({}),
            result: CommandResult::Ok,
            latency_ms: Some(18),
            output_id: None,
            at: "2026-04-23T12:00:00Z".into(),
        };
        let json = serde_json::to_string(&cmd).unwrap();
        assert!(json.contains("\"type\":\"command\""));
        let _: UiFrame = serde_json::from_str(&json).unwrap();

        let err = UiFrame::Error {
            edge_id: "air".into(),
            context: "roon.client".into(),
            message: "pair lost".into(),
            severity: ErrorSeverity::Warn,
            at: "2026-04-23T12:00:00Z".into(),
        };
        let json = serde_json::to_string(&err).unwrap();
        assert!(json.contains("\"type\":\"error\""));
        assert!(json.contains("\"severity\":\"warn\""));
        let _: UiFrame = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn edge_to_server_edge_status_roundtrip() {
        let with_wifi = EdgeToServer::EdgeStatus { wifi: Some(73) };
        let json = serde_json::to_string(&with_wifi).unwrap();
        assert!(json.contains("\"type\":\"edge_status\""));
        assert!(json.contains("\"wifi\":73"));
        let parsed: EdgeToServer = serde_json::from_str(&json).unwrap();
        match parsed {
            EdgeToServer::EdgeStatus { wifi } => assert_eq!(wifi, Some(73)),
            _ => panic!("wrong variant"),
        }

        // None should be elided from the wire form.
        let no_wifi = EdgeToServer::EdgeStatus { wifi: None };
        let json = serde_json::to_string(&no_wifi).unwrap();
        assert!(json.contains("\"type\":\"edge_status\""));
        assert!(!json.contains("wifi"));
        let parsed: EdgeToServer = serde_json::from_str(&json).unwrap();
        match parsed {
            EdgeToServer::EdgeStatus { wifi } => assert_eq!(wifi, None),
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn edge_to_server_state_with_optional_output_id() {
        let msg = EdgeToServer::State {
            service_type: "roon".into(),
            target: "zone-1".into(),
            property: "volume".into(),
            output_id: Some("output-1".into()),
            value: serde_json::json!(50),
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains("\"output_id\":\"output-1\""));

        let msg2 = EdgeToServer::State {
            service_type: "roon".into(),
            target: "zone-1".into(),
            property: "playback".into(),
            output_id: None,
            value: serde_json::json!("playing"),
        };
        let json2 = serde_json::to_string(&msg2).unwrap();
        assert!(!json2.contains("output_id"));
    }
}