agent-context 0.1.1

Multi-backend agent context manager with three-zone memory model
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
//! 集成测试:覆盖工具调用、reasoning_content 保留/剥离、on_change 通知场景

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use agent_context::{
    AgentContext, AppendMsg, ChangeEvent, ContextBackend, ContextBackendResponse,
    ContextMessage, MessagesMsg, ResponseType, SendMsg, SendStreamMsg,
};
use agent_context::{AgentError, Role};
use kameo::prelude::*;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// 辅助函数
// ---------------------------------------------------------------------------

fn rich_mock_opts(token: u64) -> RichMockOpts {
    RichMockOpts {
        common: agent_context::CommonOpts {
            model: "test".into(),
            context_window: 10000,
            max_tokens: 4096,
            auto_compress: false,
            scratch: None,
        },
        token,
    }
}

// ---------------------------------------------------------------------------
// EventCollector — 无锁事件收集器(替代 Mutex<Vec<String>>)
// ---------------------------------------------------------------------------

/// 使用 AtomicUsize 索引 + 预分配数组实现无锁事件收集。
/// `on_change` 闭包在 kameo actor 线程中被顺序调用(单 actor 单线程处理),
/// 因此 `fetch_add` 获取的槽位不会竞争写入。
struct EventCollector {
    slots: Box<[std::cell::UnsafeCell<Option<String>>]>,
    len: AtomicUsize,
}

// 单 actor 内顺序调用 on_change,写入不跨线程并发
unsafe impl Send for EventCollector {}
unsafe impl Sync for EventCollector {}

impl EventCollector {
    fn new(capacity: usize) -> Self {
        let slots = (0..capacity)
            .map(|_| std::cell::UnsafeCell::new(None))
            .collect::<Vec<_>>()
            .into_boxed_slice();
        Self {
            slots,
            len: AtomicUsize::new(0),
        }
    }

    fn push(&self, value: String) {
        let idx = self.len.fetch_add(1, Ordering::Relaxed);
        if idx < self.slots.len() {
            unsafe {
                *self.slots[idx].get() = Some(value);
            }
        }
    }

    fn collect(&self) -> Vec<String> {
        let len = self.len.load(Ordering::Relaxed);
        (0..len)
            .filter_map(|i| unsafe { (*self.slots[i].get()).take() })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// RichMockMessage — 模拟真实 provider 消息(含 reasoning_content、tool_calls)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ToolCall {
    id: String,
    function_name: String,
    arguments: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RichMockMessage {
    role: Role,
    content: String,
    reasoning_content: Option<String>,
    tool_calls: Option<Vec<ToolCall>>,
    tool_call_id: Option<String>,
}

impl RichMockMessage {
    fn user(content: impl Into<String>) -> Self {
        Self {
            role: Role::User,
            content: content.into(),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    fn system(content: impl Into<String>) -> Self {
        Self {
            role: Role::System,
            content: content.into(),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: Role::Assistant,
            content: content.into(),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    fn assistant_with_reasoning(content: impl Into<String>, reasoning: impl Into<String>) -> Self {
        Self {
            role: Role::Assistant,
            content: content.into(),
            reasoning_content: Some(reasoning.into()),
            tool_calls: None,
            tool_call_id: None,
        }
    }

    fn assistant_with_tool_calls(
        content: impl Into<String>,
        reasoning: impl Into<String>,
        tool_calls: Vec<ToolCall>,
    ) -> Self {
        Self {
            role: Role::Assistant,
            content: content.into(),
            reasoning_content: Some(reasoning.into()),
            tool_calls: Some(tool_calls),
            tool_call_id: None,
        }
    }

    fn tool_result(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            role: Role::Tool,
            content: content.into(),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: Some(tool_call_id.into()),
        }
    }
}

impl ContextMessage for RichMockMessage {
    fn role(&self) -> Role {
        self.role
    }

    /// 模拟 DeepSeek 规则:仅工具调用的 assistant 消息保留 reasoning_content
    fn preserve_reasoning(&self) -> bool {
        self.role == Role::Assistant && self.tool_calls.is_some()
    }

    fn without_reasoning(mut self) -> Self {
        self.reasoning_content = None;
        self
    }

    fn with_role(mut self, role: Role) -> Self {
        self.role = role;
        self
    }
}

// ---------------------------------------------------------------------------
// RichMockBackend — 模拟真实 provider 后端行为
// ---------------------------------------------------------------------------

#[derive(Clone)]
pub struct RichMockOpts {
    pub common: agent_context::CommonOpts,
    pub token: u64,
}

impl std::convert::AsRef<agent_context::CommonOpts> for RichMockOpts {
    fn as_ref(&self) -> &agent_context::CommonOpts {
        &self.common
    }
}

#[derive(Clone)]
struct RichMockBackend {
    send_responses: Vec<Vec<RichMockMessage>>,
    call_index: Arc<std::sync::atomic::AtomicUsize>,
    token_count: usize,
    last_opts_token: Arc<std::sync::atomic::AtomicU64>,
}

impl RichMockBackend {
    fn new(responses: Vec<Vec<RichMockMessage>>) -> Self {
        Self {
            send_responses: responses,
            call_index: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            token_count: 0,
            last_opts_token: Arc::new(std::sync::atomic::AtomicU64::new(0)),
        }
    }
}

#[derive(Debug, Clone)]
struct RichMockResponse(Vec<RichMockMessage>);

impl ContextBackendResponse for RichMockResponse {
    fn response_type(&self) -> ResponseType {
        let has_r = self
            .0
            .iter()
            .any(|m| m.reasoning_content.as_ref().is_some_and(|r| !r.is_empty()));
        let has_c = self.0.iter().any(|m| !m.content.is_empty());
        match (has_r, has_c) {
            (false, false) => ResponseType::Empty,
            (true, false) => ResponseType::Reasoning,
            (false, true) => ResponseType::Content,
            (true, true) => ResponseType::ReasoningAndContent,
        }
    }

    fn reasoning_content(&self) -> Option<String> {
        let text: String = self
            .0
            .iter()
            .filter_map(|m| m.reasoning_content.clone())
            .collect();
        if text.is_empty() { None } else { Some(text) }
    }

    fn content(&self) -> Option<String> {
        let text: String = self.0.iter().map(|m| m.content.as_str()).collect();
        if text.is_empty() { None } else { Some(text) }
    }

    fn tool_calls(&self) -> Vec<agent_context::ToolCallInfo> {
        self.0
            .iter()
            .filter_map(|m| m.tool_calls.as_ref())
            .flatten()
            .map(|tc| agent_context::ToolCallInfo {
                id: tc.id.clone(),
                name: tc.function_name.clone(),
                arguments: tc.arguments.clone(),
            })
            .collect()
    }
}

impl ContextBackend for RichMockBackend {
    type Message = RichMockMessage;
    type Opts = RichMockOpts;
    type Response = RichMockResponse;

    fn user_message(&self, content: impl Into<String> + Send) -> Self::Message {
        RichMockMessage::user(content)
    }

    fn system_message(&self, content: impl Into<String> + Send) -> Self::Message {
        RichMockMessage::system(content)
    }

    fn tool_message(
        &self,
        tool_call_id: impl Into<String> + Send,
        content: impl Into<String> + Send,
    ) -> Self::Message {
        RichMockMessage::tool_result(tool_call_id, content)
    }

    fn extract_messages(
        &self,
        responses: &[Self::Response],
    ) -> Result<Vec<Self::Message>, AgentError> {
        Ok(responses.iter().flat_map(|r| r.0.iter().cloned()).collect())
    }

    fn merge_chunks(&self, _responses: &[Self::Response]) -> Option<Self::Message> {
        None
    }

    async fn estimate_tokens(&self, _messages: &[Self::Message]) -> Result<usize, AgentError> {
        Ok(self.token_count)
    }

    async fn send(
        &self,
        _messages: &[Self::Message],
        opts: &Self::Opts,
    ) -> Result<Self::Response, AgentError> {
        self.last_opts_token
            .store(opts.token, std::sync::atomic::Ordering::SeqCst);
        let idx = self
            .call_index
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let responses = &self.send_responses;
        if idx < responses.len() {
            Ok(RichMockResponse(responses[idx].clone()))
        } else {
            Ok(RichMockResponse(vec![]))
        }
    }

    fn send_stream(
        &self,
        _messages: Vec<Self::Message>,
        opts: Self::Opts,
    ) -> impl futures_core::Stream<Item = Result<Self::Response, AgentError>> + Send + 'static {
        self.last_opts_token
            .store(opts.token, std::sync::atomic::Ordering::SeqCst);
        let idx = self
            .call_index
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let responses = &self.send_responses;
        let chunks = if idx < responses.len() {
            responses[idx].clone()
        } else {
            vec![]
        };
        futures::stream::iter(chunks.into_iter().map(|m| Ok(RichMockResponse(vec![m]))))
    }
}

// ---------------------------------------------------------------------------
// 辅助函数
// ---------------------------------------------------------------------------

fn spawn_with_backend(backend: RichMockBackend) -> ActorRef<AgentContext<RichMockBackend>> {
    let ctx = AgentContext::new(backend, vec![]);
    AgentContext::spawn(ctx)
}

fn spawn_with_on_change(
    backend: RichMockBackend,
    on_change: impl Fn(ChangeEvent<RichMockMessage>) + Send + Sync + 'static,
) -> ActorRef<AgentContext<RichMockBackend>> {
    let ctx = AgentContext::new(backend, vec![]).with_on_change(on_change);
    AgentContext::spawn(ctx)
}

// ---------------------------------------------------------------------------
// 测试
// ---------------------------------------------------------------------------

#[tokio::test]
async fn basic_conversation() {
    let backend = RichMockBackend::new(vec![vec![RichMockMessage::assistant("Hello!")]]);
    let actor = spawn_with_backend(backend);

    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("Hi"),
        })
        .await
        .unwrap();

    // ask() 自动展开 Result:handler 返回 Result<Vec<M>, AgentError>,
    // ask() 返回 Result<Vec<M>, SendError>,unwrap() 得 Vec<M>
    let raw: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw.0[0].content, "Hello!");

    let all: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    assert_eq!(all.len(), 2);
    assert_eq!(all[0].role, Role::User);
    assert_eq!(all[1].role, Role::Assistant);
    assert_eq!(all[1].content, "Hello!");

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn reasoning_stripped_without_tool_call() {
    // backend 返回带 reasoning_content 的普通 assistant 消息(无 tool_calls)
    let backend = RichMockBackend::new(vec![vec![RichMockMessage::assistant_with_reasoning(
        "答案是42",
        "让我想想...",
    )]]);
    let actor = spawn_with_backend(backend);

    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("问题"),
        })
        .await
        .unwrap();

    // 调用方拿到原始响应(含 reasoning_content)
    let raw: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert!(
        raw.0[0].reasoning_content.is_some(),
        "原始响应应含 reasoning"
    );

    // 存储的消息应已剥离 reasoning_content
    let all: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    let stored_assistant = &all[1];
    assert_eq!(stored_assistant.role, Role::Assistant);
    assert!(
        stored_assistant.reasoning_content.is_none(),
        "非工具调用场景应剥离 reasoning_content"
    );

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn reasoning_preserved_with_tool_call() {
    // backend 返回带 tool_calls + reasoning_content 的 assistant 消息
    let backend = RichMockBackend::new(vec![vec![RichMockMessage::assistant_with_tool_calls(
        "",
        "需要调用工具",
        vec![ToolCall {
            id: "call_1".into(),
            function_name: "get_weather".into(),
            arguments: r#"{"city":"Beijing"}"#.into(),
        }],
    )]]);
    let actor = spawn_with_backend(backend);

    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("北京天气"),
        })
        .await
        .unwrap();

    let raw: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw.0.len(), 1, "Should have one response message");

    // 存储的 assistant 消息应保留 reasoning_content(因为有 tool_calls)
    let all: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    let stored_assistant = &all[1];
    assert_eq!(stored_assistant.role, Role::Assistant);
    assert!(
        stored_assistant.reasoning_content.is_some(),
        "工具调用场景应保留 reasoning_content"
    );
    assert!(stored_assistant.tool_calls.is_some());

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn full_tool_call_cycle() {
    // 模拟完整工具调用周期:
    // 1. user → assistant(tool_calls + reasoning)
    // 2. tool → assistant(final answer, 无 tool_calls, reasoning → 被剥离)
    let backend = RichMockBackend::new(vec![
        // 第一次 send:返回工具调用
        vec![RichMockMessage::assistant_with_tool_calls(
            "",
            "需要查询天气",
            vec![ToolCall {
                id: "call_1".into(),
                function_name: "get_weather".into(),
                arguments: r#"{"city":"Beijing"}"#.into(),
            }],
        )],
        // 第二次 send:返回最终回答(有 reasoning 无 tool_calls → reasoning 被剥离)
        vec![RichMockMessage::assistant_with_reasoning(
            "北京今天晴,25°C",
            "根据工具返回的数据分析",
        )],
    ]);
    let actor = spawn_with_backend(backend);

    // Round 1: user 发问
    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("北京天气怎么样?"),
        })
        .await
        .unwrap();

    // Send → assistant 返回 tool_calls
    let raw1: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert!(raw1.0[0].tool_calls.is_some());

    // 存储的消息保留 reasoning_content(有 tool_calls)
    let after_r1: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    assert_eq!(after_r1.len(), 2); // user + assistant
    assert!(
        after_r1[1].reasoning_content.is_some(),
        "工具调用 assistant 保留 reasoning"
    );

    // 追加工具结果
    actor
        .ask(AppendMsg {
            message: RichMockMessage::tool_result("call_1", r#"{"temp":25,"condition":"sunny"}"#),
        })
        .await
        .unwrap();

    // Round 2: Send → assistant 返回最终回答(无 tool_calls)
    let raw2: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert!(
        raw2.0[0].reasoning_content.is_some(),
        "原始响应含 reasoning"
    );

    // 验证最终上下文:
    // user → assistant(tool_calls, reasoning保留) → tool → assistant(reasoning被剥离)
    let final_msgs: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    assert_eq!(final_msgs.len(), 4);

    assert_eq!(final_msgs[0].role, Role::User);
    assert_eq!(final_msgs[1].role, Role::Assistant);
    assert!(final_msgs[1].tool_calls.is_some());
    assert!(
        final_msgs[1].reasoning_content.is_some(),
        "工具调用 assistant 保留 reasoning"
    );

    assert_eq!(final_msgs[2].role, Role::Tool);
    assert_eq!(final_msgs[2].tool_call_id.as_deref(), Some("call_1"));

    assert_eq!(final_msgs[3].role, Role::Assistant);
    assert!(
        final_msgs[3].reasoning_content.is_none(),
        "非工具调用 assistant 应剥离 reasoning"
    );
    assert_eq!(final_msgs[3].content, "北京今天晴,25°C");

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn send_returns_raw_to_caller() {
    let backend = RichMockBackend::new(vec![vec![RichMockMessage::assistant_with_reasoning(
        "答案",
        "思考过程",
    )]]);
    let actor = spawn_with_backend(backend);

    actor
        .ask(AppendMsg {
            message: RichMockMessage::user(""),
        })
        .await
        .unwrap();

    // Send 返回原始响应——调用方拿到完整 reasoning_content
    let raw: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw.0[0].content, "答案");
    assert!(
        raw.0[0].reasoning_content.is_some(),
        "调用方应拿到原始响应(含 reasoning)"
    );

    // AC 内部存储的是转换后的版本(reasoning 被剥离,因为无 tool_calls)
    let stored: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    assert!(stored[1].reasoning_content.is_none(), "AC 内部存储应已剥离");

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn send_stream_tool_call() {
    let backend = RichMockBackend::new(vec![vec![RichMockMessage::assistant_with_tool_calls(
        "",
        "调用工具",
        vec![ToolCall {
            id: "call_s".into(),
            function_name: "search".into(),
            arguments: r#"{"q":"test"}"#.into(),
        }],
    )]]);
    let actor = spawn_with_backend(backend);

    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("搜索"),
        })
        .await
        .unwrap();

    // SendStream 返回 AgentSendStream,消费流以触发 Drop 存储
    {
        use futures::StreamExt;
        let mut stream = actor
            .ask(SendStreamMsg {
                opts: rich_mock_opts(0),
            })
            .await
            .unwrap();
        let mut count = 0usize;
        while stream.next().await.is_some() {
            count += 1;
        }
        assert_eq!(count, 1, "Should have drained one stream item");
        for msg in stream.take_chunks().into_iter().flat_map(|r| r.0) {
            actor.ask(AppendMsg { message: msg }).await.unwrap();
        }
    }

    // 流式工具调用:reasoning_content 应保留(有 tool_calls)
    let stored: Vec<RichMockMessage> = actor.ask(MessagesMsg).await.unwrap();
    assert_eq!(stored.len(), 2);
    assert!(stored[1].tool_calls.is_some());
    assert!(
        stored[1].reasoning_content.is_some(),
        "流式工具调用应保留 reasoning_content"
    );

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn on_change_event_sequence() {
    let events = Arc::new(EventCollector::new(8));
    let events_clone = events.clone();

    let backend = RichMockBackend::new(vec![
        vec![RichMockMessage::assistant("R1")],
        vec![RichMockMessage::assistant("R2")],
    ]);

    let actor = spawn_with_on_change(backend, move |event: ChangeEvent<RichMockMessage>| {
        let label = match &event {
            ChangeEvent::Appended(m) => format!("Appended({})", m.content),
            ChangeEvent::Updated { index, old, new } => {
                format!("Updated({}, {}{})", index, old.content, new.content)
            }
            ChangeEvent::Removed { index, .. } => format!("Removed({})", index),
            ChangeEvent::Cleared { .. } => "Cleared".into(),
            _ => "Other".into(),
        };
        events_clone.push(label);
    });

    // 操作序列
    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("Q1"),
        })
        .await
        .unwrap();
    let raw1: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw1.0.len(), 1, "Should have one response message");
    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("Q2"),
        })
        .await
        .unwrap();
    let raw2: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw2.0.len(), 1, "Should have one response message");

    // 验证事件序列
    let captured = events.collect();
    assert_eq!(captured.len(), 4, "应有 4 个 Appended 事件");
    assert_eq!(captured[0], "Appended(Q1)");
    assert_eq!(captured[1], "Appended(R1)");
    assert_eq!(captured[2], "Appended(Q2)");
    assert_eq!(captured[3], "Appended(R2)");

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn on_change_tracks_tool_call_cycle() {
    let events = Arc::new(EventCollector::new(8));
    let events_clone = events.clone();

    let backend = RichMockBackend::new(vec![
        vec![RichMockMessage::assistant_with_tool_calls(
            "",
            "调用工具",
            vec![ToolCall {
                id: "tc1".into(),
                function_name: "fn".into(),
                arguments: "{}".into(),
            }],
        )],
        vec![RichMockMessage::assistant("Done")],
    ]);

    let actor = spawn_with_on_change(backend, move |event: ChangeEvent<RichMockMessage>| {
        if let ChangeEvent::Appended(m) = &event {
            let label = match m.role() {
                Role::User => format!("User({})", m.content),
                Role::Assistant => {
                    let has_tc = if m.tool_calls.is_some() { "+tc" } else { "" };
                    format!("Assistant({}){}", m.content, has_tc)
                }
                Role::Tool => format!("Tool({})", m.content),
                Role::System => format!("System({})", m.content),
            };
            events_clone.push(label);
        }
    });

    // Round 1: user → assistant(tool_calls)
    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("Q"),
        })
        .await
        .unwrap();
    let raw_round1: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw_round1.0.len(), 1, "Should have one response message");

    // Round 2: tool → assistant
    actor
        .ask(AppendMsg {
            message: RichMockMessage::tool_result("tc1", "result"),
        })
        .await
        .unwrap();
    let raw_round2: RichMockResponse = actor
        .ask(SendMsg {
            opts: rich_mock_opts(0),
        })
        .await
        .unwrap();
    assert_eq!(raw_round2.0.len(), 1, "Should have one response message");

    let captured = events.collect();
    assert_eq!(
        captured.len(),
        4,
        "应有 4 个 Appended 事件:user, assistant+tc, tool, assistant"
    );
    assert_eq!(captured[0], "User(Q)");
    assert_eq!(captured[1], "Assistant()+tc");
    assert_eq!(captured[2], "Tool(result)");
    assert_eq!(captured[3], "Assistant(Done)");

    actor.stop_gracefully().await.unwrap();
}

#[tokio::test]
async fn opts_passthrough_to_backend() {
    let last_opts_token = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let mut backend = RichMockBackend::new(vec![
        vec![RichMockMessage::assistant("R1")],
        vec![RichMockMessage::assistant("R2")],
    ]);
    backend.last_opts_token = last_opts_token.clone();

    let actor = spawn_with_backend(backend);

    actor
        .ask(AppendMsg {
            message: RichMockMessage::user("Q1"),
        })
        .await
        .unwrap();

    // Send:传入 token=100,验证后端收到
    let send_response = actor
        .ask(SendMsg {
            opts: rich_mock_opts(100),
        })
        .await
        .unwrap();
    assert!(!send_response.0.is_empty(), "Response should not be empty");
    assert_eq!(
        last_opts_token.load(Ordering::SeqCst),
        100,
        "Send 的 opts 应透传到 backend.send()"
    );

    // SendStream:传入 token=200,验证后端收到
    actor
        .ask(SendStreamMsg {
            opts: rich_mock_opts(200),
        })
        .await
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    assert_eq!(
        last_opts_token.load(Ordering::SeqCst),
        200,
        "SendStream 的 opts 应透传到 backend.send_stream()"
    );

    actor.stop_gracefully().await.unwrap();
}