207
assert_eq!(fake.authenticated.load(Ordering::SeqCst), 1);
208
}
209
}
210
+
211
+mod model_list {
212
+ use std::sync::{Arc, Mutex};
213
+
214
+ use agent_client_protocol::schema::ProtocolVersion;
215
+ use agent_client_protocol::schema::v1::{InitializeRequest, NewSessionRequest};
216
+ use agent_client_protocol::{Agent, Channel, Client, ConnectionTo};
217
+ use async_trait::async_trait;
218
+ use ed_acp::{
219
+ AgentInfo, AuthCtx, AuthProvider, LlmConfig, LlmEnv, Profile, PromptCtx, Provider,
220
+ ServeOptions, Toolset,
221
+ };
222
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
223
+
224
+ /// Serves `GET /models` with whatever ids are in `models` at the time of the request.
225
+ async fn models_endpoint(models: Arc<Mutex<Vec<&'static str>>>) -> String {
226
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
227
+ let base = format!("http://{}", listener.local_addr().unwrap());
228
+ tokio::spawn(async move {
229
+ loop {
230
+ let Ok((mut socket, _)) = listener.accept().await else {
231
+ return;
232
+ };
233
+ let models = models.clone();
234
+ tokio::spawn(async move {
235
+ let mut buf = [0u8; 2048];
236
+ let _ = socket.read(&mut buf).await;
237
+ let data: Vec<_> = models
238
+ .lock()
239
+ .unwrap()
240
+ .iter()
241
+ .map(|id| serde_json::json!({"id": id}))
242
+ .collect();
243
+ let body = serde_json::json!({"object": "list", "data": data}).to_string();
244
+ let reply = format!(
245
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
246
+ body.len()
247
+ );
248
+ let _ = socket.write_all(reply.as_bytes()).await;
249
+ });
250
+ }
251
+ });
252
+ base
253
+ }
254
+
255
+ struct Signed(String);
256
+
257
+ #[async_trait]
258
+ impl AuthProvider for Signed {
259
+ fn method(&self) -> agent_client_protocol::schema::v1::AuthMethod {
260
+ agent_client_protocol::schema::v1::AuthMethod::Agent(
261
+ agent_client_protocol::schema::v1::AuthMethodAgent::new("fake", "Sign in"),
262
+ )
263
+ }
264
+
265
+ fn llm_config(&self) -> Option<LlmConfig> {
266
+ Some(LlmConfig {
267
+ provider: Provider::OpenAi,
268
+ base_url: self.0.clone(),
269
+ api_key: Some("token".into()),
270
+ model: "tier-a".into(),
271
+ })
272
+ }
273
+
274
+ async fn authenticate(&self, _ctx: AuthCtx<'_>) -> agent_client_protocol::Result<()> {
275
+ Ok(())
276
+ }
277
+
278
+ async fn logout(&self) -> anyhow::Result<()> {
279
+ Ok(())
280
+ }
281
+ }
282
+
283
+ struct Agentless(String);
284
+
285
+ impl Profile for Agentless {
286
+ fn info(&self) -> AgentInfo {
287
+ AgentInfo {
288
+ name: "model-list-agent",
289
+ display_name: "Model list",
290
+ version: "0.0.1",
291
+ env: LlmEnv {
292
+ prefix: "ED_ACP_MODEL_LIST_TEST",
293
+ dir_name: "ed-acp-model-list-test",
294
+ default_model: "tier-a",
295
+ },
296
+ }
297
+ }
298
+
299
+ fn system_prompt(&self, _ctx: &PromptCtx<'_>) -> String {
300
+ String::new()
301
+ }
302
+
303
+ fn toolsets(&self) -> Vec<Arc<dyn Toolset>> {
304
+ Vec::new()
305
+ }
306
+
307
+ fn auth(&self) -> Option<Arc<dyn AuthProvider>> {
308
+ Some(Arc::new(Signed(self.0.clone())))
309
+ }
310
+ }
311
+
312
+ fn offered(response: &impl serde::Serialize) -> Vec<String> {
313
+ let json = serde_json::to_value(response).unwrap();
314
+ json["configOptions"][0]["options"]
315
+ .as_array()
316
+ .expect("a model option")
317
+ .iter()
318
+ .map(|o| o["value"].as_str().unwrap().to_string())
319
+ .collect()
320
+ }
321
+
322
+ #[tokio::test]
323
+ async fn a_new_thread_lists_models_again() {
324
+ let models = Arc::new(Mutex::new(vec!["tier-a"]));
325
+ let base = models_endpoint(models.clone()).await;
326
+ let (agent_end, client_end) = Channel::duplex();
327
+ let opts = ServeOptions {
328
+ yolo: false,
329
+ surface: "app",
330
+ };
331
+ tokio::spawn(ed_acp::serve(Arc::new(Agentless(base)), opts, agent_end));
332
+ let cwd = std::env::temp_dir();
333
+
334
+ Client
335
+ .builder()
336
+ .connect_with(client_end, |conn: ConnectionTo<Agent>| async move {
337
+ conn.send_request(InitializeRequest::new(ProtocolVersion::V1))
338
+ .block_task()
339
+ .await?;
340
+ conn.send_request(agent_client_protocol::schema::v1::AuthenticateRequest::new(
341
+ "fake",
342
+ ))
343
+ .block_task()
344
+ .await?;
345
+
346
+ let first = conn
347
+ .send_request(NewSessionRequest::new(cwd.clone()))
348
+ .block_task()
349
+ .await?;
350
+ assert_eq!(offered(&first), ["tier-a"]);
351
+
352
+ // The endpoint's list changes, as it does when a tier is enabled in the console.
353
+ *models.lock().unwrap() = vec!["tier-a", "tier-b"];
354
+ let second = conn
355
+ .send_request(NewSessionRequest::new(cwd.clone()))
356
+ .block_task()
357
+ .await?;
358
+ assert_eq!(offered(&second), ["tier-a", "tier-b"]);
359
+ Ok(())
360
+ })
361
+ .await
362
+ .expect("conversation");
363
+ }
364
+}