magic-coder-types 0.30.0

Shared protocol + tool schemas for Magic Coder.
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Role {
    Assistant,
    User,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum RuntimeMode {
    Agent,
    Plan,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ToolExecutionTarget {
    Unspecified,
    /// Tool must be executed by a connected client (TUI/VS Code).
    ClientLocal,
    /// Tool is executed server-side (agents/MCP/etc). Clients must not provide outputs.
    ServerAgents,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ToolCallApproval {
    Unspecified,
    Pending,
    Approved,
    AutoApproved,
    Rejected,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ModelConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<String>,
    /// Optional long-context toggle. When omitted, the server keeps its current/default behavior.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_long_context: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ThreadModelOverride {
    pub model_id: Uuid,
    pub model_config: ModelConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallOutput {
    /// Tool call id
    pub id: String,

    pub is_error: bool,
    pub output: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_seconds: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SubagentEscalationResolution {
    Approved,
    Rejected {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
    },
    ResolvedWithOutput {
        #[serde(default)]
        is_error: bool,
        output: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_seconds: Option<i32>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Skill {
    pub name: String,
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Rule {
    pub name: String,
    pub description: String,
    pub text: Option<String>,
    #[serde(default)]
    pub always_apply: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkingDirectory {
    pub path: String,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_branch: Option<String>,
    #[serde(default)]
    pub agents_md: String,
    #[serde(default)]
    pub rules: Vec<Rule>,
    #[serde(default)]
    pub skills: Vec<Skill>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LocalMcpServerSource {
    UserGlobal,
    UserProject,
    Project,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LocalMcpServerStatus {
    Connected,
    Disconnected,
    Error,
    Shadowed,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LocalMcpTool {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub input_schema: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LocalMcpResource {
    pub uri: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LocalMcpResourceTemplate {
    pub uri_template: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LocalMcpServer {
    pub id: Uuid,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub source: LocalMcpServerSource,
    pub status: LocalMcpServerStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status_detail: Option<String>,
    #[serde(default)]
    pub tools: Vec<LocalMcpTool>,
    #[serde(default)]
    pub resources: Vec<LocalMcpResource>,
    #[serde(default)]
    pub resource_templates: Vec<LocalMcpResourceTemplate>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BackgroundShellStatus {
    Running,
    Exited,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BackgroundShellSnapshot {
    pub shell_id: String,
    pub command: String,
    pub status: BackgroundShellStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    pub log_lines: u64,
    pub duration_seconds: u64,
}

trait BoolExt {
    fn is_false(&self) -> bool;
}

impl BoolExt for bool {
    fn is_false(&self) -> bool {
        !*self
    }
}

/// Normalized operating system family reported by a client during the handshake.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum Os {
    /// The client could not determine a supported OS family.
    #[default]
    #[serde(rename = "other")]
    Other,
    /// Linux distributions.
    #[serde(rename = "linux")]
    Linux,
    /// macOS / Darwin.
    #[serde(rename = "macos")]
    MacOS,
    /// Microsoft Windows.
    #[serde(rename = "windows")]
    Windows,
}

/// Normalized CPU architecture reported by a client during the handshake.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum Arch {
    /// The client could not determine a supported CPU architecture.
    #[default]
    #[serde(rename = "other")]
    Other,
    /// 32-bit x86.
    #[serde(rename = "x86")]
    X86,
    /// 64-bit x86.
    #[serde(rename = "amd64")]
    Amd64,
    /// 64-bit ARM.
    #[serde(rename = "aarch64")]
    Aarch64,
}

/// Snapshot of coarse client machine characteristics captured when the socket connects.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct ClientSystemInfo {
    /// Operating system family.
    pub os: Os,
    /// Human-readable OS version string reported by the client.
    pub os_version: String,
    /// CPU architecture family.
    pub arch: Arch,
    /// Logical CPU core count.
    pub cpu_cores: u16,
    /// Total physical memory reported by the client, in whole megabytes.
    pub ram_mb: u32,
}

impl ClientSystemInfo {
    fn is_unknown(&self) -> bool {
        self == &Self::default()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClientMessage {
    HelloMath {
        /// Random per-client-instance id (generated on client startup).
        ///
        /// Used for multi-client tool-call claiming/coordination. Not derived from auth token.
        client_instance_id: String,
        /// Client version.
        version: String,
        /// Minimum supported server version (the client can work with any server >= this).
        min_supported_version: String,
        /// Optional thread root message id used by reconnecting clients to restore active thread state.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resume_thread_id: Option<Uuid>,
        /// Whether the client is currently running in automagic mode.
        #[serde(default, skip_serializing_if = "BoolExt::is_false")]
        automagic: bool,
        /// Normalized snapshot of the client machine.
        ///
        /// Older clients may omit this; missing values deserialize as "unknown".
        #[serde(default, skip_serializing_if = "ClientSystemInfo::is_unknown")]
        system_info: ClientSystemInfo,
    },
    /// Send a user message.
    ///
    /// If `thread_id` is `None`, the server creates a new thread and returns it in `SendMessageAck`.
    /// `request_id` is a client-generated correlation id for 1:1 request↔response mapping.
    SendMessage {
        request_id: Uuid,
        thread_id: Option<Uuid>,
        text: String,
        /// Optional runtime mode update to apply to the thread before generation.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        runtime_mode: Option<RuntimeMode>,
        /// Optional model override update to apply to the thread before generation.
        ///
        /// - `None`: do not change current override.
        /// - `Some(value)`: set override to `value`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        model_override: Option<ThreadModelOverride>,
    },
    /// Update/refresh auth token without reconnecting the WebSocket.
    UpdateAuthToken {
        token: String,
    },
    /// Replace the client-local working directory snapshot exposed to the server for this connection.
    ///
    /// Sent separately from `HelloMath` so working directory state can be updated without reconnecting.
    UpdateWorkingDirectories {
        working_directories: Vec<WorkingDirectory>,
    },
    /// Replace the client-local MCP catalog exposed to the server for this connection.
    ///
    /// The catalog is sanitized: it contains server ids, metadata, status, tools,
    /// resources, and resource templates, but never local commands, environment,
    /// headers, or tokens.
    UpdateMcpServers {
        servers: Vec<LocalMcpServer>,
    },
    /// Replace the client-local background shell snapshot for this connection.
    UpdateBackgroundShells {
        shells: Vec<BackgroundShellSnapshot>,
    },
    RejectToolCall {
        id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
    },
    AcceptToolCall {
        id: String,
    },
    ResolveSubagentEscalation {
        parent_message_id: Uuid,
        subagent_run_id: Uuid,
        escalation_id: String,
        resolution: SubagentEscalationResolution,
    },
    ToolCallOutputs {
        outputs: Vec<ToolCallOutput>,
    },
    /// Cancel the current in-progress generation for a specific assistant message.
    CancelGeneration {
        message_id: Uuid,
    },
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Usage {
    pub input_tokens: i32,
    pub output_tokens: i32,
    #[serde(default)]
    pub cache_read_input_tokens: i32,
    #[serde(default)]
    pub cache_creation_input_tokens: i32,
    #[serde(default)]
    pub cache_creation_input_tokens_5m: i32,
    #[serde(default)]
    pub cache_creation_input_tokens_1h: i32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum MessageStatus {
    Completed,
    /// The agent is waiting for the client/user to provide more input (e.g. tool outputs / approvals)
    /// before it can continue generation.
    WaitingForUser,
    Failed,
    Cancelled,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ServerMessage {
    HelloMagic {
        version: String,
        min_supported_version: String,
    },
    VersionMismatch {
        server_version: String,
        server_min_supported_version: String,
    },
    Goodbye {
        reconnect: bool,
    },
    SendMessageAck {
        request_id: Uuid,
        thread_id: Uuid,
        user_message_id: Uuid,
    },
    AuthUpdated,
    RuntimeModeUpdated {
        thread_id: Uuid,
        mode: RuntimeMode,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        changed_by_client_instance_id: Option<String>,
    },
    ThreadModelUpdated {
        thread_id: Uuid,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        model_override: Option<ThreadModelOverride>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        changed_by_client_instance_id: Option<String>,
    },
    MessageHeader {
        message_id: Uuid,
        thread_id: Uuid,
        role: Role,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        request_id: Option<Uuid>,
    },
    ReasoningDelta {
        message_id: Uuid,
        content: String,
    },
    TextDelta {
        message_id: Uuid,
        content: String,
    },
    ToolCallHeader {
        message_id: Uuid,
        tool_call_id: String,
        name: String,
        execution_target: ToolExecutionTarget,
        approval: ToolCallApproval,
    },
    ToolCallArgumentsDelta {
        message_id: Uuid,
        tool_call_id: String,
        delta: String,
    },
    ToolCall {
        message_id: Uuid,
        tool_call_id: String,
        args: Value,
    },
    ToolCallResult {
        message_id: Uuid,
        tool_call_id: String,
        is_error: bool,
        output: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_seconds: Option<i32>,
    },
    ToolCallClaimed {
        message_id: Uuid,
        tool_call_id: String,
        claimed_by_client_instance_id: String,
    },
    ToolCallApprovalUpdated {
        message_id: Uuid,
        tool_call_id: String,
        approval: ToolCallApproval,
    },
    MessageDone {
        message_id: Uuid,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        usage: Option<Usage>,
        status: MessageStatus,
    },
    Error {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        request_id: Option<Uuid>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message_id: Option<Uuid>,
        code: String,
        message: String,
    },
}

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

    fn background_shell_snapshot(
        shell_id: &str,
        status: BackgroundShellStatus,
    ) -> BackgroundShellSnapshot {
        BackgroundShellSnapshot {
            shell_id: shell_id.to_string(),
            command: "sleep 30".to_string(),
            status,
            exit_code: (status == BackgroundShellStatus::Exited).then_some(0),
            log_lines: 12,
            duration_seconds: 18,
        }
    }

    fn hello_math(resume_thread_id: Option<Uuid>) -> ClientMessage {
        ClientMessage::HelloMath {
            client_instance_id: "client-a".to_string(),
            version: "1.2.3".to_string(),
            min_supported_version: "1.0.0".to_string(),
            resume_thread_id,
            automagic: false,
            system_info: ClientSystemInfo::default(),
        }
    }

    #[test]
    fn model_config_omits_allow_long_context_when_not_set() {
        let config = ModelConfig::default();

        let value = serde_json::to_value(config).expect("serialize");
        let body = value.as_object().expect("model config body");

        assert!(body.get("allow_long_context").is_none());
    }

    #[test]
    fn model_config_round_trips_allow_long_context_when_set() {
        for expected in [true, false] {
            let config = ModelConfig {
                allow_long_context: Some(expected),
                ..ModelConfig::default()
            };

            let value = serde_json::to_value(&config).expect("serialize");
            let body = value.as_object().expect("model config body");
            assert_eq!(body.get("allow_long_context"), Some(&json!(expected)));

            let back: ModelConfig = serde_json::from_value(value).expect("deserialize");
            assert_eq!(back.allow_long_context, Some(expected));
        }
    }

    #[test]
    fn model_config_defaults_allow_long_context_to_none_when_missing() {
        let back: ModelConfig = serde_json::from_value(json!({
            "temperature": 0.3
        }))
        .expect("deserialize");

        assert_eq!(back.temperature, Some(0.3));
        assert_eq!(back.allow_long_context, None);
    }

    #[test]
    fn send_message_omits_optional_updates_when_not_set() {
        let msg = ClientMessage::SendMessage {
            request_id: Uuid::nil(),
            thread_id: None,
            text: "hello".to_string(),
            runtime_mode: None,
            model_override: None,
        };

        let value = serde_json::to_value(msg).expect("serialize");
        let body = value
            .get("SendMessage")
            .and_then(|v| v.as_object())
            .expect("SendMessage body");

        assert!(body.get("runtime_mode").is_none());
        assert!(body.get("model_override").is_none());
    }

    #[test]
    fn hello_math_omits_resume_thread_id_when_not_set() {
        let msg = hello_math(None);

        let value = serde_json::to_value(msg).expect("serialize");
        let body = value
            .get("HelloMath")
            .and_then(|v| v.as_object())
            .expect("HelloMath body");

        assert!(body.get("resume_thread_id").is_none());
        assert!(body.get("automagic").is_none());
        assert!(body.get("system_info").is_none());
    }

    #[test]
    fn hello_math_round_trip_resume_thread_id() {
        let thread_id = Uuid::new_v4();
        let msg = hello_math(Some(thread_id));

        let value = serde_json::to_value(&msg).expect("serialize");
        let body = value
            .get("HelloMath")
            .and_then(|v| v.as_object())
            .expect("HelloMath body");
        assert_eq!(
            body.get("resume_thread_id"),
            Some(&serde_json::Value::String(thread_id.to_string()))
        );

        let back: ClientMessage = serde_json::from_value(value).expect("deserialize");
        match back {
            ClientMessage::HelloMath {
                resume_thread_id, ..
            } => assert_eq!(resume_thread_id, Some(thread_id)),
            _ => panic!("expected HelloMath"),
        }
    }

    #[test]
    fn hello_math_deserializes_defaults_for_new_fields() {
        let value = json!({
            "HelloMath": {
                "client_instance_id": "client-a",
                "version": "1.2.3",
                "min_supported_version": "1.0.0"
            }
        });

        let back: ClientMessage = serde_json::from_value(value).expect("deserialize");
        match back {
            ClientMessage::HelloMath {
                automagic,
                system_info,
                ..
            } => {
                assert!(!automagic);
                assert_eq!(system_info, ClientSystemInfo::default());
            }
            _ => panic!("expected HelloMath"),
        }
    }

    #[test]
    fn hello_math_serializes_non_default_system_info() {
        let msg = ClientMessage::HelloMath {
            client_instance_id: "client-a".to_string(),
            version: "1.2.3".to_string(),
            min_supported_version: "1.0.0".to_string(),
            resume_thread_id: None,
            automagic: true,
            system_info: ClientSystemInfo {
                os: Os::MacOS,
                os_version: "15.5".to_string(),
                arch: Arch::Amd64,
                cpu_cores: 10,
                ram_mb: 32768,
            },
        };

        let value = serde_json::to_value(msg).expect("serialize");
        let body = value
            .get("HelloMath")
            .and_then(|v| v.as_object())
            .expect("HelloMath body");

        assert_eq!(body.get("automagic"), Some(&json!(true)));
        assert_eq!(
            body.get("system_info"),
            Some(&json!({
                "os": "macos",
                "os_version": "15.5",
                "arch": "amd64",
                "cpu_cores": 10,
                "ram_mb": 32768
            }))
        );
    }

    #[test]
    fn hello_math_deserializes_canonical_arch_names() {
        let value = json!({
            "HelloMath": {
                "client_instance_id": "client-a",
                "version": "1.2.3",
                "min_supported_version": "1.0.0",
                "system_info": {
                    "os": "linux",
                    "os_version": "6.8",
                    "arch": "amd64",
                    "cpu_cores": 8,
                    "ram_mb": 16384
                }
            }
        });

        let back: ClientMessage = serde_json::from_value(value).expect("deserialize");
        match back {
            ClientMessage::HelloMath { system_info, .. } => {
                assert_eq!(system_info.arch, Arch::Amd64);
            }
            _ => panic!("expected HelloMath"),
        }
    }

    #[test]
    fn send_message_serializes_model_override_when_set() {
        let msg = ClientMessage::SendMessage {
            request_id: Uuid::nil(),
            thread_id: Some(Uuid::nil()),
            text: "hello".to_string(),
            runtime_mode: Some(RuntimeMode::Plan),
            model_override: Some(ThreadModelOverride {
                model_id: Uuid::nil(),
                model_config: ModelConfig::default(),
            }),
        };

        let value = serde_json::to_value(msg).expect("serialize");
        let body = value
            .get("SendMessage")
            .and_then(|v| v.as_object())
            .expect("SendMessage body");

        assert_eq!(body.get("runtime_mode"), Some(&json!("Plan")));
        assert!(body.get("model_override").is_some());
    }

    #[test]
    fn send_message_deserializes_model_override_states() {
        let set_json = json!({
            "SendMessage": {
                "request_id": Uuid::nil(),
                "thread_id": Uuid::nil(),
                "text": "hello",
                "runtime_mode": "Agent",
                "model_override": {
                    "model_id": Uuid::nil(),
                    "model_config": {}
                }
            }
        });
        let keep_json = json!({
            "SendMessage": {
                "request_id": Uuid::nil(),
                "thread_id": Uuid::nil(),
                "text": "hello"
            }
        });

        let set_msg: ClientMessage = serde_json::from_value(set_json).expect("deserialize set");
        let keep_msg: ClientMessage = serde_json::from_value(keep_json).expect("deserialize keep");

        match set_msg {
            ClientMessage::SendMessage {
                runtime_mode,
                model_override,
                ..
            } => {
                assert_eq!(runtime_mode, Some(RuntimeMode::Agent));
                assert!(model_override.is_some());
            }
            _ => panic!("expected SendMessage"),
        }

        match keep_msg {
            ClientMessage::SendMessage { model_override, .. } => {
                assert_eq!(model_override, None);
            }
            _ => panic!("expected SendMessage"),
        }
    }

    #[test]
    fn update_working_directories_round_trip_full_and_empty() {
        let demo_agents_md = r#"# Demo project

- Keep changes small.
- Run `cargo test`.
"#
        .trim()
        .to_string();

        let full = ClientMessage::UpdateWorkingDirectories {
            working_directories: vec![WorkingDirectory {
                path: "/Users/dev/project".to_string(),
                git_branch: None,
                agents_md: demo_agents_md.clone(),
                rules: vec![Rule {
                    name: "Test after changes".to_string(),
                    description: "Run the relevant tests before finishing.".to_string(),
                    text: None,
                    always_apply: true,
                }],
                skills: vec![Skill {
                    name: "Build skill".to_string(),
                    description: "Run and fix build failures".to_string(),
                }],
            }],
        };
        let empty = ClientMessage::UpdateWorkingDirectories {
            working_directories: vec![],
        };

        let full_json = serde_json::to_value(&full).expect("serialize full");
        let empty_json = serde_json::to_value(&empty).expect("serialize empty");

        let full_back: ClientMessage = serde_json::from_value(full_json).expect("deserialize full");
        let empty_back: ClientMessage =
            serde_json::from_value(empty_json).expect("deserialize empty");

        match full_back {
            ClientMessage::UpdateWorkingDirectories {
                working_directories,
            } => {
                assert_eq!(working_directories.len(), 1);
                assert_eq!(working_directories[0].path, "/Users/dev/project");
                assert_eq!(working_directories[0].agents_md, demo_agents_md);
                assert_eq!(working_directories[0].rules.len(), 1);
                assert_eq!(working_directories[0].rules[0].name, "Test after changes");
                assert_eq!(
                    working_directories[0].rules[0].description,
                    "Run the relevant tests before finishing."
                );
                assert!(working_directories[0].rules[0].always_apply);
                assert_eq!(working_directories[0].skills.len(), 1);
                assert_eq!(working_directories[0].skills[0].name, "Build skill");
                assert_eq!(
                    working_directories[0].skills[0].description,
                    "Run and fix build failures"
                );
            }
            _ => panic!("expected UpdateWorkingDirectories"),
        }

        match empty_back {
            ClientMessage::UpdateWorkingDirectories {
                working_directories,
            } => {
                assert!(working_directories.is_empty());
            }
            _ => panic!("expected UpdateWorkingDirectories"),
        }
    }

    #[test]
    fn update_working_directories_defaults_missing_nested_fields() {
        let json = json!({
            "UpdateWorkingDirectories": {
                "working_directories": [{
                    "path": "/Users/dev/project"
                }]
            }
        });

        let back: ClientMessage = serde_json::from_value(json).expect("deserialize");

        match back {
            ClientMessage::UpdateWorkingDirectories {
                working_directories,
            } => {
                assert_eq!(working_directories.len(), 1);
                assert_eq!(working_directories[0].path, "/Users/dev/project");
                assert!(working_directories[0].agents_md.is_empty());
                assert!(working_directories[0].rules.is_empty());
                assert!(working_directories[0].skills.is_empty());
            }
            _ => panic!("expected UpdateWorkingDirectories"),
        }
    }

    #[test]
    fn update_background_shells_round_trip_full_and_empty() {
        let full = ClientMessage::UpdateBackgroundShells {
            shells: vec![
                background_shell_snapshot("bg_1", BackgroundShellStatus::Running),
                background_shell_snapshot("bg_2", BackgroundShellStatus::Exited),
            ],
        };
        let empty = ClientMessage::UpdateBackgroundShells { shells: vec![] };

        let full_json = serde_json::to_value(&full).expect("serialize full");
        let empty_json = serde_json::to_value(&empty).expect("serialize empty");

        let full_back: ClientMessage = serde_json::from_value(full_json).expect("deserialize full");
        let empty_back: ClientMessage =
            serde_json::from_value(empty_json).expect("deserialize empty");

        match full_back {
            ClientMessage::UpdateBackgroundShells { shells } => {
                assert_eq!(shells.len(), 2);
                assert_eq!(shells[0].shell_id, "bg_1");
                assert_eq!(shells[0].status, BackgroundShellStatus::Running);
                assert_eq!(shells[0].exit_code, None);
                assert_eq!(shells[1].status, BackgroundShellStatus::Exited);
                assert_eq!(shells[1].exit_code, Some(0));
            }
            _ => panic!("expected UpdateBackgroundShells"),
        }

        match empty_back {
            ClientMessage::UpdateBackgroundShells { shells } => {
                assert!(shells.is_empty());
            }
            _ => panic!("expected UpdateBackgroundShells"),
        }
    }

    #[test]
    fn resolve_subagent_escalation_approved_round_trip() {
        let msg = ClientMessage::ResolveSubagentEscalation {
            parent_message_id: Uuid::nil(),
            subagent_run_id: Uuid::nil(),
            escalation_id: "esc-0".to_string(),
            resolution: SubagentEscalationResolution::Approved,
        };

        let value = serde_json::to_value(&msg).expect("serialize");
        let back: ClientMessage = serde_json::from_value(value).expect("deserialize");
        match back {
            ClientMessage::ResolveSubagentEscalation {
                escalation_id,
                resolution: SubagentEscalationResolution::Approved,
                ..
            } => assert_eq!(escalation_id, "esc-0"),
            _ => panic!("expected ResolveSubagentEscalation::Approved"),
        }
    }

    #[test]
    fn resolve_subagent_escalation_rejected_round_trip() {
        let msg = ClientMessage::ResolveSubagentEscalation {
            parent_message_id: Uuid::nil(),
            subagent_run_id: Uuid::nil(),
            escalation_id: "esc-1".to_string(),
            resolution: SubagentEscalationResolution::Rejected {
                reason: Some("not now".to_string()),
            },
        };

        let value = serde_json::to_value(&msg).expect("serialize");
        let body = value
            .get("ResolveSubagentEscalation")
            .and_then(|v| v.as_object())
            .expect("ResolveSubagentEscalation body");
        assert_eq!(body.get("escalation_id"), Some(&json!("esc-1")));

        let back: ClientMessage = serde_json::from_value(value).expect("deserialize");
        match back {
            ClientMessage::ResolveSubagentEscalation {
                resolution:
                    SubagentEscalationResolution::Rejected {
                        reason: Some(reason),
                    },
                ..
            } => assert_eq!(reason, "not now"),
            _ => panic!("expected ResolveSubagentEscalation::Rejected"),
        }
    }

    #[test]
    fn resolve_subagent_escalation_resolved_with_output_round_trip() {
        let msg = ClientMessage::ResolveSubagentEscalation {
            parent_message_id: Uuid::nil(),
            subagent_run_id: Uuid::nil(),
            escalation_id: "esc-2".to_string(),
            resolution: SubagentEscalationResolution::ResolvedWithOutput {
                is_error: false,
                output: "ok".to_string(),
                duration_seconds: Some(3),
            },
        };

        let value = serde_json::to_value(&msg).expect("serialize");
        let back: ClientMessage = serde_json::from_value(value).expect("deserialize");
        match back {
            ClientMessage::ResolveSubagentEscalation {
                escalation_id,
                resolution:
                    SubagentEscalationResolution::ResolvedWithOutput {
                        is_error,
                        output,
                        duration_seconds,
                    },
                ..
            } => {
                assert_eq!(escalation_id, "esc-2");
                assert!(!is_error);
                assert_eq!(output, "ok");
                assert_eq!(duration_seconds, Some(3));
            }
            _ => panic!("expected ResolveSubagentEscalation::ResolvedWithOutput"),
        }
    }
}