-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtests.rs
More file actions
2526 lines (2226 loc) · 84 KB
/
Copy pathtests.rs
File metadata and controls
2526 lines (2226 loc) · 84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::*;
use crate::config::{ModelConfig, ModelModalities, ProviderConfig};
use crate::llm::{ContentBlock, LlmResponse, StreamEvent, TokenUsage};
use crate::store::SessionStore;
#[derive(Clone)]
struct StaticStreamingClient {
text: String,
}
impl StaticStreamingClient {
fn new(text: impl Into<String>) -> Self {
Self { text: text.into() }
}
fn response(&self) -> LlmResponse {
LlmResponse {
message: Message {
role: "assistant".to_string(),
content: vec![ContentBlock::Text {
text: self.text.clone(),
}],
reasoning_content: None,
},
usage: TokenUsage {
prompt_tokens: 1,
completion_tokens: 1,
total_tokens: 2,
cache_read_tokens: None,
cache_write_tokens: None,
},
stop_reason: Some("end_turn".to_string()),
meta: None,
}
}
}
#[derive(Clone)]
struct FailingStreamingClient;
#[derive(Clone)]
struct CancellableStreamingClient {
text: String,
}
#[derive(Debug, Default)]
struct RecordingRuntimeHook {
events: std::sync::Mutex<Vec<(String, String, AgentEvent)>>,
}
#[derive(Debug, Default)]
struct CapturingContextProvider {
session_ids: std::sync::Mutex<Vec<Option<String>>>,
}
#[derive(Default)]
struct TestWorkspaceFs {
files: std::sync::RwLock<std::collections::HashMap<String, String>>,
}
impl TestWorkspaceFs {
fn insert(&self, path: &str, content: &str) {
self.files
.write()
.unwrap()
.insert(path.to_string(), content.to_string());
}
fn read_raw(&self, path: &str) -> Option<String> {
self.files.read().unwrap().get(path).cloned()
}
}
#[async_trait::async_trait]
impl crate::workspace::WorkspaceFileSystem for TestWorkspaceFs {
async fn read_text(
&self,
path: &crate::workspace::WorkspacePath,
) -> crate::workspace::WorkspaceResult<String> {
self.files
.read()
.unwrap()
.get(path.as_str())
.cloned()
.ok_or_else(|| crate::workspace::WorkspaceError::NotFound {
path: path.as_str().to_string(),
})
}
async fn write_text(
&self,
path: &crate::workspace::WorkspacePath,
content: &str,
) -> crate::workspace::WorkspaceResult<crate::workspace::WorkspaceWriteOutcome> {
self.insert(path.as_str(), content);
Ok(crate::workspace::WorkspaceWriteOutcome {
bytes: content.len(),
lines: content.lines().count(),
})
}
async fn list_dir(
&self,
path: &crate::workspace::WorkspacePath,
) -> crate::workspace::WorkspaceResult<Vec<crate::workspace::WorkspaceDirEntry>> {
let prefix = if path.is_root() {
String::new()
} else {
format!("{}/", path.as_str())
};
let files = self.files.read().unwrap();
let mut entries = Vec::new();
for (file_path, content) in files.iter() {
if !file_path.starts_with(&prefix) {
continue;
}
let remaining = &file_path[prefix.len()..];
if remaining.is_empty() || remaining.contains('/') {
continue;
}
entries.push(crate::workspace::WorkspaceDirEntry {
name: remaining.to_string(),
kind: crate::workspace::WorkspaceFileType::File,
size: content.len() as u64,
});
}
Ok(entries)
}
}
#[derive(Default)]
struct TestWorkspaceRunner {
commands: std::sync::RwLock<Vec<String>>,
}
#[async_trait::async_trait]
impl crate::workspace::WorkspaceCommandRunner for TestWorkspaceRunner {
async fn exec(
&self,
request: crate::workspace::CommandRequest,
) -> anyhow::Result<crate::workspace::CommandOutput> {
self.commands.write().unwrap().push(request.command.clone());
Ok(crate::workspace::CommandOutput {
output: format!("session runner: {}\n", request.command),
exit_code: 0,
timed_out: false,
})
}
}
#[async_trait::async_trait]
impl crate::context::ContextProvider for CapturingContextProvider {
fn name(&self) -> &str {
"capturing-context"
}
async fn query(
&self,
query: &crate::context::ContextQuery,
) -> anyhow::Result<crate::context::ContextResult> {
self.session_ids
.lock()
.unwrap()
.push(query.session_id.clone());
Ok(crate::context::ContextResult::new(self.name()))
}
}
#[async_trait::async_trait]
impl crate::hooks::HookExecutor for RecordingRuntimeHook {
async fn fire(&self, _event: &crate::hooks::HookEvent) -> crate::hooks::HookResult {
crate::hooks::HookResult::Continue(None)
}
async fn record_agent_event(&self, event: &AgentEvent, run_id: &str, session_id: &str) {
self.events.lock().unwrap().push((
run_id.to_string(),
session_id.to_string(),
event.clone(),
));
}
}
impl CancellableStreamingClient {
fn new(text: impl Into<String>) -> Self {
Self { text: text.into() }
}
}
#[async_trait::async_trait]
impl LlmClient for StaticStreamingClient {
async fn complete(
&self,
_messages: &[Message],
_system: Option<&str>,
_tools: &[crate::llm::ToolDefinition],
) -> anyhow::Result<LlmResponse> {
Ok(self.response())
}
async fn complete_streaming(
&self,
_messages: &[Message],
_system: Option<&str>,
_tools: &[crate::llm::ToolDefinition],
_cancel_token: tokio_util::sync::CancellationToken,
) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
let (tx, rx) = mpsc::channel(8);
let text = self.text.clone();
let response = self.response();
tokio::spawn(async move {
let _ = tx.send(StreamEvent::TextDelta(text)).await;
let _ = tx.send(StreamEvent::Done(response)).await;
});
Ok(rx)
}
}
#[async_trait::async_trait]
impl LlmClient for FailingStreamingClient {
async fn complete(
&self,
_messages: &[Message],
_system: Option<&str>,
_tools: &[crate::llm::ToolDefinition],
) -> anyhow::Result<LlmResponse> {
anyhow::bail!("non-streaming fallback failed")
}
async fn complete_streaming(
&self,
_messages: &[Message],
_system: Option<&str>,
_tools: &[crate::llm::ToolDefinition],
_cancel_token: tokio_util::sync::CancellationToken,
) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
anyhow::bail!("streaming setup failed")
}
}
#[async_trait::async_trait]
impl LlmClient for CancellableStreamingClient {
async fn complete(
&self,
_messages: &[Message],
_system: Option<&str>,
_tools: &[crate::llm::ToolDefinition],
) -> anyhow::Result<LlmResponse> {
anyhow::bail!("cancellable client does not support fallback completion")
}
async fn complete_streaming(
&self,
_messages: &[Message],
_system: Option<&str>,
_tools: &[crate::llm::ToolDefinition],
cancel_token: tokio_util::sync::CancellationToken,
) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
let (tx, rx) = mpsc::channel(8);
let text = self.text.clone();
tokio::spawn(async move {
let _ = tx.send(StreamEvent::TextDelta(text)).await;
cancel_token.cancelled().await;
});
Ok(rx)
}
}
fn test_config() -> CodeConfig {
CodeConfig {
default_model: Some("anthropic/claude-sonnet-4-20250514".to_string()),
providers: vec![
ProviderConfig {
name: "anthropic".to_string(),
api_key: Some("test-key".to_string()),
base_url: None,
headers: std::collections::HashMap::new(),
session_id_header: None,
models: vec![ModelConfig {
id: "claude-sonnet-4-20250514".to_string(),
name: "Claude Sonnet 4".to_string(),
family: "claude-sonnet".to_string(),
api_key: None,
base_url: None,
headers: std::collections::HashMap::new(),
session_id_header: None,
attachment: false,
reasoning: false,
tool_call: true,
temperature: true,
release_date: None,
modalities: ModelModalities::default(),
cost: Default::default(),
limit: Default::default(),
}],
},
ProviderConfig {
name: "openai".to_string(),
api_key: Some("test-openai-key".to_string()),
base_url: None,
headers: std::collections::HashMap::new(),
session_id_header: None,
models: vec![ModelConfig {
id: "gpt-4o".to_string(),
name: "GPT-4o".to_string(),
family: "gpt-4".to_string(),
api_key: None,
base_url: None,
headers: std::collections::HashMap::new(),
session_id_header: None,
attachment: false,
reasoning: false,
tool_call: true,
temperature: true,
release_date: None,
modalities: ModelModalities::default(),
cost: Default::default(),
limit: Default::default(),
}],
},
],
..Default::default()
}
}
fn build_effective_registry_for_test(
agent_registry: Option<Arc<crate::skills::SkillRegistry>>,
opts: &SessionOptions,
) -> Arc<crate::skills::SkillRegistry> {
super::capabilities::build_effective_skill_registry(agent_registry.as_deref(), opts)
}
#[tokio::test]
async fn test_from_config() {
let agent = Agent::from_config(test_config()).await;
assert!(agent.is_ok());
}
#[tokio::test]
async fn test_session_default() {
let agent = Agent::from_config(test_config()).await.unwrap();
let session = agent.session("/tmp/test-workspace", None);
assert!(session.is_ok());
let debug = format!("{:?}", session.unwrap());
assert!(debug.contains("AgentSession"));
}
#[tokio::test]
async fn test_session_uses_workspace_backend_for_direct_tools() {
let fs = Arc::new(TestWorkspaceFs::default());
fs.insert("app.txt", "hello from backend\n");
let fs_backend: Arc<dyn crate::workspace::WorkspaceFileSystem> = fs.clone();
let runner = Arc::new(TestWorkspaceRunner::default());
let runner_backend: Arc<dyn crate::workspace::WorkspaceCommandRunner> = runner.clone();
let services = crate::workspace::WorkspaceServices::builder(
crate::workspace::WorkspaceRef::new("session-workspace", "session://workspace"),
fs_backend,
)
.command_runner(runner_backend)
.build();
let agent = Agent::from_config(test_config()).await.unwrap();
let session = agent
.session(
"/server/local-placeholder",
Some(SessionOptions::new().with_workspace_backend(services)),
)
.unwrap();
let tool_names = session.tool_names();
assert!(tool_names.contains(&"read".to_string()));
assert!(tool_names.contains(&"write".to_string()));
assert!(tool_names.contains(&"ls".to_string()));
assert!(tool_names.contains(&"bash".to_string()));
assert!(!tool_names.contains(&"grep".to_string()));
assert!(!tool_names.contains(&"glob".to_string()));
assert!(!tool_names.contains(&"git".to_string()));
let read = session.read_file("app.txt").await.unwrap();
assert!(read.contains("hello from backend"));
let write = session
.write_file("created.txt", "one\ntwo\n")
.await
.unwrap();
assert_eq!(write.exit_code, 0, "{}", write.output);
assert_eq!(fs.read_raw("created.txt").as_deref(), Some("one\ntwo\n"));
let listing = session.ls(None).await.unwrap();
assert_eq!(listing.exit_code, 0, "{}", listing.output);
assert!(listing.output.contains("created.txt"));
let edit = session
.edit_file("created.txt", "one", "uno", false)
.await
.unwrap();
assert_eq!(edit.exit_code, 0, "{}", edit.output);
assert_eq!(fs.read_raw("created.txt").as_deref(), Some("uno\ntwo\n"));
let patch = session
.patch_file("created.txt", "@@ -1,2 +1,2 @@\n uno\n-two\n+dos")
.await
.unwrap();
assert_eq!(patch.exit_code, 0, "{}", patch.output);
assert_eq!(fs.read_raw("created.txt").as_deref(), Some("uno\ndos\n"));
let bash = session.bash("pwd").await.unwrap();
assert_eq!(bash, "session runner: pwd\n");
}
#[tokio::test]
async fn test_session_routes_agents_md_through_context_provider() {
let temp_dir = tempfile::tempdir().unwrap();
std::fs::write(
temp_dir.path().join("AGENTS.md"),
"Always run focused tests before reporting completion.",
)
.unwrap();
let agent = Agent::from_config(test_config()).await.unwrap();
let session = agent
.session(temp_dir.path().display().to_string(), None)
.unwrap();
let agents_provider = session
.config
.context_providers
.iter()
.find(|provider| provider.name() == "agents_md")
.expect("AGENTS.md provider should be registered");
assert!(!session
.config
.prompt_slots
.extra
.as_deref()
.unwrap_or_default()
.contains("Project Instructions (AGENTS.md)"));
let result = agents_provider
.query(&crate::context::ContextQuery::new("complete the task"))
.await
.unwrap();
assert_eq!(result.items.len(), 1);
assert_eq!(result.items[0].id, "agents_md");
assert!(result.items[0]
.content
.contains("Always run focused tests before reporting completion."));
assert_eq!(result.items[0].relevance, 0.95);
}
#[tokio::test]
async fn test_session_initializes_without_legacy_agentic_tools() {
let agent = Agent::from_config(test_config()).await.unwrap();
let _session = agent.session("/tmp/test-workspace", None).unwrap();
}
#[tokio::test]
async fn test_session_with_model_override() {
let agent = Agent::from_config(test_config()).await.unwrap();
let opts = SessionOptions::new().with_model("openai/gpt-4o");
let session = agent.session("/tmp/test-workspace", Some(opts));
assert!(session.is_ok());
}
#[tokio::test]
async fn test_session_with_invalid_model_format() {
let agent = Agent::from_config(test_config()).await.unwrap();
let opts = SessionOptions::new().with_model("gpt-4o");
let session = agent.session("/tmp/test-workspace", Some(opts));
assert!(session.is_err());
}
#[tokio::test]
async fn test_session_with_model_not_found() {
let agent = Agent::from_config(test_config()).await.unwrap();
let opts = SessionOptions::new().with_model("openai/nonexistent");
let session = agent.session("/tmp/test-workspace", Some(opts));
assert!(session.is_err());
}
#[tokio::test]
async fn test_session_skill_dirs_preserve_agent_registry_validator() {
use crate::skills::validator::DefaultSkillValidator;
use crate::skills::SkillRegistry;
let registry = Arc::new(SkillRegistry::new());
registry.set_validator(Arc::new(DefaultSkillValidator::default()));
let temp_dir = tempfile::tempdir().unwrap();
let invalid_skill = temp_dir.path().join("invalid.md");
std::fs::write(
&invalid_skill,
r#"---
name: BadName
description: "invalid skill name"
kind: instruction
---
# Invalid Skill
"#,
)
.unwrap();
let opts = SessionOptions::new().with_skill_dirs([temp_dir.path()]);
let effective_registry = build_effective_registry_for_test(Some(registry), &opts);
assert!(effective_registry.get("BadName").is_none());
}
#[tokio::test]
async fn test_session_skill_registry_overrides_agent_registry_without_polluting_parent() {
use crate::skills::{Skill, SkillKind, SkillRegistry};
let registry = Arc::new(SkillRegistry::new());
registry.register_unchecked(Arc::new(Skill {
name: "shared-skill".to_string(),
description: "agent level".to_string(),
allowed_tools: None,
disable_model_invocation: false,
kind: SkillKind::Instruction,
content: "agent content".to_string(),
tags: vec![],
version: None,
}));
let session_registry = Arc::new(SkillRegistry::new());
session_registry.register_unchecked(Arc::new(Skill {
name: "shared-skill".to_string(),
description: "session level".to_string(),
allowed_tools: None,
disable_model_invocation: false,
kind: SkillKind::Instruction,
content: "session content".to_string(),
tags: vec![],
version: None,
}));
let opts = SessionOptions::new().with_skill_registry(session_registry);
let effective_registry = build_effective_registry_for_test(Some(registry.clone()), &opts);
assert_eq!(
effective_registry.get("shared-skill").unwrap().content,
"session content"
);
assert_eq!(
registry.get("shared-skill").unwrap().content,
"agent content"
);
}
#[tokio::test]
async fn test_session_skill_dirs_override_session_registry_and_skip_invalid_entries() {
use crate::skills::{Skill, SkillKind, SkillRegistry};
let session_registry = Arc::new(SkillRegistry::new());
session_registry.register_unchecked(Arc::new(Skill {
name: "shared-skill".to_string(),
description: "session registry".to_string(),
allowed_tools: None,
disable_model_invocation: false,
kind: SkillKind::Instruction,
content: "registry content".to_string(),
tags: vec![],
version: None,
}));
let temp_dir = tempfile::tempdir().unwrap();
std::fs::write(
temp_dir.path().join("shared.md"),
r#"---
name: shared-skill
description: "skill dir override"
kind: instruction
---
# Shared Skill
dir content
"#,
)
.unwrap();
std::fs::write(temp_dir.path().join("README.md"), "# not a skill").unwrap();
let opts = SessionOptions::new()
.with_skill_registry(session_registry)
.with_skill_dirs([temp_dir.path()]);
let effective_registry = build_effective_registry_for_test(None, &opts);
assert_eq!(
effective_registry.get("shared-skill").unwrap().description,
"skill dir override"
);
assert!(effective_registry.get("README").is_none());
}
#[tokio::test]
async fn test_session_specific_skills_do_not_leak_across_sessions() {
use crate::skills::{Skill, SkillKind, SkillRegistry};
let mut agent = Agent::from_config(test_config()).await.unwrap();
let agent_registry = Arc::new(SkillRegistry::with_builtins());
agent.config.skill_registry = Some(agent_registry);
let session_registry = Arc::new(SkillRegistry::new());
session_registry.register_unchecked(Arc::new(Skill {
name: "session-only".to_string(),
description: "only for first session".to_string(),
allowed_tools: None,
disable_model_invocation: false,
kind: SkillKind::Instruction,
content: "session one".to_string(),
tags: vec![],
version: None,
}));
let session_one = agent
.session(
"/tmp/test-workspace",
Some(SessionOptions::new().with_skill_registry(session_registry)),
)
.unwrap();
let session_two = agent.session("/tmp/test-workspace", None).unwrap();
assert!(session_one
.config
.skill_registry
.as_ref()
.unwrap()
.get("session-only")
.is_some());
assert!(session_two
.config
.skill_registry
.as_ref()
.unwrap()
.get("session-only")
.is_none());
}
#[tokio::test]
async fn test_session_for_agent_applies_definition_and_keeps_skill_overrides_isolated() {
use crate::skills::{Skill, SkillKind, SkillRegistry};
use crate::subagent::AgentDefinition;
let mut agent = Agent::from_config(test_config()).await.unwrap();
agent.config.skill_registry = Some(Arc::new(SkillRegistry::with_builtins()));
let definition = AgentDefinition::new("reviewer", "Review code")
.with_prompt("Agent definition prompt")
.with_max_steps(7);
let session_registry = Arc::new(SkillRegistry::new());
session_registry.register_unchecked(Arc::new(Skill {
name: "agent-session-skill".to_string(),
description: "agent session only".to_string(),
allowed_tools: None,
disable_model_invocation: false,
kind: SkillKind::Instruction,
content: "agent session content".to_string(),
tags: vec![],
version: None,
}));
let session_one = agent
.session_for_agent(
"/tmp/test-workspace",
&definition,
Some(SessionOptions::new().with_skill_registry(session_registry)),
)
.unwrap();
let session_two = agent
.session_for_agent("/tmp/test-workspace", &definition, None)
.unwrap();
assert_eq!(session_one.config.max_tool_rounds, 7);
let extra = session_one.config.prompt_slots.extra.as_deref().unwrap();
assert!(extra.contains("Agent definition prompt"));
assert!(!extra.contains("agent-session-skill"));
assert!(session_one
.config
.context_providers
.iter()
.any(|provider| provider.name() == "skills_catalog"));
assert!(session_one
.config
.skill_registry
.as_ref()
.unwrap()
.get("agent-session-skill")
.is_some());
assert!(session_two
.config
.skill_registry
.as_ref()
.unwrap()
.get("agent-session-skill")
.is_none());
}
#[tokio::test]
async fn test_session_for_agent_preserves_existing_prompt_slots_when_injecting_definition_prompt() {
use crate::prompts::SystemPromptSlots;
use crate::subagent::AgentDefinition;
let agent = Agent::from_config(test_config()).await.unwrap();
let definition = AgentDefinition::new("planner", "Plan work")
.with_prompt("Definition extra prompt")
.with_max_steps(3);
let opts = SessionOptions::new().with_prompt_slots(SystemPromptSlots {
style: None,
role: Some("Custom role".to_string()),
guidelines: None,
response_style: None,
extra: None,
});
let session = agent
.session_for_agent("/tmp/test-workspace", &definition, Some(opts))
.unwrap();
assert_eq!(
session.config.prompt_slots.role.as_deref(),
Some("Custom role")
);
assert!(session
.config
.prompt_slots
.extra
.as_deref()
.unwrap()
.contains("Definition extra prompt"));
assert_eq!(session.config.max_tool_rounds, 3);
}
#[tokio::test]
async fn test_new_with_acl_string() {
let acl = r#"
default_model = "anthropic/claude-sonnet-4-20250514"
providers "anthropic" {
apiKey = "test-key"
models "claude-sonnet-4-20250514" {
name = "Claude Sonnet 4"
}
}
"#;
let agent = Agent::new(acl).await;
assert!(agent.is_ok());
}
#[tokio::test]
async fn test_create_alias_acl() {
let acl = r#"
default_model = "anthropic/claude-sonnet-4-20250514"
providers "anthropic" {
apiKey = "test-key"
models "claude-sonnet-4-20250514" {
name = "Claude Sonnet 4"
}
}
"#;
let agent = Agent::create(acl).await;
assert!(agent.is_ok());
}
#[tokio::test]
async fn test_create_and_new_produce_same_result() {
let acl = r#"
default_model = "anthropic/claude-sonnet-4-20250514"
providers "anthropic" {
apiKey = "test-key"
models "claude-sonnet-4-20250514" {
name = "Claude Sonnet 4"
}
}
"#;
let agent_new = Agent::new(acl).await;
let agent_create = Agent::create(acl).await;
assert!(agent_new.is_ok());
assert!(agent_create.is_ok());
// Both should produce working sessions
let session_new = agent_new.unwrap().session("/tmp/test-ws-new", None);
let session_create = agent_create.unwrap().session("/tmp/test-ws-create", None);
assert!(session_new.is_ok());
assert!(session_create.is_ok());
}
#[tokio::test]
async fn test_new_with_existing_acl_file_uses_file_loading() {
let temp_dir = tempfile::tempdir().unwrap();
let config_path = temp_dir.path().join("agent.acl");
std::fs::write(&config_path, "providers {").unwrap();
let err = Agent::new(config_path.display().to_string())
.await
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("Failed to load config"));
assert!(msg.contains("agent.acl"));
assert!(!msg.contains("Failed to parse config as ACL string"));
}
#[tokio::test]
async fn test_new_with_missing_acl_file_reports_not_found() {
let temp_dir = tempfile::tempdir().unwrap();
let missing_path = temp_dir.path().join("agent.acl");
let err = Agent::new(missing_path.display().to_string())
.await
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("Config file not found"));
assert!(msg.contains("agent.acl"));
assert!(!msg.contains("Failed to parse config as ACL string"));
}
#[tokio::test]
async fn test_new_rejects_hcl_files() {
let temp_dir = tempfile::tempdir().unwrap();
let config_path = temp_dir.path().join("agent.hcl");
std::fs::write(&config_path, "default_model = \"openai/test\"").unwrap();
let err = Agent::new(config_path.display().to_string())
.await
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("HCL config files are not supported in 2.0"));
assert!(msg.contains(".acl"));
}
#[test]
fn test_from_config_requires_default_model() {
let rt = tokio::runtime::Runtime::new().unwrap();
let config = CodeConfig {
providers: vec![ProviderConfig {
name: "anthropic".to_string(),
api_key: Some("test-key".to_string()),
base_url: None,
headers: std::collections::HashMap::new(),
session_id_header: None,
models: vec![],
}],
..Default::default()
};
let result = rt.block_on(Agent::from_config(config));
assert!(result.is_err());
}
#[tokio::test]
async fn test_history_empty_on_new_session() {
let agent = Agent::from_config(test_config()).await.unwrap();
let session = agent.session("/tmp/test-workspace", None).unwrap();
assert!(session.history().is_empty());
}
#[tokio::test]
async fn test_stream_updates_history_and_auto_saves() {
let store = Arc::new(crate::store::MemorySessionStore::new());
let agent = Agent::from_config(test_config()).await.unwrap();
let opts = SessionOptions::new()
.with_session_store(store.clone())
.with_session_id("stream-history-test")
.with_auto_save(true);
let session = agent
.build_session(
"/tmp/test-stream-history".into(),
Arc::new(StaticStreamingClient::new("streamed answer")),
&opts,
)
.unwrap();
let (mut rx, handle) = session.stream("hello", None).await.unwrap();
let mut saw_end = false;
while let Some(event) = rx.recv().await {
if matches!(event, AgentEvent::End { .. }) {
saw_end = true;
break;
}
}
handle.await.unwrap();
assert!(saw_end);
let history = session.history();
assert_eq!(history.len(), 2);
assert_eq!(history[0].text(), "hello");
assert_eq!(history[1].text(), "streamed answer");
let saved = store
.load("stream-history-test")
.await
.unwrap()
.expect("saved session");
assert_eq!(saved.messages.len(), 2);
assert_eq!(saved.messages[1].text(), "streamed answer");
let run_records = store
.load_run_records("stream-history-test")
.await
.unwrap()
.expect("saved run records");
assert_eq!(run_records.len(), 1);
assert_eq!(
run_records[0].snapshot.status,
crate::run::RunStatus::Completed
);
assert!(run_records[0]
.events
.iter()
.any(|record| matches!(record.event, AgentEvent::End { .. })));
}
#[tokio::test]
async fn test_stream_with_custom_history_does_not_update_session_history() {
let agent = Agent::from_config(test_config()).await.unwrap();
let session = agent
.build_session(
"/tmp/test-stream-custom-history".into(),
Arc::new(StaticStreamingClient::new("custom history answer")),
&SessionOptions::new(),
)
.unwrap();
let custom_history = vec![Message::user("custom prompt")];
let (mut rx, handle) = session
.stream("ignored", Some(&custom_history))
.await
.unwrap();
while let Some(event) = rx.recv().await {
if matches!(event, AgentEvent::End { .. }) {
break;
}
}
handle.await.unwrap();
assert!(session.history().is_empty());
}
#[tokio::test]
async fn test_stream_error_does_not_update_history_or_auto_save() {
let store = Arc::new(crate::store::MemorySessionStore::new());
let agent = Agent::from_config(test_config()).await.unwrap();
let opts = SessionOptions::new()
.with_session_store(store.clone())
.with_session_id("stream-error-test")
.with_auto_save(true);
let session = agent
.build_session(
"/tmp/test-stream-error".into(),
Arc::new(FailingStreamingClient),
&opts,
)
.unwrap();
let (mut rx, handle) = session.stream("hello", None).await.unwrap();
let mut saw_error = false;
while let Some(event) = rx.recv().await {
if matches!(event, AgentEvent::Error { .. }) {
saw_error = true;
break;
}
}
handle.await.unwrap();
assert!(saw_error);
assert!(session.history().is_empty());
assert!(store.load("stream-error-test").await.unwrap().is_none());
}
#[tokio::test]
async fn test_stream_cancel_does_not_update_history_or_auto_save() {
let store = Arc::new(crate::store::MemorySessionStore::new());
let agent = Agent::from_config(test_config()).await.unwrap();
let opts = SessionOptions::new()
.with_session_store(store.clone())
.with_session_id("stream-cancel-test")
.with_auto_save(true);
let session = agent
.build_session(
"/tmp/test-stream-cancel".into(),
Arc::new(CancellableStreamingClient::new("partial answer")),
&opts,
)
.unwrap();
let (mut rx, handle) = session.stream("hello", None).await.unwrap();
let mut saw_delta = false;
for _ in 0..16 {
let event = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
.await
.expect("stream event before timeout")
.expect("stream should stay open until cancelled");
if matches!(event, AgentEvent::TextDelta { ref text } if text == "partial answer") {
saw_delta = true;
break;
}
}
assert!(saw_delta);