@ondeinference / ed Mirror · read-only
Fork 0

Read-only mirror of github.com/ondeinference/ed.

Mirrored from https://github.com/ondeinference/ed.git

Synced Nov 23, 01:00 UTC

development
rs 123 lines 4.74 KB
Raw
1 //! `Claude` against a mock OpenAI-compatible endpoint: the stored key becomes the bearer, a
2 //! streamed tool-call turn round-trips, and the process environment is never consulted.
3
4 use std::sync::Arc;
5
6 use agent_client_protocol::schema::ProtocolVersion;
7 use agent_client_protocol::schema::v1::{
8 ContentBlock, InitializeRequest, NewSessionRequest, PromptRequest, StopReason, TextContent,
9 };
10 use agent_client_protocol::{Agent, Channel, Client, ConnectionTo};
11 use ed_acp::{AuthProvider, ServeOptions};
12 use ed_acp_testkit::{MockStats, Script, Step, TEST_KEY, start_mock_llm, temp_dir};
13 use ed_claude::{Claude, ClaudeAuth, DEFAULT_MODEL, MODELS, credentials};
14 use serde_json::json;
15
16 /// Held by every test that changes the process environment or runs the agent, which reads it,
17 /// so a `set_var` never overlaps another thread's `getenv`.
18 static ENV: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
19
20 #[test]
21 fn no_key_means_no_llm_config_even_with_provider_env_set() {
22 let _env = ENV.blocking_lock();
23 let dir = temp_dir("ed-claude-nokey");
24 // SAFETY: ENV is held, and the other test that reads the environment waits for it.
25 unsafe {
26 std::env::set_var("OPENAI_API_KEY", "sk-from-env");
27 std::env::set_var("ED_CLAUDE_API_KEY", "sk-from-env");
28 std::env::set_var("ONDE_API_KEY", "app:secret");
29 }
30 let auth = ClaudeAuth::new().with_dir(dir.clone());
31 assert!(auth.llm_config().is_none());
32 unsafe {
33 std::env::remove_var("OPENAI_API_KEY");
34 std::env::remove_var("ED_CLAUDE_API_KEY");
35 std::env::remove_var("ONDE_API_KEY");
36 }
37 }
38
39 #[test]
40 fn llm_config_uses_the_stored_key_and_model() {
41 let dir = temp_dir("ed-claude-config");
42 let auth = ClaudeAuth::new().with_dir(dir.clone());
43 credentials::store_in_for_tests(&dir, "sk-ant-1", Some("claude-opus-5-5"));
44 let config = auth.llm_config().expect("config");
45 assert_eq!(config.base_url, "https://api.anthropic.com/v1");
46 assert_eq!(config.api_key.as_deref(), Some("sk-ant-1"));
47 assert_eq!(config.model, "claude-opus-5-5");
48
49 // A model outside the offered list falls back to the default.
50 credentials::store_in_for_tests(&dir, "sk-ant-1", Some("gpt-4o"));
51 assert_eq!(auth.llm_config().unwrap().model, DEFAULT_MODEL);
52 assert_eq!(auth.models().unwrap(), MODELS.map(String::from).to_vec());
53 }
54
55 #[tokio::test]
56 async fn a_streamed_tool_call_turn_round_trips() {
57 let _env = ENV.lock().await;
58 let data = temp_dir("ed-claude-data");
59 let key_dir = temp_dir("ed-claude-keys");
60 let work = temp_dir("ed-claude-work");
61 std::fs::write(work.join("hello.txt"), "hi").unwrap();
62 // SAFETY: ENV is held for the whole turn; only the data dir, no credentials.
63 unsafe { std::env::set_var("ED_CLAUDE_DATA_DIR", &data) };
64 credentials::store_in_for_tests(&key_dir, TEST_KEY, None);
65
66 let stats = Arc::new(MockStats::default());
67 let script = Script(vec![
68 Step::ToolCall {
69 name: "list_directory",
70 arguments: json!({"path": "."}),
71 },
72 Step::Final("done"),
73 ]);
74 let base = start_mock_llm(script, stats.clone()).await;
75 let auth = ClaudeAuth::new().with_base_url(base).with_dir(key_dir);
76
77 let (agent_end, client_end) = Channel::duplex();
78 let opts = ServeOptions {
79 yolo: true,
80 surface: "app",
81 };
82 tokio::spawn(ed_acp::serve(
83 Arc::new(Claude::without_shell().with_auth(auth)),
84 opts,
85 agent_end,
86 ));
87
88 let stop = Client
89 .builder()
90 .connect_with(client_end, |conn: ConnectionTo<Agent>| async move {
91 conn.send_request(InitializeRequest::new(ProtocolVersion::V1))
92 .block_task()
93 .await?;
94 let session = conn
95 .send_request(NewSessionRequest::new(work.clone()))
96 .block_task()
97 .await?;
98 let reply = conn
99 .send_request(PromptRequest::new(
100 session.session_id,
101 vec![ContentBlock::Text(TextContent::new("list the files"))],
102 ))
103 .block_task()
104 .await?;
105 Ok(reply.stop_reason)
106 })
107 .await
108 .expect("turn");
109
110 assert_eq!(stop, StopReason::EndTurn);
111 assert!(*stats.saw_bearer.lock().unwrap(), "the key is the bearer");
112 let payloads = stats.payloads.lock().unwrap();
113 assert_eq!(payloads.len(), 2, "tool call, then the answer");
114 assert_eq!(payloads[0]["model"], DEFAULT_MODEL);
115 let names: Vec<_> = payloads[0]["tools"]
116 .as_array()
117 .unwrap()
118 .iter()
119 .map(|t| t["function"]["name"].as_str().unwrap().to_string())
120 .collect();
121 assert!(names.contains(&"edit_file".to_string()));
122 assert!(!names.contains(&"run_command".to_string()), "no shell");
123 }