shelly-liveview 0.2.0

Core runtime primitives for Shelly LiveView.
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
use crate::{Event, ShellyError};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// Message received from the browser runtime.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientMessage {
    /// Initial protocol negotiation from the browser runtime.
    Connect {
        protocol: String,
        #[serde(default)]
        session_id: Option<String>,
        #[serde(default)]
        last_revision: Option<u64>,
    },

    /// Browser event captured by the Shelly JavaScript client.
    Event {
        event: String,
        target: Option<String>,
        #[serde(default)]
        value: Value,
        #[serde(default)]
        metadata: Map<String, Value>,
    },

    /// Health check from the browser.
    Ping { nonce: Option<String> },

    /// Request an internal URL patch on the current LiveView route.
    PatchUrl { to: String },

    /// Request an internal navigation to another LiveView route.
    Navigate { to: String },

    /// Negotiate a new upload before sending chunks.
    UploadStart {
        upload_id: String,
        event: String,
        target: Option<String>,
        name: String,
        size: u64,
        content_type: Option<String>,
    },

    /// Send one base64-encoded upload chunk.
    UploadChunk {
        upload_id: String,
        offset: u64,
        data: String,
    },

    /// Finish an upload after all chunks have been sent.
    UploadComplete { upload_id: String },
}

impl TryFrom<ClientMessage> for Event {
    type Error = ShellyError;

    fn try_from(message: ClientMessage) -> Result<Self, Self::Error> {
        match message {
            ClientMessage::Connect { .. } => Err(ShellyError::InvalidMessage(
                "connect cannot be converted into a LiveView event".to_string(),
            )),
            ClientMessage::Event {
                event,
                target,
                value,
                metadata,
            } => Ok(Event {
                name: event,
                target,
                value,
                metadata,
            }),
            ClientMessage::Ping { .. } => Err(ShellyError::InvalidMessage(
                "ping cannot be converted into a LiveView event".to_string(),
            )),
            ClientMessage::PatchUrl { .. } => Err(ShellyError::InvalidMessage(
                "patch_url cannot be converted into a LiveView event".to_string(),
            )),
            ClientMessage::Navigate { .. } => Err(ShellyError::InvalidMessage(
                "navigate cannot be converted into a LiveView event".to_string(),
            )),
            ClientMessage::UploadStart { .. }
            | ClientMessage::UploadChunk { .. }
            | ClientMessage::UploadComplete { .. } => Err(ShellyError::InvalidMessage(
                "upload protocol messages cannot be converted into LiveView events".to_string(),
            )),
        }
    }
}

/// Message sent from the Rust runtime to the browser runtime.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerMessage {
    /// Sent when the WebSocket is established.
    Hello {
        session_id: String,
        target: String,
        revision: u64,
        protocol: String,
    },

    /// Replace or morph a target node's inner content.
    Patch {
        target: String,
        html: String,
        revision: u64,
    },

    /// Replace changed dynamic slots within a previously patched template.
    Diff {
        target: String,
        revision: u64,
        slots: Vec<DynamicSlotPatch>,
    },

    /// Insert one rendered item into a browser stream.
    StreamInsert {
        target: String,
        id: String,
        html: String,
        at: StreamPosition,
    },

    /// Delete one rendered item from a browser stream.
    StreamDelete { target: String, id: String },

    /// Append one point into a browser-managed chart series.
    ChartSeriesAppend {
        chart: String,
        series: String,
        point: ChartPoint,
    },

    /// Replace one chart series with a full point set.
    ChartSeriesReplace {
        chart: String,
        series: String,
        points: Vec<ChartPoint>,
    },

    /// Clear all chart series data for one chart.
    ChartReset { chart: String },

    /// Insert or replace one chart annotation.
    ChartAnnotationUpsert {
        chart: String,
        annotation: ChartAnnotation,
    },

    /// Delete one chart annotation.
    ChartAnnotationDelete { chart: String, id: String },

    /// Push one toast notification.
    ToastPush { toast: Toast },

    /// Dismiss one toast notification by id.
    ToastDismiss { id: String },

    /// Insert or replace one inbox item.
    InboxUpsert { item: InboxItem },

    /// Delete one inbox item.
    InboxDelete { id: String },

    /// Replace one enterprise grid state snapshot.
    GridReplace { grid: String, state: GridState },

    /// Dispatch one browser-side interop event.
    InteropDispatch { dispatch: JsInteropDispatch },

    /// Reply to a ping.
    Pong { nonce: Option<String> },

    /// Navigate the browser to another URL.
    Redirect { to: String },

    /// Patch the browser URL using history.pushState without replacing the view.
    PatchUrl { to: String },

    /// Navigate to another internal LiveView route using history.pushState.
    Navigate { to: String },

    /// Report upload transfer progress.
    UploadProgress {
        upload_id: String,
        received: u64,
        total: u64,
    },

    /// Report a completed upload.
    UploadComplete {
        upload_id: String,
        name: String,
        size: u64,
        content_type: Option<String>,
    },

    /// Report an upload-specific validation or transport error.
    UploadError {
        upload_id: String,
        message: String,
        code: Option<String>,
    },

    /// Report a recoverable server-side error.
    Error {
        message: String,
        code: Option<String>,
    },
}

/// Dynamic slot update sent by a `diff` server message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DynamicSlotPatch {
    pub index: usize,
    pub html: String,
}

/// One numeric chart point.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ChartPoint {
    pub x: f64,
    pub y: f64,
}

/// One chart annotation marker.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChartAnnotation {
    pub id: String,
    pub x: f64,
    pub label: String,
}

/// One toast message shown by the browser runtime.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Toast {
    pub id: String,
    pub level: ToastLevel,
    pub title: Option<String>,
    pub message: String,
    pub ttl_ms: Option<u64>,
}

/// Visual severity for a toast.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToastLevel {
    Info,
    Success,
    Warning,
    Error,
}

/// One inbox item shown by the browser runtime.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InboxItem {
    pub id: String,
    pub title: String,
    pub body: String,
    pub read: bool,
    pub inserted_at: Option<String>,
}

/// Full browser-managed data-grid state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GridState {
    #[serde(default)]
    pub columns: Vec<GridColumn>,
    #[serde(default)]
    pub rows: Vec<GridRow>,
    pub total_rows: usize,
    pub offset: usize,
    pub limit: usize,
    #[serde(default)]
    pub views: Vec<GridSavedView>,
    pub active_view: Option<String>,
    pub group_by: Option<String>,
    pub query: Option<String>,
    pub sort: Option<GridSort>,
}

/// One grid column descriptor.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GridColumn {
    pub id: String,
    pub label: String,
    pub width_px: Option<u16>,
    pub min_width_px: Option<u16>,
    #[serde(default)]
    pub pinned: GridPinned,
    #[serde(default = "default_true")]
    pub sortable: bool,
    #[serde(default = "default_true")]
    pub resizable: bool,
    #[serde(default)]
    pub editable: bool,
}

/// Grid column pin side.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum GridPinned {
    Left,
    Right,
    #[default]
    None,
}

/// One grid row record.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GridRow {
    pub id: String,
    #[serde(default)]
    pub cells: Map<String, Value>,
    pub group: Option<String>,
}

/// One saved grid view.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GridSavedView {
    pub id: String,
    pub label: String,
}

/// Active grid sort definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GridSort {
    pub column: String,
    pub direction: GridSortDirection,
}

/// Grid sort direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GridSortDirection {
    Asc,
    Desc,
}

/// One browser interop dispatch instruction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsInteropDispatch {
    pub target: Option<String>,
    pub event: String,
    #[serde(default)]
    pub detail: Value,
    #[serde(default = "default_true")]
    pub bubbles: bool,
}

fn default_true() -> bool {
    true
}

/// Position used by a `stream_insert` server message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StreamPosition {
    Append,
    Prepend,
}

#[cfg(test)]
mod tests {
    use super::{
        ChartAnnotation, ChartPoint, ClientMessage, DynamicSlotPatch, GridColumn, GridPinned,
        GridRow, GridSavedView, GridSort, GridSortDirection, GridState, InboxItem,
        JsInteropDispatch, ServerMessage, StreamPosition, Toast, ToastLevel,
    };
    use crate::Event;
    use serde_json::{json, Map};

    #[test]
    fn decodes_client_event() {
        let raw = r#"{
            "type": "event",
            "event": "inc",
            "target": "counter",
            "value": {"step": 1},
            "metadata": {"tag": "BUTTON"}
        }"#;

        let message: ClientMessage = serde_json::from_str(raw).unwrap();
        let event = Event::try_from(message).unwrap();

        assert_eq!(event.name, "inc");
        assert_eq!(event.target.as_deref(), Some("counter"));
        assert_eq!(event.value, json!({"step": 1}));
        assert_eq!(event.metadata.get("tag"), Some(&json!("BUTTON")));
    }

    #[test]
    fn decodes_protocol_connect() {
        let message: ClientMessage =
            serde_json::from_value(json!({"type": "connect", "protocol": "shelly/1"})).unwrap();

        assert_eq!(
            message,
            ClientMessage::Connect {
                protocol: "shelly/1".to_string(),
                session_id: None,
                last_revision: None,
            }
        );
    }

    #[test]
    fn decodes_protocol_connect_resume_hints() {
        let message: ClientMessage = serde_json::from_value(json!({
            "type": "connect",
            "protocol": "shelly/1",
            "session_id": "sid-1",
            "last_revision": 7
        }))
        .unwrap();

        assert_eq!(
            message,
            ClientMessage::Connect {
                protocol: "shelly/1".to_string(),
                session_id: Some("sid-1".to_string()),
                last_revision: Some(7),
            }
        );
    }

    #[test]
    fn decodes_navigation_requests() {
        assert_eq!(
            serde_json::from_value::<ClientMessage>(json!({
                "type": "patch_url",
                "to": "/pages/intro"
            }))
            .unwrap(),
            ClientMessage::PatchUrl {
                to: "/pages/intro".to_string()
            }
        );
        assert_eq!(
            serde_json::from_value::<ClientMessage>(json!({
                "type": "navigate",
                "to": "/users/1"
            }))
            .unwrap(),
            ClientMessage::Navigate {
                to: "/users/1".to_string()
            }
        );
    }

    #[test]
    fn decodes_upload_requests() {
        assert_eq!(
            serde_json::from_value::<ClientMessage>(json!({
                "type": "upload_start",
                "upload_id": "up-1",
                "event": "uploaded",
                "target": "file",
                "name": "notes.txt",
                "size": 12,
                "content_type": "text/plain"
            }))
            .unwrap(),
            ClientMessage::UploadStart {
                upload_id: "up-1".to_string(),
                event: "uploaded".to_string(),
                target: Some("file".to_string()),
                name: "notes.txt".to_string(),
                size: 12,
                content_type: Some("text/plain".to_string()),
            }
        );
        assert_eq!(
            serde_json::from_value::<ClientMessage>(json!({
                "type": "upload_chunk",
                "upload_id": "up-1",
                "offset": 0,
                "data": "aGVsbG8="
            }))
            .unwrap(),
            ClientMessage::UploadChunk {
                upload_id: "up-1".to_string(),
                offset: 0,
                data: "aGVsbG8=".to_string(),
            }
        );
        assert_eq!(
            serde_json::from_value::<ClientMessage>(json!({
                "type": "upload_complete",
                "upload_id": "up-1"
            }))
            .unwrap(),
            ClientMessage::UploadComplete {
                upload_id: "up-1".to_string()
            }
        );
    }

    #[test]
    fn encodes_server_patch() {
        let message = ServerMessage::Patch {
            target: "shelly-root".to_string(),
            html: "<p>ok</p>".to_string(),
            revision: 2,
        };

        let encoded = serde_json::to_value(message).unwrap();
        assert_eq!(encoded["type"], "patch");
        assert_eq!(encoded["target"], "shelly-root");
        assert_eq!(encoded["revision"], 2);
    }

    #[test]
    fn encodes_server_diff() {
        let message = ServerMessage::Diff {
            target: "shelly-root".to_string(),
            revision: 3,
            slots: vec![DynamicSlotPatch {
                index: 0,
                html: "2".to_string(),
            }],
        };

        let encoded = serde_json::to_value(message).unwrap();
        assert_eq!(
            encoded,
            json!({
                "type": "diff",
                "target": "shelly-root",
                "revision": 3,
                "slots": [{"index": 0, "html": "2"}]
            })
        );
    }

    #[test]
    fn encodes_stream_messages() {
        assert_eq!(
            serde_json::to_value(ServerMessage::StreamInsert {
                target: "messages".to_string(),
                id: "msg-1".to_string(),
                html: "<li id=\"msg-1\">hi</li>".to_string(),
                at: StreamPosition::Append,
            })
            .unwrap(),
            json!({
                "type": "stream_insert",
                "target": "messages",
                "id": "msg-1",
                "html": "<li id=\"msg-1\">hi</li>",
                "at": "append"
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::StreamDelete {
                target: "messages".to_string(),
                id: "msg-1".to_string(),
            })
            .unwrap(),
            json!({
                "type": "stream_delete",
                "target": "messages",
                "id": "msg-1"
            })
        );
    }

    #[test]
    fn encodes_chart_messages() {
        assert_eq!(
            serde_json::to_value(ServerMessage::ChartSeriesAppend {
                chart: "traffic-chart".to_string(),
                series: "requests".to_string(),
                point: ChartPoint { x: 4.0, y: 11.5 },
            })
            .unwrap(),
            json!({
                "type": "chart_series_append",
                "chart": "traffic-chart",
                "series": "requests",
                "point": {
                    "x": 4.0,
                    "y": 11.5
                }
            })
        );

        assert_eq!(
            serde_json::to_value(ServerMessage::ChartSeriesReplace {
                chart: "traffic-chart".to_string(),
                series: "requests".to_string(),
                points: vec![
                    ChartPoint { x: 1.0, y: 10.0 },
                    ChartPoint { x: 2.0, y: 11.5 }
                ],
            })
            .unwrap(),
            json!({
                "type": "chart_series_replace",
                "chart": "traffic-chart",
                "series": "requests",
                "points": [
                    {"x": 1.0, "y": 10.0},
                    {"x": 2.0, "y": 11.5}
                ]
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::ChartReset {
                chart: "traffic-chart".to_string(),
            })
            .unwrap(),
            json!({
                "type": "chart_reset",
                "chart": "traffic-chart"
            })
        );

        assert_eq!(
            serde_json::to_value(ServerMessage::ChartAnnotationUpsert {
                chart: "traffic-chart".to_string(),
                annotation: ChartAnnotation {
                    id: "release-1".to_string(),
                    x: 18.0,
                    label: "Deploy".to_string(),
                },
            })
            .unwrap(),
            json!({
                "type": "chart_annotation_upsert",
                "chart": "traffic-chart",
                "annotation": {
                    "id": "release-1",
                    "x": 18.0,
                    "label": "Deploy"
                }
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::ChartAnnotationDelete {
                chart: "traffic-chart".to_string(),
                id: "release-1".to_string(),
            })
            .unwrap(),
            json!({
                "type": "chart_annotation_delete",
                "chart": "traffic-chart",
                "id": "release-1"
            })
        );
    }

    #[test]
    fn encodes_toast_and_inbox_messages() {
        assert_eq!(
            serde_json::to_value(ServerMessage::ToastPush {
                toast: Toast {
                    id: "toast-1".to_string(),
                    level: ToastLevel::Success,
                    title: Some("Saved".to_string()),
                    message: "Profile updated".to_string(),
                    ttl_ms: Some(2500),
                },
            })
            .unwrap(),
            json!({
                "type": "toast_push",
                "toast": {
                    "id": "toast-1",
                    "level": "success",
                    "title": "Saved",
                    "message": "Profile updated",
                    "ttl_ms": 2500
                }
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::ToastDismiss {
                id: "toast-1".to_string(),
            })
            .unwrap(),
            json!({
                "type": "toast_dismiss",
                "id": "toast-1"
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::InboxUpsert {
                item: InboxItem {
                    id: "msg-1".to_string(),
                    title: "Welcome".to_string(),
                    body: "Thanks for joining".to_string(),
                    read: false,
                    inserted_at: Some("2026-05-05T12:00:00Z".to_string()),
                },
            })
            .unwrap(),
            json!({
                "type": "inbox_upsert",
                "item": {
                    "id": "msg-1",
                    "title": "Welcome",
                    "body": "Thanks for joining",
                    "read": false,
                    "inserted_at": "2026-05-05T12:00:00Z"
                }
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::InboxDelete {
                id: "msg-1".to_string(),
            })
            .unwrap(),
            json!({
                "type": "inbox_delete",
                "id": "msg-1"
            })
        );

        assert_eq!(
            serde_json::to_value(ServerMessage::GridReplace {
                grid: "enterprise-grid".to_string(),
                state: GridState {
                    columns: vec![
                        GridColumn {
                            id: "name".to_string(),
                            label: "Name".to_string(),
                            width_px: Some(220),
                            min_width_px: Some(120),
                            pinned: GridPinned::Left,
                            sortable: true,
                            resizable: true,
                            editable: false,
                        },
                        GridColumn {
                            id: "arr".to_string(),
                            label: "ARR".to_string(),
                            width_px: Some(120),
                            min_width_px: Some(80),
                            pinned: GridPinned::None,
                            sortable: true,
                            resizable: true,
                            editable: true,
                        },
                    ],
                    rows: vec![GridRow {
                        id: "acct-1".to_string(),
                        cells: Map::from_iter([
                            ("name".to_string(), json!("Acme")),
                            ("arr".to_string(), json!(125000)),
                        ]),
                        group: Some("Enterprise".to_string()),
                    }],
                    total_rows: 1000,
                    offset: 0,
                    limit: 100,
                    views: vec![GridSavedView {
                        id: "ops".to_string(),
                        label: "Ops".to_string(),
                    }],
                    active_view: Some("ops".to_string()),
                    group_by: Some("segment".to_string()),
                    query: Some("acme".to_string()),
                    sort: Some(GridSort {
                        column: "arr".to_string(),
                        direction: GridSortDirection::Desc,
                    }),
                },
            })
            .unwrap(),
            json!({
                "type": "grid_replace",
                "grid": "enterprise-grid",
                "state": {
                    "columns": [
                        {
                            "id": "name",
                            "label": "Name",
                            "width_px": 220,
                            "min_width_px": 120,
                            "pinned": "left",
                            "sortable": true,
                            "resizable": true,
                            "editable": false
                        },
                        {
                            "id": "arr",
                            "label": "ARR",
                            "width_px": 120,
                            "min_width_px": 80,
                            "pinned": "none",
                            "sortable": true,
                            "resizable": true,
                            "editable": true
                        }
                    ],
                    "rows": [
                        {
                            "id": "acct-1",
                            "cells": {
                                "name": "Acme",
                                "arr": 125000
                            },
                            "group": "Enterprise"
                        }
                    ],
                    "total_rows": 1000,
                    "offset": 0,
                    "limit": 100,
                    "views": [
                        {
                            "id": "ops",
                            "label": "Ops"
                        }
                    ],
                    "active_view": "ops",
                    "group_by": "segment",
                    "query": "acme",
                    "sort": {
                        "column": "arr",
                        "direction": "desc"
                    }
                }
            })
        );

        assert_eq!(
            serde_json::to_value(ServerMessage::InteropDispatch {
                dispatch: JsInteropDispatch {
                    target: Some("peer-a".to_string()),
                    event: "shelly:webrtc-signal".to_string(),
                    detail: json!({"kind": "offer", "sdp": "v=0..."}),
                    bubbles: true,
                },
            })
            .unwrap(),
            json!({
                "type": "interop_dispatch",
                "dispatch": {
                    "target": "peer-a",
                    "event": "shelly:webrtc-signal",
                    "detail": {"kind": "offer", "sdp": "v=0..."},
                    "bubbles": true
                }
            })
        );
    }

    #[test]
    fn encodes_navigation_messages() {
        assert_eq!(
            serde_json::to_value(ServerMessage::PatchUrl {
                to: "/pages/intro".to_string(),
            })
            .unwrap(),
            json!({"type": "patch_url", "to": "/pages/intro"})
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::Navigate {
                to: "/users/1".to_string(),
            })
            .unwrap(),
            json!({"type": "navigate", "to": "/users/1"})
        );
    }

    #[test]
    fn encodes_upload_status_messages() {
        assert_eq!(
            serde_json::to_value(ServerMessage::UploadProgress {
                upload_id: "up-1".to_string(),
                received: 5,
                total: 10,
            })
            .unwrap(),
            json!({
                "type": "upload_progress",
                "upload_id": "up-1",
                "received": 5,
                "total": 10
            })
        );
        assert_eq!(
            serde_json::to_value(ServerMessage::UploadError {
                upload_id: "up-1".to_string(),
                message: "too large".to_string(),
                code: Some("upload_too_large".to_string()),
            })
            .unwrap(),
            json!({
                "type": "upload_error",
                "upload_id": "up-1",
                "message": "too large",
                "code": "upload_too_large"
            })
        );
    }

    #[test]
    fn rejects_unknown_client_message_type() {
        let decoded = serde_json::from_value::<ClientMessage>(json!({
            "type": "do_the_thing",
            "payload": {}
        }));
        assert!(decoded.is_err());
    }

    #[test]
    fn rejects_event_without_event_name() {
        let decoded = serde_json::from_value::<ClientMessage>(json!({
            "type": "event",
            "target": "counter",
            "value": {"step": 1}
        }));
        assert!(decoded.is_err());
    }

    #[test]
    fn rejects_upload_chunk_without_required_fields() {
        let missing_data = serde_json::from_value::<ClientMessage>(json!({
            "type": "upload_chunk",
            "upload_id": "up-1",
            "offset": 0
        }));
        assert!(missing_data.is_err());

        let missing_offset = serde_json::from_value::<ClientMessage>(json!({
            "type": "upload_chunk",
            "upload_id": "up-1",
            "data": "aGVsbG8="
        }));
        assert!(missing_offset.is_err());
    }
}