ilink-hub 0.3.0

iLink-compatible multiplexer hub for WeChat ClawBot — route one WeChat account to multiple AI agent backends
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
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, Ordering};

pub const ILINK_BASE_URL: &str = "https://ilinkai.weixin.qq.com";
pub const ILINK_CDN_BASE_URL: &str = "https://novac2c.cdn.weixin.qq.com/c2c";

// ─── Common ──────────────────────────────────────────────────────────────────

/// Attached to every outgoing CGI request per iLink protocol.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BaseInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bot_agent: Option<String>,
}

impl Default for BaseInfo {
    fn default() -> Self {
        Self {
            channel_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            bot_agent: Some(format!("ilink-hub/{}", env!("CARGO_PKG_VERSION"))),
        }
    }
}

// ─── Login / QR Code ────────────────────────────────────────────────────────

/// Response from `/ilink/bot/get_bot_qrcode`.
/// Actual API shape: {"ret":0,"qrcode":"<key>","qrcode_img_content":"https://..."}
#[derive(Debug, Serialize, Deserialize)]
pub struct GetQrcodeResponse {
    pub ret: i32,
    /// The QR code key / identifier used for polling.
    pub qrcode: Option<String>,
    /// The URL to render as a QR code (user scans this URL).
    pub qrcode_img_content: Option<String>,
    pub errmsg: Option<String>,
}

/// Response from `/ilink/bot/get_qrcode_status`.
/// Observed status values: "wait" | "scaned" | "confirmed" | "expired"
/// On "confirmed": also includes bot_token, baseurl, ilink_bot_id, ilink_user_id.
#[derive(Debug, Serialize, Deserialize)]
pub struct QrcodeStatusResponse {
    pub ret: i32,
    /// "wait" | "confirmed" | "expired" (string, not integer)
    pub status: Option<String>,
    pub bot_token: Option<String>,
    pub baseurl: Option<String>,
    pub ilink_bot_id: Option<String>,
    pub ilink_user_id: Option<String>,
    pub errmsg: Option<String>,
}

// ─── Message item types ──────────────────────────────────────────────────────

pub mod msg_type {
    pub const TEXT: i32 = 1;
    pub const IMAGE: i32 = 2;
    pub const VOICE: i32 = 3;
    pub const FILE: i32 = 4;
    pub const VIDEO: i32 = 5;
}

pub mod message_state {
    pub const FINISH: i32 = 2;
}

/// Text content inside a MessageItem.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TextItem {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// Voice content inside a MessageItem (type=3).
/// `text` is the ASR transcript provided by WeChat, may be absent if recognition failed.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VoiceItem {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// Image content inside a MessageItem (type=2).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ImageItem {
    /// CDN URL for the image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cdn_url: Option<String>,
    /// MD5 hash of the image bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub md5: Option<String>,
    /// media_id returned by getuploadurl (used when sending).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_id: Option<String>,
}

/// File content inside a MessageItem (type=4).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FileItem {
    /// Original file name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// CDN URL for the file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cdn_url: Option<String>,
    /// File size in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_size: Option<u64>,
    /// MD5 hash of the file bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub md5: Option<String>,
    /// media_id returned by getuploadurl (used when sending).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_id: Option<String>,
}

/// Video content inside a MessageItem (type=5).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VideoItem {
    /// CDN URL for the video.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cdn_url: Option<String>,
    /// Duration in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u32>,
    /// MD5 hash of the video bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub md5: Option<String>,
    /// media_id returned by getuploadurl (used when sending).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_id: Option<String>,
}

/// One item inside a WeixinMessage's item_list.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MessageItem {
    /// Item type: 1=text, 2=image, 3=voice, 4=file, 5=video
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub item_type: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_item: Option<TextItem>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub voice_item: Option<VoiceItem>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_item: Option<ImageItem>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_item: Option<FileItem>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub video_item: Option<VideoItem>,
    /// Catch-all for unknown fields from iLink upstream.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

// ─── Unified message type ────────────────────────────────────────────────────

/// The canonical message type used in both upstream (iLink wire protocol) and
/// the hub's downstream API (what agent backends receive and send).
///
/// Field names mirror the official iLink / openclaw-weixin SDK.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WeixinMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seq: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_id: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_time_ms: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update_time_ms: Option<i64>,
    /// Present for group messages (group/session identifier).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_id: Option<String>,
    /// 1 = user message, 2 = bot message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_type: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_state: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_list: Option<std::sync::Arc<Vec<MessageItem>>>,
    /// Required for routing replies back to the correct conversation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_token: Option<String>,
    /// ilink-hub 扩展元数据(Hub 与已注册后端之间专用,不会透传给官方 iLink 上游)。
    ///
    /// Hub 在转发消息给下游前注入此字段;下游回复时可在此字段中携带 `cli_session_id`
    /// 以告知 Hub 当前活跃的后端 session UUID(如 Claude Code `--resume` 的 UUID)。
    ///
    /// 使用官方 iLink SDK 的后端不感知此字段(忽略未知 JSON key);
    /// 不支持 session 管理的后端同样可以正常收发消息,只是无法利用 session 连续性。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ilink_hub_ext: Option<HubExt>,
}

/// ilink-hub 专有扩展字段,封装于 `WeixinMessage.ilink_hub_ext`。
///
/// * **Hub → 下游**:`session_id`(当前活跃 session 的后端 UUID)、`session_name`(可读标识)
/// * **下游 → Hub**:`cli_session_id`(下游上报的后端 UUID,Hub 将其持久化到对应 session)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HubExt {
    /// Hub 注入:当前活跃 session 已持久化的后端 UUID(如 Claude `--resume` 值)。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Hub 注入:当前活跃 session 的可读名称(如 `"feature-a"`,默认 `"default"`)。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_name: Option<String>,
    /// 下游 → Hub:下游在 `sendmessage` 时填入,Hub 将其写入当前活跃 session 的存储。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cli_session_id: Option<String>,
    /// A2A call identifier.  Set by Hub on the inbound message to the target Agent;
    /// the target echoes it back in its `sendmessage` so Hub can resolve the waiter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub a2a_call_id: Option<String>,
    /// A2A call chain depth (0 = direct user message, N = N levels deep in A2A calls).
    /// Set by Hub on synthetic A2A inbound messages; Bridge echoes it back in sendmessage.
    /// Hub rejects `call_agent` when depth >= MAX_A2A_DEPTH.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub a2a_depth: Option<u8>,
    /// Bridge → Hub: optional AgentProc 0.4 `usage` object from the terminal
    /// `result` / `error` event (token/cost stats). Hub MAY persist for display.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<serde_json::Value>,
}

impl WeixinMessage {
    /// Extract displayable text: prefers text_item, falls back to voice_item ASR transcript.
    pub fn text(&self) -> Option<&str> {
        let items = self.item_list.as_ref()?;
        items
            .iter()
            .find_map(|item| item.text_item.as_ref()?.text.as_deref())
            .or_else(|| {
                items
                    .iter()
                    .find_map(|item| item.voice_item.as_ref()?.text.as_deref())
            })
    }

    /// Return the `item_type` of the first item in the list, if any.
    pub fn first_item_type(&self) -> Option<i32> {
        self.item_list.as_ref()?.first()?.item_type
    }

    /// Return true if the message contains at least one non-empty item (any type).
    pub fn has_content(&self) -> bool {
        self.item_list
            .as_ref()
            .map(|l| !l.is_empty())
            .unwrap_or(false)
    }

    /// Return true if the message contains at least one non-text media item (image / voice / file / video).
    ///
    /// Unlike [`has_content`], this returns `false` for a text-only item_list even when the text
    /// is empty. Used by the sendmessage handler to distinguish session-persist-only messages
    /// (empty TextItem) from real media replies that have no text but do carry content.
    pub fn has_media_content(&self) -> bool {
        self.item_list
            .as_ref()
            .map(|l| {
                l.iter()
                    .any(|item| !matches!(item.item_type, Some(msg_type::TEXT) | None))
            })
            .unwrap_or(false)
    }

    /// Build a text reply to this message.
    pub fn build_text_reply(context_token: String, text: String) -> WeixinMessage {
        let mut msg = WeixinMessage {
            context_token: Some(context_token),
            message_type: Some(2), // BOT
            message_state: Some(message_state::FINISH),
            from_user_id: Some(String::new()),
            client_id: Some(new_client_id()),
            item_list: Some(std::sync::Arc::new(vec![MessageItem {
                item_type: Some(msg_type::TEXT),
                text_item: Some(TextItem { text: Some(text) }),
                ..Default::default()
            }])),
            ..Default::default()
        };
        msg.ensure_outbound();
        msg
    }

    /// Build an image reply using a media_id obtained from `getuploadurl`.
    pub fn build_image_reply(context_token: String, media_id: String) -> WeixinMessage {
        let mut msg = WeixinMessage {
            context_token: Some(context_token),
            message_type: Some(2),
            message_state: Some(message_state::FINISH),
            from_user_id: Some(String::new()),
            client_id: Some(new_client_id()),
            item_list: Some(std::sync::Arc::new(vec![MessageItem {
                item_type: Some(msg_type::IMAGE),
                image_item: Some(ImageItem {
                    media_id: Some(media_id),
                    ..Default::default()
                }),
                ..Default::default()
            }])),
            ..Default::default()
        };
        msg.ensure_outbound();
        msg
    }

    /// Build a file reply using a media_id obtained from `getuploadurl`.
    pub fn build_file_reply(
        context_token: String,
        media_id: String,
        file_name: Option<String>,
    ) -> WeixinMessage {
        let mut msg = WeixinMessage {
            context_token: Some(context_token),
            message_type: Some(2),
            message_state: Some(message_state::FINISH),
            from_user_id: Some(String::new()),
            client_id: Some(new_client_id()),
            item_list: Some(std::sync::Arc::new(vec![MessageItem {
                item_type: Some(msg_type::FILE),
                file_item: Some(FileItem {
                    media_id: Some(media_id),
                    file_name,
                    ..Default::default()
                }),
                ..Default::default()
            }])),
            ..Default::default()
        };
        msg.ensure_outbound();
        msg
    }

    /// Normalize outbound fields per iLink protocol (empty from_user_id, unique client_id, FINISH state).
    pub fn ensure_outbound(&mut self) {
        self.from_user_id = Some(String::new());
        if self.message_type.is_none() {
            self.message_type = Some(2);
        }
        if self.message_state.is_none() {
            self.message_state = Some(message_state::FINISH);
        }
        if self
            .client_id
            .as_ref()
            .map(|s| s.is_empty())
            .unwrap_or(true)
        {
            self.client_id = Some(new_client_id());
        }
        // Assign a Hub-generated `message_id` that iLink preserves verbatim and
        // echoes back as `ref_msg.message_item.msg_id` on quote-reply (verified
        // against the live iLink service). Persisted in `messages.ilink_msg_id`
        // at send time so inbound quote-replies can route to the exact backend/
        // session (L0 exact match) instead of the ±10s timestamp fallback.
        if self.message_id.is_none() {
            self.message_id = Some(new_outbound_msg_id());
        }
    }
}

/// Restart-safe, Hub-generated outbound `message_id` (i64).
///
/// Structure: `unix_millis * 1_000_000 + counter % 1_000_000`.
/// * `unix_millis` (~1.78e12) advances across restarts, so two processes (or a
///   restarted hub) never collide on the same id;
/// * the 20-bit counter slot disambiguates multiple sends within the same ms;
/// * magnitude ~1.78e18 stays well under `i64::MAX` (9.22e18) and in the range
///   confirmed to be preserved by iLink.
fn new_outbound_msg_id() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed) % 1_000_000;
    (millis * 1_000_000 + n) as i64
}

fn new_client_id() -> String {
    format!("ilink-hub:{}", uuid::Uuid::new_v4())
}

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

    #[test]
    fn build_text_reply_sets_outbound_fields() {
        let msg = WeixinMessage::build_text_reply("ctx".to_string(), "hi".to_string());
        assert_eq!(msg.from_user_id.as_deref(), Some(""));
        assert_eq!(msg.message_type, Some(2));
        assert_eq!(msg.message_state, Some(message_state::FINISH));
        assert!(msg.client_id.as_deref().unwrap().starts_with("ilink-hub:"));
    }

    #[test]
    fn ensure_outbound_assigns_unique_client_id() {
        let mut msg1 = WeixinMessage::default();
        let mut msg2 = WeixinMessage::default();
        msg1.ensure_outbound();
        msg2.ensure_outbound();
        assert_ne!(msg1.client_id, msg2.client_id);
    }

    // ── has_media_content ────────────────────────────────────────────────────

    /// 空文本消息(session-persist-only)不含 media 内容。
    /// 这是发现 duplicate-reply bug 的核心断言:`build_text_reply("")` 会建出一个含空
    /// TextItem 的 item_list,has_content() 对此返回 true,但 has_media_content() 必须
    /// 返回 false,否则 sendmessage 的早返回保护失效,footer 被追加到空消息后发出。
    #[test]
    fn has_media_content_false_for_empty_text_reply() {
        let msg = WeixinMessage::build_text_reply("ctx".to_string(), String::new());
        assert!(
            !msg.has_media_content(),
            "空 TextItem 不应视为 media content"
        );
    }

    #[test]
    fn has_media_content_false_for_nonempty_text_reply() {
        let msg = WeixinMessage::build_text_reply("ctx".to_string(), "hello".to_string());
        assert!(!msg.has_media_content(), "纯文本回复不含 media content");
    }

    #[test]
    fn has_media_content_true_for_image_reply() {
        let msg = WeixinMessage::build_image_reply("ctx".to_string(), "media-id-abc".to_string());
        assert!(msg.has_media_content(), "图片回复应视为有 media content");
    }

    #[test]
    fn has_media_content_true_for_file_reply() {
        let msg = WeixinMessage::build_file_reply(
            "ctx".to_string(),
            "media-id-xyz".to_string(),
            Some("report.pdf".to_string()),
        );
        assert!(msg.has_media_content(), "文件回复应视为有 media content");
    }

    #[test]
    fn has_media_content_false_for_empty_item_list() {
        let msg = WeixinMessage::default();
        assert!(
            !msg.has_media_content(),
            "无 item_list 时不含 media content"
        );
    }

    /// 保证旧的 has_content() 对空 TextItem 仍返回 true(语义未变)。
    /// sendmessage handler 已改用 has_media_content();此测试记录 has_content() 的现有行为
    /// 避免未来误改其语义影响其他调用方。
    #[test]
    fn has_content_true_for_empty_text_item() {
        let msg = WeixinMessage::build_text_reply("ctx".to_string(), String::new());
        assert!(
            msg.has_content(),
            "has_content() 对含空 TextItem 的 item_list 应返回 true(记录现有行为)"
        );
    }

    // ── WeixinMessage::text() ────────────────────────────────────────────────

    #[test]
    fn text_returns_text_item_content() {
        let msg = WeixinMessage::build_text_reply("ctx".to_string(), "hello".to_string());
        assert_eq!(msg.text(), Some("hello"));
    }

    #[test]
    fn text_falls_back_to_voice_item_asr_transcript() {
        let msg = WeixinMessage {
            item_list: Some(std::sync::Arc::new(vec![MessageItem {
                item_type: Some(msg_type::VOICE),
                voice_item: Some(VoiceItem {
                    text: Some("voice asr text".to_string()),
                }),
                ..Default::default()
            }])),
            ..Default::default()
        };
        assert_eq!(
            msg.text(),
            Some("voice asr text"),
            "text() must fall back to voice_item ASR transcript"
        );
    }

    #[test]
    fn text_returns_none_when_no_item_list() {
        let msg = WeixinMessage::default();
        assert!(msg.text().is_none());
    }

    #[test]
    fn text_returns_none_when_text_item_has_no_text_field_and_no_voice_fallback() {
        let msg = WeixinMessage {
            item_list: Some(std::sync::Arc::new(vec![MessageItem {
                item_type: Some(msg_type::IMAGE),
                image_item: Some(crate::ilink::types::ImageItem {
                    cdn_url: Some("https://cdn.example.com/img.jpg".to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }])),
            ..Default::default()
        };
        assert!(
            msg.text().is_none(),
            "image-only message must return None from text()"
        );
    }

    // ── WeixinMessage::first_item_type() ─────────────────────────────────────

    #[test]
    fn first_item_type_returns_type_of_first_item() {
        let msg = WeixinMessage::build_text_reply("ctx".to_string(), "hi".to_string());
        assert_eq!(msg.first_item_type(), Some(msg_type::TEXT));
    }

    #[test]
    fn first_item_type_returns_none_when_no_item_list() {
        let msg = WeixinMessage::default();
        assert!(msg.first_item_type().is_none());
    }

    // ── SendMessageRequest::reply_text() ─────────────────────────────────────

    #[test]
    fn reply_text_sets_to_user_id_when_non_empty() {
        let req =
            SendMessageRequest::reply_text("ctx".to_string(), "hi".to_string(), "user-123", None);
        let to_user = req.msg.as_ref().unwrap().to_user_id.as_deref();
        assert_eq!(
            to_user,
            Some("user-123"),
            "non-empty to_user_id must be set on msg"
        );
    }

    #[test]
    fn reply_text_does_not_set_to_user_id_when_empty() {
        let req = SendMessageRequest::reply_text("ctx".to_string(), "hi".to_string(), "", None);
        let to_user = req.msg.as_ref().unwrap().to_user_id.as_deref();
        assert!(to_user.is_none(), "empty to_user_id must NOT be set on msg");
    }

    #[test]
    fn reply_text_sets_ilink_hub_ext_when_cli_session_id_provided() {
        let req = SendMessageRequest::reply_text(
            "ctx".to_string(),
            "hi".to_string(),
            "",
            Some("session-uuid-abc".to_string()),
        );
        let ext = req.msg.as_ref().unwrap().ilink_hub_ext.as_ref();
        assert!(ext.is_some(), "cli_session_id must set ilink_hub_ext");
        assert_eq!(
            ext.unwrap().cli_session_id.as_deref(),
            Some("session-uuid-abc")
        );
    }

    // ── SendMessageResponse::ok() / err() ────────────────────────────────────

    #[test]
    fn send_message_response_ok_has_ret_zero_and_no_errmsg() {
        let r = SendMessageResponse::ok();
        assert_eq!(r.ret, Some(0));
        assert!(r.errmsg.is_none());
    }

    #[test]
    fn send_message_response_err_has_non_zero_ret_and_errmsg() {
        let r = SendMessageResponse::err(-1, "bad request");
        assert_eq!(r.ret, Some(-1));
        assert_eq!(r.errmsg.as_deref(), Some("bad request"));
    }
}

// ─── GetUpdates (getupdates endpoint) ────────────────────────────────────────

/// Request body for `POST /ilink/bot/getupdates`.
#[derive(Debug, Serialize, Deserialize)]
pub struct GetUpdatesRequest {
    /// Long-poll cursor; send empty string on first call.
    #[serde(default)]
    pub get_updates_buf: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_info: Option<BaseInfo>,
    /// Long-poll seconds (0 = return immediately if no messages). Defaults to 30 on Hub.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u32>,
}

/// Response body for `POST /ilink/bot/getupdates`.
#[derive(Debug, Serialize, Deserialize)]
pub struct GetUpdatesResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ret: Option<i32>,
    /// Server error code (e.g. -14 = session timeout). Present when request fails.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errcode: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errmsg: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub msgs: Option<Vec<WeixinMessage>>,
    /// Updated cursor to pass on next request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub get_updates_buf: Option<String>,
}

// ─── SendMessage ─────────────────────────────────────────────────────────────

/// Request body for `POST /ilink/bot/sendmessage`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SendMessageRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub msg: Option<WeixinMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_info: Option<BaseInfo>,
}

impl SendMessageRequest {
    pub fn text(context_token: String, text: String) -> Self {
        Self {
            msg: Some(WeixinMessage::build_text_reply(context_token, text)),
            base_info: Some(BaseInfo::default()),
        }
    }

    /// Build a text reply to a WeChat user. `from_user_id` must be empty per iLink protocol.
    pub fn reply(context_token: String, text: String, to_user_id: &str) -> Self {
        Self::reply_text(context_token, text, to_user_id, None)
    }

    /// Same as [`reply`](Self::reply) but allows bridge to attach `cli_session_id` (via `ilink_hub_ext`) for Hub to persist.
    pub fn reply_text(
        context_token: String,
        text: String,
        to_user_id: &str,
        cli_session_id: Option<String>,
    ) -> Self {
        let mut msg = WeixinMessage::build_text_reply(context_token, text);
        if !to_user_id.is_empty() {
            msg.to_user_id = Some(to_user_id.to_string());
        }
        if cli_session_id.is_some() {
            msg.ilink_hub_ext = Some(HubExt {
                cli_session_id,
                ..Default::default()
            });
        }
        Self {
            msg: Some(msg),
            base_info: Some(BaseInfo::default()),
        }
    }
}

/// Response body for `POST /ilink/bot/sendmessage`.
/// The real iLink API returns an empty body on success; ret/errmsg added by hub.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct SendMessageResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ret: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errmsg: Option<String>,
}

impl SendMessageResponse {
    pub fn ok() -> Self {
        Self {
            ret: Some(0),
            errmsg: None,
        }
    }
    pub fn err(code: i32, msg: impl Into<String>) -> Self {
        Self {
            ret: Some(code),
            errmsg: Some(msg.into()),
        }
    }
}

// ─── GetConfig ───────────────────────────────────────────────────────────────

/// Request body for `POST /ilink/bot/getconfig`.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct GetConfigRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ilink_user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_info: Option<BaseInfo>,
}

/// Response body for `POST /ilink/bot/getconfig`.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct GetConfigResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ret: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errmsg: Option<String>,
    /// Base64-encoded typing ticket for sendTyping.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub typing_ticket: Option<String>,
}

// ─── SendTyping ──────────────────────────────────────────────────────────────

/// Request body for `POST /ilink/bot/sendtyping`.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct SendTypingRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ilink_user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub typing_ticket: Option<String>,
    /// 1 = typing (default), 2 = cancel typing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_info: Option<BaseInfo>,
}

// ─── Media Upload ─────────────────────────────────────────────────────────────

#[derive(Debug, Serialize, Deserialize)]
pub struct GetUploadUrlRequest {
    pub file_type: String,
    pub file_size: u64,
    pub file_md5: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GetUploadUrlResponse {
    pub ret: i32,
    pub upload_url: Option<String>,
    pub media_id: Option<String>,
    pub errmsg: Option<String>,
}