node-token 0.1.0

KeyCompute node-token client for personal PC nodes
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
//! 节点协议类型定义
//!
//! 从 keycompute-types 复制的协议类型,node-token 作为独立项目不依赖 workspace。
//! 本协议版本固定为 `node.v1`,所有公开 JSON 字段使用 `snake_case`。

use serde::{Deserialize, Serialize};
use uuid::Uuid;

// ============================================================================
// 类型别名
// ============================================================================

/// 节点 ID
pub type NodeId = Uuid;

/// 节点会话 ID
pub type NodeSessionId = Uuid;

/// 节点任务 ID
pub type NodeTaskId = Uuid;

/// 节点租约 ID
pub type NodeLeaseId = Uuid;

// ============================================================================
// 节点能力
// ============================================================================

/// 节点模型能力
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeModelCapability {
    /// 模型名称
    pub model: String,
}

/// 节点能力声明
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeCapabilities {
    /// 运行时类型(MVP 固定为 "ollama")
    pub runtime: String,
    /// 支持的模型列表
    pub models: Vec<NodeModelCapability>,
}

// ============================================================================
// 注册协议
// ============================================================================

/// 节点注册请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeRegisterRequest {
    /// 协议版本(固定为 "node.v1")
    pub protocol_version: String,
    /// 客户端实例 ID
    pub client_instance_id: String,
    /// 节点显示名称
    pub display_name: String,
    /// 注册 token
    pub registration_token: String,
    /// 节点能力声明
    pub capabilities: NodeCapabilities,
}

/// 节点注册响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeRegisterResponse {
    /// 协议版本
    pub protocol_version: String,
    /// 节点 ID
    pub node_id: NodeId,
    /// 会话 ID
    pub session_id: NodeSessionId,
    /// 会话 token(只返回一次,服务端只保存 hash)
    pub session_token: String,
    /// 心跳间隔(秒)
    pub heartbeat_interval_secs: u64,
    /// 轮询超时(秒)
    pub poll_timeout_secs: u64,
}

// ============================================================================
// 心跳协议
// ============================================================================

/// 节点心跳请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeHeartbeatRequest {
    /// 协议版本
    pub protocol_version: String,
    /// 节点 ID
    pub node_id: NodeId,
    /// 会话 ID
    pub session_id: NodeSessionId,
    /// 当前可接受模型列表
    pub accepted_models: Vec<String>,
}

/// 节点心跳响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeHeartbeatResponse {
    /// 协议版本
    pub protocol_version: String,
    /// 是否接受(session 与请求体身份校验通过)
    pub accepted: bool,
    /// 节点状态(online/offline/excluded)
    pub node_status: String,
    /// 服务端失败计数
    pub server_failure_count: u32,
    /// 失败阈值
    pub failure_threshold: u32,
}

// ============================================================================
// 轮询协议
// ============================================================================

/// 节点轮询请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodePollRequest {
    /// 协议版本
    pub protocol_version: String,
    /// 节点 ID
    pub node_id: NodeId,
    /// 会话 ID
    pub session_id: NodeSessionId,
}

/// 节点轮询响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodePollResponse {
    /// 协议版本
    pub protocol_version: String,
    /// 任务信封(如果有任务)
    pub task: Option<NodeTaskEnvelope>,
    /// 重试间隔(毫秒)
    pub retry_after_ms: Option<u64>,
}

// ============================================================================
// 任务协议
// ============================================================================

/// 节点任务信封
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeTaskEnvelope {
    /// 任务 ID
    pub task_id: NodeTaskId,
    /// 租约 ID
    pub lease_id: NodeLeaseId,
    /// 模型名称(去掉 node: 前缀后的实际模型名)
    pub model: String,
    /// 任务截止时间(Unix 毫秒时间戳)
    pub deadline_unix_ms: i64,
    /// 完成宽限期(Unix 毫秒时间戳)
    pub complete_grace_until_unix_ms: i64,
    /// 任务载荷
    pub payload: NodeTaskPayload,
}

/// 节点任务载荷
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeTaskPayload {
    /// 请求 ID
    pub request_id: Uuid,
    /// Chat 完成请求
    pub chat: ChatCompletionRequest,
}

// ============================================================================
// 提交结果协议
// ============================================================================

/// 节点任务完成请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeTaskCompleteRequest {
    /// 协议版本
    pub protocol_version: String,
    /// 节点 ID
    pub node_id: NodeId,
    /// 会话 ID
    pub session_id: NodeSessionId,
    /// 任务 ID
    pub task_id: NodeTaskId,
    /// 租约 ID
    pub lease_id: NodeLeaseId,
    /// 任务结果
    pub result: NodeTaskResult,
}

/// 节点任务结果
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum NodeTaskResult {
    /// 任务成功
    Succeeded {
        /// Chat 完成响应
        response: ChatCompletionResponse,
    },
    /// 任务失败
    Failed {
        /// 错误码
        code: String,
        /// 错误消息
        message: String,
    },
}

/// 节点任务完成响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeTaskCompleteResponse {
    /// 执行动作
    pub action: NodeTaskCompleteAction,
    /// 任务状态
    pub task_status: String,
    /// 节点状态
    pub node_status: String,
    /// 服务端失败计数
    pub server_failure_count: u32,
    /// 失败阈值
    pub failure_threshold: u32,
}

/// 节点任务完成动作
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NodeTaskCompleteAction {
    /// 任务成功完成
    Succeeded,
    /// 任务恢复为 queued(重新入队)
    Requeued,
    /// 任务失败
    Failed,
    /// 任务过期
    Expired,
}

// ============================================================================
// OpenAI 兼容的请求/响应类型(用于与 Ollama 交互)
// ============================================================================

/// 消息角色枚举
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageRole {
    System,
    #[default]
    User,
    Assistant,
    Tool,
}

impl MessageRole {
    /// 获取角色字符串表示
    pub fn as_str(&self) -> &'static str {
        match self {
            MessageRole::System => "system",
            MessageRole::User => "user",
            MessageRole::Assistant => "assistant",
            MessageRole::Tool => "tool",
        }
    }
}

impl std::fmt::Display for MessageRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// 消息结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub role: MessageRole,
    pub content: String,
}

impl Message {
    #[allow(dead_code)] // 在后续阶段使用
    pub fn new(role: MessageRole, content: impl Into<String>) -> Self {
        Self {
            role,
            content: content.into(),
        }
    }

    #[allow(dead_code)] // 在后续阶段使用
    pub fn system(content: impl Into<String>) -> Self {
        Self::new(MessageRole::System, content)
    }

    #[allow(dead_code)] // 在后续阶段使用
    pub fn user(content: impl Into<String>) -> Self {
        Self::new(MessageRole::User, content)
    }

    #[allow(dead_code)] // 在后续阶段使用
    pub fn assistant(content: impl Into<String>) -> Self {
        Self::new(MessageRole::Assistant, content)
    }

    #[allow(dead_code)] // 在后续阶段使用
    pub fn tool(content: impl Into<String>) -> Self {
        Self::new(MessageRole::Tool, content)
    }
}

/// OpenAI 兼容的请求体
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionRequest {
    pub model: String,
    pub messages: Vec<Message>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,
}

impl ChatCompletionRequest {
    #[allow(dead_code)] // 在后续阶段使用
    pub fn new(model: impl Into<String>, messages: Vec<Message>) -> Self {
        Self {
            model: model.into(),
            messages,
            stream: None,
            max_tokens: None,
            temperature: None,
            top_p: None,
            n: None,
            stop: None,
        }
    }
}

/// OpenAI 兼容的非流式响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionResponse {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<CompletionChoice>,
    pub usage: Usage,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionChoice {
    pub index: u32,
    pub message: MessageContent,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageContent {
    pub role: String,
    pub content: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

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

    #[test]
    fn test_message_role_serialize() {
        let role = MessageRole::Assistant;
        let json = serde_json::to_string(&role).unwrap();
        assert_eq!(json, "\"assistant\"");
    }

    #[test]
    fn test_message_role_deserialize() {
        let json = "\"system\"";
        let role: MessageRole = serde_json::from_str(json).unwrap();
        assert_eq!(role, MessageRole::System);
    }

    #[test]
    fn test_chat_completion_request_serialize() {
        let req = ChatCompletionRequest::new("deepseek-chat", vec![Message::user("Hello")]);
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"model\":\"deepseek-chat\""));
        assert!(json.contains("\"role\":\"user\""));
    }

    // ========================================================================
    // 节点能力测试
    // ========================================================================

    #[test]
    fn test_node_model_capability_serialize() {
        let capability = NodeModelCapability {
            model: "deepseek-chat".to_string(),
        };
        let json = serde_json::to_string(&capability).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodeModelCapability = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.model, "deepseek-chat");
    }

    #[test]
    fn test_node_model_capability_deserialize() {
        let json = r#"{"model":"llama3"}"#;
        let capability: NodeModelCapability = serde_json::from_str(json).unwrap();
        assert_eq!(capability.model, "llama3");
    }

    #[test]
    fn test_node_capabilities_serialize() {
        let caps = NodeCapabilities {
            runtime: "ollama".to_string(),
            models: vec![
                NodeModelCapability {
                    model: "deepseek-chat".to_string(),
                },
                NodeModelCapability {
                    model: "llama3".to_string(),
                },
            ],
        };
        let json = serde_json::to_string(&caps).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodeCapabilities = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.runtime, "ollama");
        assert_eq!(parsed.models.len(), 2);
        assert_eq!(parsed.models[0].model, "deepseek-chat");
        assert_eq!(parsed.models[1].model, "llama3");
    }

    #[test]
    fn test_node_capabilities_deserialize() {
        let json = r#"{
            "runtime": "ollama",
            "models": [
                {"model": "deepseek-chat"},
                {"model": "llama3"}
            ]
        }"#;
        let caps: NodeCapabilities = serde_json::from_str(json).unwrap();
        assert_eq!(caps.runtime, "ollama");
        assert_eq!(caps.models.len(), 2);
        assert_eq!(caps.models[0].model, "deepseek-chat");
        assert_eq!(caps.models[1].model, "llama3");
    }

    // ========================================================================
    // 注册协议测试
    // ========================================================================

    #[test]
    fn test_node_register_request_serialize() {
        let req = NodeRegisterRequest {
            protocol_version: "node.v1".to_string(),
            client_instance_id: "test-instance-001".to_string(),
            display_name: "Test Node".to_string(),
            registration_token: "secret-token".to_string(),
            capabilities: NodeCapabilities {
                runtime: "ollama".to_string(),
                models: vec![NodeModelCapability {
                    model: "deepseek-chat".to_string(),
                }],
            },
        };
        let json = serde_json::to_string(&req).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodeRegisterRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.protocol_version, "node.v1");
        assert_eq!(parsed.client_instance_id, "test-instance-001");
        assert_eq!(parsed.display_name, "Test Node");
        assert_eq!(parsed.capabilities.runtime, "ollama");
        assert_eq!(parsed.capabilities.models.len(), 1);
    }

    #[test]
    fn test_node_register_response_deserialize() {
        let node_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let json = serde_json::json!({
            "protocol_version": "node.v1",
            "node_id": node_id.to_string(),
            "session_id": session_id.to_string(),
            "session_token": "test-session-token",
            "heartbeat_interval_secs": 30,
            "poll_timeout_secs": 60
        });
        let resp: NodeRegisterResponse = serde_json::from_value(json).unwrap();
        assert_eq!(resp.protocol_version, "node.v1");
        assert_eq!(resp.node_id, node_id);
        assert_eq!(resp.session_id, session_id);
        assert_eq!(resp.session_token, "test-session-token");
        assert_eq!(resp.heartbeat_interval_secs, 30);
        assert_eq!(resp.poll_timeout_secs, 60);
    }

    // ========================================================================
    // 心跳协议测试
    // ========================================================================

    #[test]
    fn test_node_heartbeat_request_serialize() {
        let node_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let req = NodeHeartbeatRequest {
            protocol_version: "node.v1".to_string(),
            node_id,
            session_id,
            accepted_models: vec!["deepseek-chat".to_string(), "llama3".to_string()],
        };
        let json = serde_json::to_string(&req).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodeHeartbeatRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.protocol_version, "node.v1");
        assert_eq!(parsed.node_id, node_id);
        assert_eq!(parsed.session_id, session_id);
        assert_eq!(parsed.accepted_models.len(), 2);
        assert!(parsed
            .accepted_models
            .contains(&"deepseek-chat".to_string()));
        assert!(parsed.accepted_models.contains(&"llama3".to_string()));
    }

    #[test]
    fn test_node_heartbeat_response_deserialize() {
        let json = serde_json::json!({
            "protocol_version": "node.v1",
            "accepted": true,
            "node_status": "online",
            "server_failure_count": 0,
            "failure_threshold": 3
        });
        let resp: NodeHeartbeatResponse = serde_json::from_value(json).unwrap();
        assert_eq!(resp.protocol_version, "node.v1");
        assert!(resp.accepted);
        assert_eq!(resp.node_status, "online");
        assert_eq!(resp.server_failure_count, 0);
        assert_eq!(resp.failure_threshold, 3);
    }

    #[test]
    fn test_node_heartbeat_response_excluded() {
        let json = serde_json::json!({
            "protocol_version": "node.v1",
            "accepted": true,
            "node_status": "excluded",
            "server_failure_count": 3,
            "failure_threshold": 3
        });
        let resp: NodeHeartbeatResponse = serde_json::from_value(json).unwrap();
        assert!(resp.accepted);
        assert_eq!(resp.node_status, "excluded");
        assert_eq!(resp.server_failure_count, 3);
    }

    // ========================================================================
    // 轮询协议测试
    // ========================================================================

    #[test]
    fn test_node_poll_request_serialize() {
        let node_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let req = NodePollRequest {
            protocol_version: "node.v1".to_string(),
            node_id,
            session_id,
        };
        let json = serde_json::to_string(&req).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodePollRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.protocol_version, "node.v1");
        assert_eq!(parsed.node_id, node_id);
        assert_eq!(parsed.session_id, session_id);
    }

    #[test]
    fn test_node_poll_response_with_task() {
        let task_id = Uuid::new_v4();
        let lease_id = Uuid::new_v4();
        let json = serde_json::json!({
            "protocol_version": "node.v1",
            "task": {
                "task_id": task_id.to_string(),
                "lease_id": lease_id.to_string(),
                "model": "deepseek-chat",
                "deadline_unix_ms": 1234567890123i64,
                "complete_grace_until_unix_ms": 1234567950123i64,
                "payload": {
                    "request_id": Uuid::new_v4().to_string(),
                    "chat": {
                        "model": "deepseek-chat",
                        "messages": [{"role": "user", "content": "Hello"}]
                    }
                }
            },
            "retry_after_ms": null
        });
        let resp: NodePollResponse = serde_json::from_value(json).unwrap();
        assert_eq!(resp.protocol_version, "node.v1");
        assert!(resp.task.is_some());
        let task = resp.task.unwrap();
        assert_eq!(task.task_id, task_id);
        assert_eq!(task.lease_id, lease_id);
        assert_eq!(task.model, "deepseek-chat");
    }

    #[test]
    fn test_node_poll_response_no_task() {
        let json = serde_json::json!({
            "protocol_version": "node.v1",
            "task": null,
            "retry_after_ms": 1000
        });
        let resp: NodePollResponse = serde_json::from_value(json).unwrap();
        assert!(resp.task.is_none());
        assert_eq!(resp.retry_after_ms, Some(1000));
    }

    // ========================================================================
    // 提交结果协议测试
    // ========================================================================

    #[test]
    fn test_node_task_complete_request_succeeded() {
        let node_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let task_id = Uuid::new_v4();
        let lease_id = Uuid::new_v4();
        let req = NodeTaskCompleteRequest {
            protocol_version: "node.v1".to_string(),
            node_id,
            session_id,
            task_id,
            lease_id,
            result: NodeTaskResult::Succeeded {
                response: ChatCompletionResponse {
                    id: "resp-001".to_string(),
                    object: "chat.completion".to_string(),
                    created: 1234567890,
                    model: "deepseek-chat".to_string(),
                    choices: vec![CompletionChoice {
                        index: 0,
                        message: MessageContent {
                            role: "assistant".to_string(),
                            content: "Hello! How can I help you?".to_string(),
                        },
                        finish_reason: Some("stop".to_string()),
                    }],
                    usage: Usage {
                        prompt_tokens: 10,
                        completion_tokens: 20,
                        total_tokens: 30,
                    },
                },
            },
        };
        let json = serde_json::to_string(&req).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodeTaskCompleteRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.protocol_version, "node.v1");
        assert_eq!(parsed.node_id, node_id);
        assert_eq!(parsed.task_id, task_id);
        assert_eq!(parsed.lease_id, lease_id);
        match parsed.result {
            NodeTaskResult::Succeeded { response } => {
                assert_eq!(response.id, "resp-001");
                assert_eq!(
                    response.choices[0].message.content,
                    "Hello! How can I help you?"
                );
            }
            NodeTaskResult::Failed { .. } => panic!("Expected Succeeded variant"),
        }
    }

    #[test]
    fn test_node_task_complete_request_failed() {
        let node_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let task_id = Uuid::new_v4();
        let lease_id = Uuid::new_v4();
        let req = NodeTaskCompleteRequest {
            protocol_version: "node.v1".to_string(),
            node_id,
            session_id,
            task_id,
            lease_id,
            result: NodeTaskResult::Failed {
                code: "ollama_error".to_string(),
                message: "Model not found".to_string(),
            },
        };
        let json = serde_json::to_string(&req).unwrap();

        // 反序列化验证(强断言)
        let parsed: NodeTaskCompleteRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.protocol_version, "node.v1");
        assert_eq!(parsed.task_id, task_id);
        match parsed.result {
            NodeTaskResult::Failed { code, message } => {
                assert_eq!(code, "ollama_error");
                assert_eq!(message, "Model not found");
            }
            NodeTaskResult::Succeeded { .. } => panic!("Expected Failed variant"),
        }
    }

    #[test]
    fn test_node_task_complete_response_deserialize() {
        let json = serde_json::json!({
            "action": "succeeded",
            "task_status": "succeeded",
            "node_status": "online",
            "server_failure_count": 0,
            "failure_threshold": 3
        });
        let resp: NodeTaskCompleteResponse = serde_json::from_value(json).unwrap();
        assert_eq!(resp.action, NodeTaskCompleteAction::Succeeded);
        assert_eq!(resp.task_status, "succeeded");
        assert_eq!(resp.node_status, "online");
    }

    #[test]
    fn test_node_task_complete_action_enum() {
        // 测试所有 action 变体的序列化
        let actions = vec![
            (NodeTaskCompleteAction::Succeeded, "succeeded"),
            (NodeTaskCompleteAction::Requeued, "requeued"),
            (NodeTaskCompleteAction::Failed, "failed"),
            (NodeTaskCompleteAction::Expired, "expired"),
        ];

        for (action, expected_str) in actions {
            let json = serde_json::to_string(&action).unwrap();
            assert_eq!(json, format!("\"{}\"", expected_str));

            // 反序列化验证
            let deserialized: NodeTaskCompleteAction = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized, action);
        }
    }

    // ========================================================================
    // ChatCompletionResponse 测试
    // ========================================================================

    #[test]
    fn test_chat_completion_response_serialize() {
        let resp = ChatCompletionResponse {
            id: "resp-001".to_string(),
            object: "chat.completion".to_string(),
            created: 1234567890,
            model: "deepseek-chat".to_string(),
            choices: vec![CompletionChoice {
                index: 0,
                message: MessageContent {
                    role: "assistant".to_string(),
                    content: "Test response".to_string(),
                },
                finish_reason: Some("stop".to_string()),
            }],
            usage: Usage {
                prompt_tokens: 5,
                completion_tokens: 10,
                total_tokens: 15,
            },
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"id\":\"resp-001\""));
        assert!(json.contains("\"object\":\"chat.completion\""));
        assert!(json.contains("\"model\":\"deepseek-chat\""));
        assert!(json.contains("\"role\":\"assistant\""));
        assert!(json.contains("Test response"));
    }

    #[test]
    fn test_chat_completion_response_deserialize() {
        let json = r#"{
            "id": "resp-002",
            "object": "chat.completion",
            "created": 1234567891,
            "model": "llama3",
            "choices": [{
                "index": 0,
                "message": {"role": "assistant", "content": "Response"},
                "finish_reason": "stop"
            }],
            "usage": {"prompt_tokens": 8, "completion_tokens": 12, "total_tokens": 20}
        }"#;
        let resp: ChatCompletionResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.id, "resp-002");
        assert_eq!(resp.model, "llama3");
        assert_eq!(resp.choices.len(), 1);
        assert_eq!(resp.choices[0].message.content, "Response");
        assert_eq!(resp.usage.total_tokens, 20);
    }

    // ========================================================================
    // Message 测试
    // ========================================================================

    #[test]
    fn test_message_serialize() {
        let msg = Message::user("Hello, world!");
        let json = serde_json::to_string(&msg).unwrap();

        // 反序列化验证(强断言)
        let parsed: Message = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.role, MessageRole::User);
        assert_eq!(parsed.content, "Hello, world!");
    }

    #[test]
    fn test_message_deserialize() {
        let json = r#"{"role":"system","content":"You are a helpful assistant"}"#;
        let msg: Message = serde_json::from_str(json).unwrap();
        assert_eq!(msg.role, MessageRole::System);
        assert_eq!(msg.content, "You are a helpful assistant");
    }

    #[test]
    fn test_message_helper_methods() {
        let system_msg = Message::system("System prompt");
        assert_eq!(system_msg.role, MessageRole::System);
        assert_eq!(system_msg.content, "System prompt");

        let user_msg = Message::user("User question");
        assert_eq!(user_msg.role, MessageRole::User);
        assert_eq!(user_msg.content, "User question");

        let assistant_msg = Message::assistant("Assistant response");
        assert_eq!(assistant_msg.role, MessageRole::Assistant);
        assert_eq!(assistant_msg.content, "Assistant response");

        let tool_msg = Message::tool("Tool output");
        assert_eq!(tool_msg.role, MessageRole::Tool);
        assert_eq!(tool_msg.content, "Tool output");
    }

    // ========================================================================
    // 边界条件测试
    // ========================================================================

    #[test]
    fn test_message_with_unicode() {
        let msg = Message::user("🚀 My Node 节点 Привет");
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: Message = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.content, "🚀 My Node 节点 Привет");
    }

    #[test]
    fn test_message_with_special_characters() {
        let content = r#"Line1\nLine2\"Quote\\Backslash"#;
        let msg = Message::user(content);
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: Message = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.content, content);
    }

    #[test]
    fn test_empty_accepted_models() {
        let node_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let req = NodeHeartbeatRequest {
            protocol_version: "node.v1".to_string(),
            node_id,
            session_id,
            accepted_models: vec![], // 空列表
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: NodeHeartbeatRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.accepted_models.len(), 0);
    }

    #[test]
    fn test_chat_completion_request_with_optional_fields() {
        let req = ChatCompletionRequest {
            model: "deepseek-chat".to_string(),
            messages: vec![Message::user("Test")],
            stream: Some(false),
            max_tokens: Some(100),
            temperature: Some(0.7),
            top_p: Some(0.9),
            n: Some(1),
            stop: Some(vec!["\n".to_string()]),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: ChatCompletionRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.max_tokens, Some(100));
        assert_eq!(parsed.temperature, Some(0.7));
        assert_eq!(parsed.top_p, Some(0.9));
        assert_eq!(parsed.stop, Some(vec!["\n".to_string()]));
    }

    #[test]
    fn test_node_task_complete_action_all_variants() {
        // 测试所有 action 变体的 roundtrip
        let actions = vec![
            NodeTaskCompleteAction::Succeeded,
            NodeTaskCompleteAction::Requeued,
            NodeTaskCompleteAction::Failed,
            NodeTaskCompleteAction::Expired,
        ];

        for action in actions {
            let json = serde_json::to_string(&action).unwrap();
            let parsed: NodeTaskCompleteAction = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, action);
        }
    }
}