mod.rs

   1use super::*;
   2use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelList, UserMessageId};
   3use agent_client_protocol::{self as acp};
   4use agent_settings::AgentProfileId;
   5use anyhow::Result;
   6use client::{Client, UserStore};
   7use cloud_llm_client::CompletionIntent;
   8use collections::IndexMap;
   9use context_server::{ContextServer, ContextServerCommand, ContextServerId};
  10use fs::{FakeFs, Fs};
  11use futures::{
  12    StreamExt,
  13    channel::{
  14        mpsc::{self, UnboundedReceiver},
  15        oneshot,
  16    },
  17};
  18use gpui::{
  19    App, AppContext, Entity, Task, TestAppContext, UpdateGlobal, http_client::FakeHttpClient,
  20};
  21use indoc::indoc;
  22use language_model::{
  23    LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
  24    LanguageModelProviderName, LanguageModelRegistry, LanguageModelRequest,
  25    LanguageModelRequestMessage, LanguageModelToolResult, LanguageModelToolSchemaFormat,
  26    LanguageModelToolUse, MessageContent, Role, StopReason, fake_provider::FakeLanguageModel,
  27};
  28use pretty_assertions::assert_eq;
  29use project::{
  30    Project, context_server_store::ContextServerStore, project_settings::ProjectSettings,
  31};
  32use prompt_store::ProjectContext;
  33use reqwest_client::ReqwestClient;
  34use schemars::JsonSchema;
  35use serde::{Deserialize, Serialize};
  36use serde_json::json;
  37use settings::{Settings, SettingsStore};
  38use std::{path::Path, rc::Rc, sync::Arc, time::Duration};
  39use util::path;
  40
  41mod test_tools;
  42use test_tools::*;
  43
  44#[gpui::test]
  45async fn test_echo(cx: &mut TestAppContext) {
  46    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
  47    let fake_model = model.as_fake();
  48
  49    let events = thread
  50        .update(cx, |thread, cx| {
  51            thread.send(UserMessageId::new(), ["Testing: Reply with 'Hello'"], cx)
  52        })
  53        .unwrap();
  54    cx.run_until_parked();
  55    fake_model.send_last_completion_stream_text_chunk("Hello");
  56    fake_model
  57        .send_last_completion_stream_event(LanguageModelCompletionEvent::Stop(StopReason::EndTurn));
  58    fake_model.end_last_completion_stream();
  59
  60    let events = events.collect().await;
  61    thread.update(cx, |thread, _cx| {
  62        assert_eq!(
  63            thread.last_message().unwrap().to_markdown(),
  64            indoc! {"
  65                ## Assistant
  66
  67                Hello
  68            "}
  69        )
  70    });
  71    assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
  72}
  73
  74#[gpui::test]
  75async fn test_thinking(cx: &mut TestAppContext) {
  76    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
  77    let fake_model = model.as_fake();
  78
  79    let events = thread
  80        .update(cx, |thread, cx| {
  81            thread.send(
  82                UserMessageId::new(),
  83                [indoc! {"
  84                    Testing:
  85
  86                    Generate a thinking step where you just think the word 'Think',
  87                    and have your final answer be 'Hello'
  88                "}],
  89                cx,
  90            )
  91        })
  92        .unwrap();
  93    cx.run_until_parked();
  94    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::Thinking {
  95        text: "Think".to_string(),
  96        signature: None,
  97    });
  98    fake_model.send_last_completion_stream_text_chunk("Hello");
  99    fake_model
 100        .send_last_completion_stream_event(LanguageModelCompletionEvent::Stop(StopReason::EndTurn));
 101    fake_model.end_last_completion_stream();
 102
 103    let events = events.collect().await;
 104    thread.update(cx, |thread, _cx| {
 105        assert_eq!(
 106            thread.last_message().unwrap().to_markdown(),
 107            indoc! {"
 108                ## Assistant
 109
 110                <think>Think</think>
 111                Hello
 112            "}
 113        )
 114    });
 115    assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
 116}
 117
 118#[gpui::test]
 119async fn test_system_prompt(cx: &mut TestAppContext) {
 120    let ThreadTest {
 121        model,
 122        thread,
 123        project_context,
 124        ..
 125    } = setup(cx, TestModel::Fake).await;
 126    let fake_model = model.as_fake();
 127
 128    project_context.update(cx, |project_context, _cx| {
 129        project_context.shell = "test-shell".into()
 130    });
 131    thread.update(cx, |thread, _| thread.add_tool(EchoTool));
 132    thread
 133        .update(cx, |thread, cx| {
 134            thread.send(UserMessageId::new(), ["abc"], cx)
 135        })
 136        .unwrap();
 137    cx.run_until_parked();
 138    let mut pending_completions = fake_model.pending_completions();
 139    assert_eq!(
 140        pending_completions.len(),
 141        1,
 142        "unexpected pending completions: {:?}",
 143        pending_completions
 144    );
 145
 146    let pending_completion = pending_completions.pop().unwrap();
 147    assert_eq!(pending_completion.messages[0].role, Role::System);
 148
 149    let system_message = &pending_completion.messages[0];
 150    let system_prompt = system_message.content[0].to_str().unwrap();
 151    assert!(
 152        system_prompt.contains("test-shell"),
 153        "unexpected system message: {:?}",
 154        system_message
 155    );
 156    assert!(
 157        system_prompt.contains("## Fixing Diagnostics"),
 158        "unexpected system message: {:?}",
 159        system_message
 160    );
 161}
 162
 163#[gpui::test]
 164async fn test_prompt_caching(cx: &mut TestAppContext) {
 165    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
 166    let fake_model = model.as_fake();
 167
 168    // Send initial user message and verify it's cached
 169    thread
 170        .update(cx, |thread, cx| {
 171            thread.send(UserMessageId::new(), ["Message 1"], cx)
 172        })
 173        .unwrap();
 174    cx.run_until_parked();
 175
 176    let completion = fake_model.pending_completions().pop().unwrap();
 177    assert_eq!(
 178        completion.messages[1..],
 179        vec![LanguageModelRequestMessage {
 180            role: Role::User,
 181            content: vec!["Message 1".into()],
 182            cache: true
 183        }]
 184    );
 185    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::Text(
 186        "Response to Message 1".into(),
 187    ));
 188    fake_model.end_last_completion_stream();
 189    cx.run_until_parked();
 190
 191    // Send another user message and verify only the latest is cached
 192    thread
 193        .update(cx, |thread, cx| {
 194            thread.send(UserMessageId::new(), ["Message 2"], cx)
 195        })
 196        .unwrap();
 197    cx.run_until_parked();
 198
 199    let completion = fake_model.pending_completions().pop().unwrap();
 200    assert_eq!(
 201        completion.messages[1..],
 202        vec![
 203            LanguageModelRequestMessage {
 204                role: Role::User,
 205                content: vec!["Message 1".into()],
 206                cache: false
 207            },
 208            LanguageModelRequestMessage {
 209                role: Role::Assistant,
 210                content: vec!["Response to Message 1".into()],
 211                cache: false
 212            },
 213            LanguageModelRequestMessage {
 214                role: Role::User,
 215                content: vec!["Message 2".into()],
 216                cache: true
 217            }
 218        ]
 219    );
 220    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::Text(
 221        "Response to Message 2".into(),
 222    ));
 223    fake_model.end_last_completion_stream();
 224    cx.run_until_parked();
 225
 226    // Simulate a tool call and verify that the latest tool result is cached
 227    thread.update(cx, |thread, _| thread.add_tool(EchoTool));
 228    thread
 229        .update(cx, |thread, cx| {
 230            thread.send(UserMessageId::new(), ["Use the echo tool"], cx)
 231        })
 232        .unwrap();
 233    cx.run_until_parked();
 234
 235    let tool_use = LanguageModelToolUse {
 236        id: "tool_1".into(),
 237        name: EchoTool::name().into(),
 238        raw_input: json!({"text": "test"}).to_string(),
 239        input: json!({"text": "test"}),
 240        is_input_complete: true,
 241    };
 242    fake_model
 243        .send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(tool_use.clone()));
 244    fake_model.end_last_completion_stream();
 245    cx.run_until_parked();
 246
 247    let completion = fake_model.pending_completions().pop().unwrap();
 248    let tool_result = LanguageModelToolResult {
 249        tool_use_id: "tool_1".into(),
 250        tool_name: EchoTool::name().into(),
 251        is_error: false,
 252        content: "test".into(),
 253        output: Some("test".into()),
 254    };
 255    assert_eq!(
 256        completion.messages[1..],
 257        vec![
 258            LanguageModelRequestMessage {
 259                role: Role::User,
 260                content: vec!["Message 1".into()],
 261                cache: false
 262            },
 263            LanguageModelRequestMessage {
 264                role: Role::Assistant,
 265                content: vec!["Response to Message 1".into()],
 266                cache: false
 267            },
 268            LanguageModelRequestMessage {
 269                role: Role::User,
 270                content: vec!["Message 2".into()],
 271                cache: false
 272            },
 273            LanguageModelRequestMessage {
 274                role: Role::Assistant,
 275                content: vec!["Response to Message 2".into()],
 276                cache: false
 277            },
 278            LanguageModelRequestMessage {
 279                role: Role::User,
 280                content: vec!["Use the echo tool".into()],
 281                cache: false
 282            },
 283            LanguageModelRequestMessage {
 284                role: Role::Assistant,
 285                content: vec![MessageContent::ToolUse(tool_use)],
 286                cache: false
 287            },
 288            LanguageModelRequestMessage {
 289                role: Role::User,
 290                content: vec![MessageContent::ToolResult(tool_result)],
 291                cache: true
 292            }
 293        ]
 294    );
 295}
 296
 297#[gpui::test]
 298#[cfg_attr(not(feature = "e2e"), ignore)]
 299async fn test_basic_tool_calls(cx: &mut TestAppContext) {
 300    let ThreadTest { thread, .. } = setup(cx, TestModel::Sonnet4).await;
 301
 302    // Test a tool call that's likely to complete *before* streaming stops.
 303    let events = thread
 304        .update(cx, |thread, cx| {
 305            thread.add_tool(EchoTool);
 306            thread.send(
 307                UserMessageId::new(),
 308                ["Now test the echo tool with 'Hello'. Does it work? Say 'Yes' or 'No'."],
 309                cx,
 310            )
 311        })
 312        .unwrap()
 313        .collect()
 314        .await;
 315    assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
 316
 317    // Test a tool calls that's likely to complete *after* streaming stops.
 318    let events = thread
 319        .update(cx, |thread, cx| {
 320            thread.remove_tool(&EchoTool::name());
 321            thread.add_tool(DelayTool);
 322            thread.send(
 323                UserMessageId::new(),
 324                [
 325                    "Now call the delay tool with 200ms.",
 326                    "When the timer goes off, then you echo the output of the tool.",
 327                ],
 328                cx,
 329            )
 330        })
 331        .unwrap()
 332        .collect()
 333        .await;
 334    assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
 335    thread.update(cx, |thread, _cx| {
 336        assert!(
 337            thread
 338                .last_message()
 339                .unwrap()
 340                .as_agent_message()
 341                .unwrap()
 342                .content
 343                .iter()
 344                .any(|content| {
 345                    if let AgentMessageContent::Text(text) = content {
 346                        text.contains("Ding")
 347                    } else {
 348                        false
 349                    }
 350                }),
 351            "{}",
 352            thread.to_markdown()
 353        );
 354    });
 355}
 356
 357#[gpui::test]
 358#[cfg_attr(not(feature = "e2e"), ignore)]
 359async fn test_streaming_tool_calls(cx: &mut TestAppContext) {
 360    let ThreadTest { thread, .. } = setup(cx, TestModel::Sonnet4).await;
 361
 362    // Test a tool call that's likely to complete *before* streaming stops.
 363    let mut events = thread
 364        .update(cx, |thread, cx| {
 365            thread.add_tool(WordListTool);
 366            thread.send(UserMessageId::new(), ["Test the word_list tool."], cx)
 367        })
 368        .unwrap();
 369
 370    let mut saw_partial_tool_use = false;
 371    while let Some(event) = events.next().await {
 372        if let Ok(ThreadEvent::ToolCall(tool_call)) = event {
 373            thread.update(cx, |thread, _cx| {
 374                // Look for a tool use in the thread's last message
 375                let message = thread.last_message().unwrap();
 376                let agent_message = message.as_agent_message().unwrap();
 377                let last_content = agent_message.content.last().unwrap();
 378                if let AgentMessageContent::ToolUse(last_tool_use) = last_content {
 379                    assert_eq!(last_tool_use.name.as_ref(), "word_list");
 380                    if tool_call.status == acp::ToolCallStatus::Pending {
 381                        if !last_tool_use.is_input_complete
 382                            && last_tool_use.input.get("g").is_none()
 383                        {
 384                            saw_partial_tool_use = true;
 385                        }
 386                    } else {
 387                        last_tool_use
 388                            .input
 389                            .get("a")
 390                            .expect("'a' has streamed because input is now complete");
 391                        last_tool_use
 392                            .input
 393                            .get("g")
 394                            .expect("'g' has streamed because input is now complete");
 395                    }
 396                } else {
 397                    panic!("last content should be a tool use");
 398                }
 399            });
 400        }
 401    }
 402
 403    assert!(
 404        saw_partial_tool_use,
 405        "should see at least one partially streamed tool use in the history"
 406    );
 407}
 408
 409#[gpui::test]
 410async fn test_tool_authorization(cx: &mut TestAppContext) {
 411    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
 412    let fake_model = model.as_fake();
 413
 414    let mut events = thread
 415        .update(cx, |thread, cx| {
 416            thread.add_tool(ToolRequiringPermission);
 417            thread.send(UserMessageId::new(), ["abc"], cx)
 418        })
 419        .unwrap();
 420    cx.run_until_parked();
 421    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
 422        LanguageModelToolUse {
 423            id: "tool_id_1".into(),
 424            name: ToolRequiringPermission::name().into(),
 425            raw_input: "{}".into(),
 426            input: json!({}),
 427            is_input_complete: true,
 428        },
 429    ));
 430    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
 431        LanguageModelToolUse {
 432            id: "tool_id_2".into(),
 433            name: ToolRequiringPermission::name().into(),
 434            raw_input: "{}".into(),
 435            input: json!({}),
 436            is_input_complete: true,
 437        },
 438    ));
 439    fake_model.end_last_completion_stream();
 440    let tool_call_auth_1 = next_tool_call_authorization(&mut events).await;
 441    let tool_call_auth_2 = next_tool_call_authorization(&mut events).await;
 442
 443    // Approve the first
 444    tool_call_auth_1
 445        .response
 446        .send(tool_call_auth_1.options[1].id.clone())
 447        .unwrap();
 448    cx.run_until_parked();
 449
 450    // Reject the second
 451    tool_call_auth_2
 452        .response
 453        .send(tool_call_auth_1.options[2].id.clone())
 454        .unwrap();
 455    cx.run_until_parked();
 456
 457    let completion = fake_model.pending_completions().pop().unwrap();
 458    let message = completion.messages.last().unwrap();
 459    assert_eq!(
 460        message.content,
 461        vec![
 462            language_model::MessageContent::ToolResult(LanguageModelToolResult {
 463                tool_use_id: tool_call_auth_1.tool_call.id.0.to_string().into(),
 464                tool_name: ToolRequiringPermission::name().into(),
 465                is_error: false,
 466                content: "Allowed".into(),
 467                output: Some("Allowed".into())
 468            }),
 469            language_model::MessageContent::ToolResult(LanguageModelToolResult {
 470                tool_use_id: tool_call_auth_2.tool_call.id.0.to_string().into(),
 471                tool_name: ToolRequiringPermission::name().into(),
 472                is_error: true,
 473                content: "Permission to run tool denied by user".into(),
 474                output: None
 475            })
 476        ]
 477    );
 478
 479    // Simulate yet another tool call.
 480    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
 481        LanguageModelToolUse {
 482            id: "tool_id_3".into(),
 483            name: ToolRequiringPermission::name().into(),
 484            raw_input: "{}".into(),
 485            input: json!({}),
 486            is_input_complete: true,
 487        },
 488    ));
 489    fake_model.end_last_completion_stream();
 490
 491    // Respond by always allowing tools.
 492    let tool_call_auth_3 = next_tool_call_authorization(&mut events).await;
 493    tool_call_auth_3
 494        .response
 495        .send(tool_call_auth_3.options[0].id.clone())
 496        .unwrap();
 497    cx.run_until_parked();
 498    let completion = fake_model.pending_completions().pop().unwrap();
 499    let message = completion.messages.last().unwrap();
 500    assert_eq!(
 501        message.content,
 502        vec![language_model::MessageContent::ToolResult(
 503            LanguageModelToolResult {
 504                tool_use_id: tool_call_auth_3.tool_call.id.0.to_string().into(),
 505                tool_name: ToolRequiringPermission::name().into(),
 506                is_error: false,
 507                content: "Allowed".into(),
 508                output: Some("Allowed".into())
 509            }
 510        )]
 511    );
 512
 513    // Simulate a final tool call, ensuring we don't trigger authorization.
 514    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
 515        LanguageModelToolUse {
 516            id: "tool_id_4".into(),
 517            name: ToolRequiringPermission::name().into(),
 518            raw_input: "{}".into(),
 519            input: json!({}),
 520            is_input_complete: true,
 521        },
 522    ));
 523    fake_model.end_last_completion_stream();
 524    cx.run_until_parked();
 525    let completion = fake_model.pending_completions().pop().unwrap();
 526    let message = completion.messages.last().unwrap();
 527    assert_eq!(
 528        message.content,
 529        vec![language_model::MessageContent::ToolResult(
 530            LanguageModelToolResult {
 531                tool_use_id: "tool_id_4".into(),
 532                tool_name: ToolRequiringPermission::name().into(),
 533                is_error: false,
 534                content: "Allowed".into(),
 535                output: Some("Allowed".into())
 536            }
 537        )]
 538    );
 539}
 540
 541#[gpui::test]
 542async fn test_tool_hallucination(cx: &mut TestAppContext) {
 543    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
 544    let fake_model = model.as_fake();
 545
 546    let mut events = thread
 547        .update(cx, |thread, cx| {
 548            thread.send(UserMessageId::new(), ["abc"], cx)
 549        })
 550        .unwrap();
 551    cx.run_until_parked();
 552    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
 553        LanguageModelToolUse {
 554            id: "tool_id_1".into(),
 555            name: "nonexistent_tool".into(),
 556            raw_input: "{}".into(),
 557            input: json!({}),
 558            is_input_complete: true,
 559        },
 560    ));
 561    fake_model.end_last_completion_stream();
 562
 563    let tool_call = expect_tool_call(&mut events).await;
 564    assert_eq!(tool_call.title, "nonexistent_tool");
 565    assert_eq!(tool_call.status, acp::ToolCallStatus::Pending);
 566    let update = expect_tool_call_update_fields(&mut events).await;
 567    assert_eq!(update.fields.status, Some(acp::ToolCallStatus::Failed));
 568}
 569
 570#[gpui::test]
 571async fn test_resume_after_tool_use_limit(cx: &mut TestAppContext) {
 572    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
 573    let fake_model = model.as_fake();
 574
 575    let events = thread
 576        .update(cx, |thread, cx| {
 577            thread.add_tool(EchoTool);
 578            thread.send(UserMessageId::new(), ["abc"], cx)
 579        })
 580        .unwrap();
 581    cx.run_until_parked();
 582    let tool_use = LanguageModelToolUse {
 583        id: "tool_id_1".into(),
 584        name: EchoTool::name().into(),
 585        raw_input: "{}".into(),
 586        input: serde_json::to_value(&EchoToolInput { text: "def".into() }).unwrap(),
 587        is_input_complete: true,
 588    };
 589    fake_model
 590        .send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(tool_use.clone()));
 591    fake_model.end_last_completion_stream();
 592
 593    cx.run_until_parked();
 594    let completion = fake_model.pending_completions().pop().unwrap();
 595    let tool_result = LanguageModelToolResult {
 596        tool_use_id: "tool_id_1".into(),
 597        tool_name: EchoTool::name().into(),
 598        is_error: false,
 599        content: "def".into(),
 600        output: Some("def".into()),
 601    };
 602    assert_eq!(
 603        completion.messages[1..],
 604        vec![
 605            LanguageModelRequestMessage {
 606                role: Role::User,
 607                content: vec!["abc".into()],
 608                cache: false
 609            },
 610            LanguageModelRequestMessage {
 611                role: Role::Assistant,
 612                content: vec![MessageContent::ToolUse(tool_use.clone())],
 613                cache: false
 614            },
 615            LanguageModelRequestMessage {
 616                role: Role::User,
 617                content: vec![MessageContent::ToolResult(tool_result.clone())],
 618                cache: true
 619            },
 620        ]
 621    );
 622
 623    // Simulate reaching tool use limit.
 624    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::StatusUpdate(
 625        cloud_llm_client::CompletionRequestStatus::ToolUseLimitReached,
 626    ));
 627    fake_model.end_last_completion_stream();
 628    let last_event = events.collect::<Vec<_>>().await.pop().unwrap();
 629    assert!(
 630        last_event
 631            .unwrap_err()
 632            .is::<language_model::ToolUseLimitReachedError>()
 633    );
 634
 635    let events = thread.update(cx, |thread, cx| thread.resume(cx)).unwrap();
 636    cx.run_until_parked();
 637    let completion = fake_model.pending_completions().pop().unwrap();
 638    assert_eq!(
 639        completion.messages[1..],
 640        vec![
 641            LanguageModelRequestMessage {
 642                role: Role::User,
 643                content: vec!["abc".into()],
 644                cache: false
 645            },
 646            LanguageModelRequestMessage {
 647                role: Role::Assistant,
 648                content: vec![MessageContent::ToolUse(tool_use)],
 649                cache: false
 650            },
 651            LanguageModelRequestMessage {
 652                role: Role::User,
 653                content: vec![MessageContent::ToolResult(tool_result)],
 654                cache: false
 655            },
 656            LanguageModelRequestMessage {
 657                role: Role::User,
 658                content: vec!["Continue where you left off".into()],
 659                cache: true
 660            }
 661        ]
 662    );
 663
 664    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::Text("Done".into()));
 665    fake_model.end_last_completion_stream();
 666    events.collect::<Vec<_>>().await;
 667    thread.read_with(cx, |thread, _cx| {
 668        assert_eq!(
 669            thread.last_message().unwrap().to_markdown(),
 670            indoc! {"
 671                ## Assistant
 672
 673                Done
 674            "}
 675        )
 676    });
 677}
 678
 679#[gpui::test]
 680async fn test_send_after_tool_use_limit(cx: &mut TestAppContext) {
 681    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
 682    let fake_model = model.as_fake();
 683
 684    let events = thread
 685        .update(cx, |thread, cx| {
 686            thread.add_tool(EchoTool);
 687            thread.send(UserMessageId::new(), ["abc"], cx)
 688        })
 689        .unwrap();
 690    cx.run_until_parked();
 691
 692    let tool_use = LanguageModelToolUse {
 693        id: "tool_id_1".into(),
 694        name: EchoTool::name().into(),
 695        raw_input: "{}".into(),
 696        input: serde_json::to_value(&EchoToolInput { text: "def".into() }).unwrap(),
 697        is_input_complete: true,
 698    };
 699    let tool_result = LanguageModelToolResult {
 700        tool_use_id: "tool_id_1".into(),
 701        tool_name: EchoTool::name().into(),
 702        is_error: false,
 703        content: "def".into(),
 704        output: Some("def".into()),
 705    };
 706    fake_model
 707        .send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(tool_use.clone()));
 708    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::StatusUpdate(
 709        cloud_llm_client::CompletionRequestStatus::ToolUseLimitReached,
 710    ));
 711    fake_model.end_last_completion_stream();
 712    let last_event = events.collect::<Vec<_>>().await.pop().unwrap();
 713    assert!(
 714        last_event
 715            .unwrap_err()
 716            .is::<language_model::ToolUseLimitReachedError>()
 717    );
 718
 719    thread
 720        .update(cx, |thread, cx| {
 721            thread.send(UserMessageId::new(), vec!["ghi"], cx)
 722        })
 723        .unwrap();
 724    cx.run_until_parked();
 725    let completion = fake_model.pending_completions().pop().unwrap();
 726    assert_eq!(
 727        completion.messages[1..],
 728        vec![
 729            LanguageModelRequestMessage {
 730                role: Role::User,
 731                content: vec!["abc".into()],
 732                cache: false
 733            },
 734            LanguageModelRequestMessage {
 735                role: Role::Assistant,
 736                content: vec![MessageContent::ToolUse(tool_use)],
 737                cache: false
 738            },
 739            LanguageModelRequestMessage {
 740                role: Role::User,
 741                content: vec![MessageContent::ToolResult(tool_result)],
 742                cache: false
 743            },
 744            LanguageModelRequestMessage {
 745                role: Role::User,
 746                content: vec!["ghi".into()],
 747                cache: true
 748            }
 749        ]
 750    );
 751}
 752
 753async fn expect_tool_call(events: &mut UnboundedReceiver<Result<ThreadEvent>>) -> acp::ToolCall {
 754    let event = events
 755        .next()
 756        .await
 757        .expect("no tool call authorization event received")
 758        .unwrap();
 759    match event {
 760        ThreadEvent::ToolCall(tool_call) => tool_call,
 761        event => {
 762            panic!("Unexpected event {event:?}");
 763        }
 764    }
 765}
 766
 767async fn expect_tool_call_update_fields(
 768    events: &mut UnboundedReceiver<Result<ThreadEvent>>,
 769) -> acp::ToolCallUpdate {
 770    let event = events
 771        .next()
 772        .await
 773        .expect("no tool call authorization event received")
 774        .unwrap();
 775    match event {
 776        ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) => update,
 777        event => {
 778            panic!("Unexpected event {event:?}");
 779        }
 780    }
 781}
 782
 783async fn next_tool_call_authorization(
 784    events: &mut UnboundedReceiver<Result<ThreadEvent>>,
 785) -> ToolCallAuthorization {
 786    loop {
 787        let event = events
 788            .next()
 789            .await
 790            .expect("no tool call authorization event received")
 791            .unwrap();
 792        if let ThreadEvent::ToolCallAuthorization(tool_call_authorization) = event {
 793            let permission_kinds = tool_call_authorization
 794                .options
 795                .iter()
 796                .map(|o| o.kind)
 797                .collect::<Vec<_>>();
 798            assert_eq!(
 799                permission_kinds,
 800                vec![
 801                    acp::PermissionOptionKind::AllowAlways,
 802                    acp::PermissionOptionKind::AllowOnce,
 803                    acp::PermissionOptionKind::RejectOnce,
 804                ]
 805            );
 806            return tool_call_authorization;
 807        }
 808    }
 809}
 810
 811#[gpui::test]
 812#[cfg_attr(not(feature = "e2e"), ignore)]
 813async fn test_concurrent_tool_calls(cx: &mut TestAppContext) {
 814    let ThreadTest { thread, .. } = setup(cx, TestModel::Sonnet4).await;
 815
 816    // Test concurrent tool calls with different delay times
 817    let events = thread
 818        .update(cx, |thread, cx| {
 819            thread.add_tool(DelayTool);
 820            thread.send(
 821                UserMessageId::new(),
 822                [
 823                    "Call the delay tool twice in the same message.",
 824                    "Once with 100ms. Once with 300ms.",
 825                    "When both timers are complete, describe the outputs.",
 826                ],
 827                cx,
 828            )
 829        })
 830        .unwrap()
 831        .collect()
 832        .await;
 833
 834    let stop_reasons = stop_events(events);
 835    assert_eq!(stop_reasons, vec![acp::StopReason::EndTurn]);
 836
 837    thread.update(cx, |thread, _cx| {
 838        let last_message = thread.last_message().unwrap();
 839        let agent_message = last_message.as_agent_message().unwrap();
 840        let text = agent_message
 841            .content
 842            .iter()
 843            .filter_map(|content| {
 844                if let AgentMessageContent::Text(text) = content {
 845                    Some(text.as_str())
 846                } else {
 847                    None
 848                }
 849            })
 850            .collect::<String>();
 851
 852        assert!(text.contains("Ding"));
 853    });
 854}
 855
 856#[gpui::test]
 857async fn test_profiles(cx: &mut TestAppContext) {
 858    let ThreadTest {
 859        model, thread, fs, ..
 860    } = setup(cx, TestModel::Fake).await;
 861    let fake_model = model.as_fake();
 862
 863    thread.update(cx, |thread, _cx| {
 864        thread.add_tool(DelayTool);
 865        thread.add_tool(EchoTool);
 866        thread.add_tool(InfiniteTool);
 867    });
 868
 869    // Override profiles and wait for settings to be loaded.
 870    fs.insert_file(
 871        paths::settings_file(),
 872        json!({
 873            "agent": {
 874                "profiles": {
 875                    "test-1": {
 876                        "name": "Test Profile 1",
 877                        "tools": {
 878                            EchoTool::name(): true,
 879                            DelayTool::name(): true,
 880                        }
 881                    },
 882                    "test-2": {
 883                        "name": "Test Profile 2",
 884                        "tools": {
 885                            InfiniteTool::name(): true,
 886                        }
 887                    }
 888                }
 889            }
 890        })
 891        .to_string()
 892        .into_bytes(),
 893    )
 894    .await;
 895    cx.run_until_parked();
 896
 897    // Test that test-1 profile (default) has echo and delay tools
 898    thread
 899        .update(cx, |thread, cx| {
 900            thread.set_profile(AgentProfileId("test-1".into()));
 901            thread.send(UserMessageId::new(), ["test"], cx)
 902        })
 903        .unwrap();
 904    cx.run_until_parked();
 905
 906    let mut pending_completions = fake_model.pending_completions();
 907    assert_eq!(pending_completions.len(), 1);
 908    let completion = pending_completions.pop().unwrap();
 909    let tool_names: Vec<String> = completion
 910        .tools
 911        .iter()
 912        .map(|tool| tool.name.clone())
 913        .collect();
 914    assert_eq!(tool_names, vec![DelayTool::name(), EchoTool::name()]);
 915    fake_model.end_last_completion_stream();
 916
 917    // Switch to test-2 profile, and verify that it has only the infinite tool.
 918    thread
 919        .update(cx, |thread, cx| {
 920            thread.set_profile(AgentProfileId("test-2".into()));
 921            thread.send(UserMessageId::new(), ["test2"], cx)
 922        })
 923        .unwrap();
 924    cx.run_until_parked();
 925    let mut pending_completions = fake_model.pending_completions();
 926    assert_eq!(pending_completions.len(), 1);
 927    let completion = pending_completions.pop().unwrap();
 928    let tool_names: Vec<String> = completion
 929        .tools
 930        .iter()
 931        .map(|tool| tool.name.clone())
 932        .collect();
 933    assert_eq!(tool_names, vec![InfiniteTool::name()]);
 934}
 935
 936#[gpui::test]
 937async fn test_mcp_tools(cx: &mut TestAppContext) {
 938    let ThreadTest {
 939        model,
 940        thread,
 941        context_server_store,
 942        fs,
 943        ..
 944    } = setup(cx, TestModel::Fake).await;
 945    let fake_model = model.as_fake();
 946
 947    // Override profiles and wait for settings to be loaded.
 948    fs.insert_file(
 949        paths::settings_file(),
 950        json!({
 951            "agent": {
 952                "profiles": {
 953                    "test": {
 954                        "name": "Test Profile",
 955                        "enable_all_context_servers": true,
 956                        "tools": {
 957                            EchoTool::name(): true,
 958                        }
 959                    },
 960                }
 961            }
 962        })
 963        .to_string()
 964        .into_bytes(),
 965    )
 966    .await;
 967    cx.run_until_parked();
 968    thread.update(cx, |thread, _| {
 969        thread.set_profile(AgentProfileId("test".into()))
 970    });
 971
 972    let mut mcp_tool_calls = setup_context_server(
 973        "test_server",
 974        vec![context_server::types::Tool {
 975            name: "echo".into(),
 976            description: None,
 977            input_schema: serde_json::to_value(
 978                EchoTool.input_schema(LanguageModelToolSchemaFormat::JsonSchema),
 979            )
 980            .unwrap(),
 981            output_schema: None,
 982            annotations: None,
 983        }],
 984        &context_server_store,
 985        cx,
 986    );
 987
 988    let events = thread.update(cx, |thread, cx| {
 989        thread.send(UserMessageId::new(), ["Hey"], cx).unwrap()
 990    });
 991    cx.run_until_parked();
 992
 993    // Simulate the model calling the MCP tool.
 994    let completion = fake_model.pending_completions().pop().unwrap();
 995    assert_eq!(tool_names_for_completion(&completion), vec!["echo"]);
 996    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
 997        LanguageModelToolUse {
 998            id: "tool_1".into(),
 999            name: "echo".into(),
1000            raw_input: json!({"text": "test"}).to_string(),
1001            input: json!({"text": "test"}),
1002            is_input_complete: true,
1003        },
1004    ));
1005    fake_model.end_last_completion_stream();
1006    cx.run_until_parked();
1007
1008    let (tool_call_params, tool_call_response) = mcp_tool_calls.next().await.unwrap();
1009    assert_eq!(tool_call_params.name, "echo");
1010    assert_eq!(tool_call_params.arguments, Some(json!({"text": "test"})));
1011    tool_call_response
1012        .send(context_server::types::CallToolResponse {
1013            content: vec![context_server::types::ToolResponseContent::Text {
1014                text: "test".into(),
1015            }],
1016            is_error: None,
1017            meta: None,
1018            structured_content: None,
1019        })
1020        .unwrap();
1021    cx.run_until_parked();
1022
1023    assert_eq!(tool_names_for_completion(&completion), vec!["echo"]);
1024    fake_model.send_last_completion_stream_text_chunk("Done!");
1025    fake_model.end_last_completion_stream();
1026    events.collect::<Vec<_>>().await;
1027
1028    // Send again after adding the echo tool, ensuring the name collision is resolved.
1029    let events = thread.update(cx, |thread, cx| {
1030        thread.add_tool(EchoTool);
1031        thread.send(UserMessageId::new(), ["Go"], cx).unwrap()
1032    });
1033    cx.run_until_parked();
1034    let completion = fake_model.pending_completions().pop().unwrap();
1035    assert_eq!(
1036        tool_names_for_completion(&completion),
1037        vec!["echo", "test_server_echo"]
1038    );
1039    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
1040        LanguageModelToolUse {
1041            id: "tool_2".into(),
1042            name: "test_server_echo".into(),
1043            raw_input: json!({"text": "mcp"}).to_string(),
1044            input: json!({"text": "mcp"}),
1045            is_input_complete: true,
1046        },
1047    ));
1048    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
1049        LanguageModelToolUse {
1050            id: "tool_3".into(),
1051            name: "echo".into(),
1052            raw_input: json!({"text": "native"}).to_string(),
1053            input: json!({"text": "native"}),
1054            is_input_complete: true,
1055        },
1056    ));
1057    fake_model.end_last_completion_stream();
1058    cx.run_until_parked();
1059
1060    let (tool_call_params, tool_call_response) = mcp_tool_calls.next().await.unwrap();
1061    assert_eq!(tool_call_params.name, "echo");
1062    assert_eq!(tool_call_params.arguments, Some(json!({"text": "mcp"})));
1063    tool_call_response
1064        .send(context_server::types::CallToolResponse {
1065            content: vec![context_server::types::ToolResponseContent::Text { text: "mcp".into() }],
1066            is_error: None,
1067            meta: None,
1068            structured_content: None,
1069        })
1070        .unwrap();
1071    cx.run_until_parked();
1072
1073    // Ensure the tool results were inserted with the correct names.
1074    let completion = fake_model.pending_completions().pop().unwrap();
1075    assert_eq!(
1076        completion.messages.last().unwrap().content,
1077        vec![
1078            MessageContent::ToolResult(LanguageModelToolResult {
1079                tool_use_id: "tool_3".into(),
1080                tool_name: "echo".into(),
1081                is_error: false,
1082                content: "native".into(),
1083                output: Some("native".into()),
1084            },),
1085            MessageContent::ToolResult(LanguageModelToolResult {
1086                tool_use_id: "tool_2".into(),
1087                tool_name: "test_server_echo".into(),
1088                is_error: false,
1089                content: "mcp".into(),
1090                output: Some("mcp".into()),
1091            },),
1092        ]
1093    );
1094    fake_model.end_last_completion_stream();
1095    events.collect::<Vec<_>>().await;
1096}
1097
1098#[gpui::test]
1099async fn test_mcp_tool_truncation(cx: &mut TestAppContext) {
1100    let ThreadTest {
1101        model,
1102        thread,
1103        context_server_store,
1104        fs,
1105        ..
1106    } = setup(cx, TestModel::Fake).await;
1107    let fake_model = model.as_fake();
1108
1109    // Set up a profile with all tools enabled
1110    fs.insert_file(
1111        paths::settings_file(),
1112        json!({
1113            "agent": {
1114                "profiles": {
1115                    "test": {
1116                        "name": "Test Profile",
1117                        "enable_all_context_servers": true,
1118                        "tools": {
1119                            EchoTool::name(): true,
1120                            DelayTool::name(): true,
1121                            WordListTool::name(): true,
1122                            ToolRequiringPermission::name(): true,
1123                            InfiniteTool::name(): true,
1124                        }
1125                    },
1126                }
1127            }
1128        })
1129        .to_string()
1130        .into_bytes(),
1131    )
1132    .await;
1133    cx.run_until_parked();
1134
1135    thread.update(cx, |thread, _| {
1136        thread.set_profile(AgentProfileId("test".into()));
1137        thread.add_tool(EchoTool);
1138        thread.add_tool(DelayTool);
1139        thread.add_tool(WordListTool);
1140        thread.add_tool(ToolRequiringPermission);
1141        thread.add_tool(InfiniteTool);
1142    });
1143
1144    // Set up multiple context servers with some overlapping tool names
1145    let _server1_calls = setup_context_server(
1146        "xxx",
1147        vec![
1148            context_server::types::Tool {
1149                name: "echo".into(), // Conflicts with native EchoTool
1150                description: None,
1151                input_schema: serde_json::to_value(
1152                    EchoTool.input_schema(LanguageModelToolSchemaFormat::JsonSchema),
1153                )
1154                .unwrap(),
1155                output_schema: None,
1156                annotations: None,
1157            },
1158            context_server::types::Tool {
1159                name: "unique_tool_1".into(),
1160                description: None,
1161                input_schema: json!({"type": "object", "properties": {}}),
1162                output_schema: None,
1163                annotations: None,
1164            },
1165        ],
1166        &context_server_store,
1167        cx,
1168    );
1169
1170    let _server2_calls = setup_context_server(
1171        "yyy",
1172        vec![
1173            context_server::types::Tool {
1174                name: "echo".into(), // Also conflicts with native EchoTool
1175                description: None,
1176                input_schema: serde_json::to_value(
1177                    EchoTool.input_schema(LanguageModelToolSchemaFormat::JsonSchema),
1178                )
1179                .unwrap(),
1180                output_schema: None,
1181                annotations: None,
1182            },
1183            context_server::types::Tool {
1184                name: "unique_tool_2".into(),
1185                description: None,
1186                input_schema: json!({"type": "object", "properties": {}}),
1187                output_schema: None,
1188                annotations: None,
1189            },
1190            context_server::types::Tool {
1191                name: "a".repeat(MAX_TOOL_NAME_LENGTH - 2),
1192                description: None,
1193                input_schema: json!({"type": "object", "properties": {}}),
1194                output_schema: None,
1195                annotations: None,
1196            },
1197            context_server::types::Tool {
1198                name: "b".repeat(MAX_TOOL_NAME_LENGTH - 1),
1199                description: None,
1200                input_schema: json!({"type": "object", "properties": {}}),
1201                output_schema: None,
1202                annotations: None,
1203            },
1204        ],
1205        &context_server_store,
1206        cx,
1207    );
1208    let _server3_calls = setup_context_server(
1209        "zzz",
1210        vec![
1211            context_server::types::Tool {
1212                name: "a".repeat(MAX_TOOL_NAME_LENGTH - 2),
1213                description: None,
1214                input_schema: json!({"type": "object", "properties": {}}),
1215                output_schema: None,
1216                annotations: None,
1217            },
1218            context_server::types::Tool {
1219                name: "b".repeat(MAX_TOOL_NAME_LENGTH - 1),
1220                description: None,
1221                input_schema: json!({"type": "object", "properties": {}}),
1222                output_schema: None,
1223                annotations: None,
1224            },
1225            context_server::types::Tool {
1226                name: "c".repeat(MAX_TOOL_NAME_LENGTH + 1),
1227                description: None,
1228                input_schema: json!({"type": "object", "properties": {}}),
1229                output_schema: None,
1230                annotations: None,
1231            },
1232        ],
1233        &context_server_store,
1234        cx,
1235    );
1236
1237    thread
1238        .update(cx, |thread, cx| {
1239            thread.send(UserMessageId::new(), ["Go"], cx)
1240        })
1241        .unwrap();
1242    cx.run_until_parked();
1243    let completion = fake_model.pending_completions().pop().unwrap();
1244    assert_eq!(
1245        tool_names_for_completion(&completion),
1246        vec![
1247            "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
1248            "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
1249            "delay",
1250            "echo",
1251            "infinite",
1252            "tool_requiring_permission",
1253            "unique_tool_1",
1254            "unique_tool_2",
1255            "word_list",
1256            "xxx_echo",
1257            "y_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1258            "yyy_echo",
1259            "z_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1260        ]
1261    );
1262}
1263
1264#[gpui::test]
1265#[cfg_attr(not(feature = "e2e"), ignore)]
1266async fn test_cancellation(cx: &mut TestAppContext) {
1267    let ThreadTest { thread, .. } = setup(cx, TestModel::Sonnet4).await;
1268
1269    let mut events = thread
1270        .update(cx, |thread, cx| {
1271            thread.add_tool(InfiniteTool);
1272            thread.add_tool(EchoTool);
1273            thread.send(
1274                UserMessageId::new(),
1275                ["Call the echo tool, then call the infinite tool, then explain their output"],
1276                cx,
1277            )
1278        })
1279        .unwrap();
1280
1281    // Wait until both tools are called.
1282    let mut expected_tools = vec!["Echo", "Infinite Tool"];
1283    let mut echo_id = None;
1284    let mut echo_completed = false;
1285    while let Some(event) = events.next().await {
1286        match event.unwrap() {
1287            ThreadEvent::ToolCall(tool_call) => {
1288                assert_eq!(tool_call.title, expected_tools.remove(0));
1289                if tool_call.title == "Echo" {
1290                    echo_id = Some(tool_call.id);
1291                }
1292            }
1293            ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
1294                acp::ToolCallUpdate {
1295                    id,
1296                    fields:
1297                        acp::ToolCallUpdateFields {
1298                            status: Some(acp::ToolCallStatus::Completed),
1299                            ..
1300                        },
1301                },
1302            )) if Some(&id) == echo_id.as_ref() => {
1303                echo_completed = true;
1304            }
1305            _ => {}
1306        }
1307
1308        if expected_tools.is_empty() && echo_completed {
1309            break;
1310        }
1311    }
1312
1313    // Cancel the current send and ensure that the event stream is closed, even
1314    // if one of the tools is still running.
1315    thread.update(cx, |thread, cx| thread.cancel(cx));
1316    let events = events.collect::<Vec<_>>().await;
1317    let last_event = events.last();
1318    assert!(
1319        matches!(
1320            last_event,
1321            Some(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
1322        ),
1323        "unexpected event {last_event:?}"
1324    );
1325
1326    // Ensure we can still send a new message after cancellation.
1327    let events = thread
1328        .update(cx, |thread, cx| {
1329            thread.send(
1330                UserMessageId::new(),
1331                ["Testing: reply with 'Hello' then stop."],
1332                cx,
1333            )
1334        })
1335        .unwrap()
1336        .collect::<Vec<_>>()
1337        .await;
1338    thread.update(cx, |thread, _cx| {
1339        let message = thread.last_message().unwrap();
1340        let agent_message = message.as_agent_message().unwrap();
1341        assert_eq!(
1342            agent_message.content,
1343            vec![AgentMessageContent::Text("Hello".to_string())]
1344        );
1345    });
1346    assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
1347}
1348
1349#[gpui::test]
1350async fn test_in_progress_send_canceled_by_next_send(cx: &mut TestAppContext) {
1351    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1352    let fake_model = model.as_fake();
1353
1354    let events_1 = thread
1355        .update(cx, |thread, cx| {
1356            thread.send(UserMessageId::new(), ["Hello 1"], cx)
1357        })
1358        .unwrap();
1359    cx.run_until_parked();
1360    fake_model.send_last_completion_stream_text_chunk("Hey 1!");
1361    cx.run_until_parked();
1362
1363    let events_2 = thread
1364        .update(cx, |thread, cx| {
1365            thread.send(UserMessageId::new(), ["Hello 2"], cx)
1366        })
1367        .unwrap();
1368    cx.run_until_parked();
1369    fake_model.send_last_completion_stream_text_chunk("Hey 2!");
1370    fake_model
1371        .send_last_completion_stream_event(LanguageModelCompletionEvent::Stop(StopReason::EndTurn));
1372    fake_model.end_last_completion_stream();
1373
1374    let events_1 = events_1.collect::<Vec<_>>().await;
1375    assert_eq!(stop_events(events_1), vec![acp::StopReason::Cancelled]);
1376    let events_2 = events_2.collect::<Vec<_>>().await;
1377    assert_eq!(stop_events(events_2), vec![acp::StopReason::EndTurn]);
1378}
1379
1380#[gpui::test]
1381async fn test_subsequent_successful_sends_dont_cancel(cx: &mut TestAppContext) {
1382    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1383    let fake_model = model.as_fake();
1384
1385    let events_1 = thread
1386        .update(cx, |thread, cx| {
1387            thread.send(UserMessageId::new(), ["Hello 1"], cx)
1388        })
1389        .unwrap();
1390    cx.run_until_parked();
1391    fake_model.send_last_completion_stream_text_chunk("Hey 1!");
1392    fake_model
1393        .send_last_completion_stream_event(LanguageModelCompletionEvent::Stop(StopReason::EndTurn));
1394    fake_model.end_last_completion_stream();
1395    let events_1 = events_1.collect::<Vec<_>>().await;
1396
1397    let events_2 = thread
1398        .update(cx, |thread, cx| {
1399            thread.send(UserMessageId::new(), ["Hello 2"], cx)
1400        })
1401        .unwrap();
1402    cx.run_until_parked();
1403    fake_model.send_last_completion_stream_text_chunk("Hey 2!");
1404    fake_model
1405        .send_last_completion_stream_event(LanguageModelCompletionEvent::Stop(StopReason::EndTurn));
1406    fake_model.end_last_completion_stream();
1407    let events_2 = events_2.collect::<Vec<_>>().await;
1408
1409    assert_eq!(stop_events(events_1), vec![acp::StopReason::EndTurn]);
1410    assert_eq!(stop_events(events_2), vec![acp::StopReason::EndTurn]);
1411}
1412
1413#[gpui::test]
1414async fn test_refusal(cx: &mut TestAppContext) {
1415    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1416    let fake_model = model.as_fake();
1417
1418    let events = thread
1419        .update(cx, |thread, cx| {
1420            thread.send(UserMessageId::new(), ["Hello"], cx)
1421        })
1422        .unwrap();
1423    cx.run_until_parked();
1424    thread.read_with(cx, |thread, _| {
1425        assert_eq!(
1426            thread.to_markdown(),
1427            indoc! {"
1428                ## User
1429
1430                Hello
1431            "}
1432        );
1433    });
1434
1435    fake_model.send_last_completion_stream_text_chunk("Hey!");
1436    cx.run_until_parked();
1437    thread.read_with(cx, |thread, _| {
1438        assert_eq!(
1439            thread.to_markdown(),
1440            indoc! {"
1441                ## User
1442
1443                Hello
1444
1445                ## Assistant
1446
1447                Hey!
1448            "}
1449        );
1450    });
1451
1452    // If the model refuses to continue, the thread should remove all the messages after the last user message.
1453    fake_model
1454        .send_last_completion_stream_event(LanguageModelCompletionEvent::Stop(StopReason::Refusal));
1455    let events = events.collect::<Vec<_>>().await;
1456    assert_eq!(stop_events(events), vec![acp::StopReason::Refusal]);
1457    thread.read_with(cx, |thread, _| {
1458        assert_eq!(thread.to_markdown(), "");
1459    });
1460}
1461
1462#[gpui::test]
1463async fn test_truncate_first_message(cx: &mut TestAppContext) {
1464    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1465    let fake_model = model.as_fake();
1466
1467    let message_id = UserMessageId::new();
1468    thread
1469        .update(cx, |thread, cx| {
1470            thread.send(message_id.clone(), ["Hello"], cx)
1471        })
1472        .unwrap();
1473    cx.run_until_parked();
1474    thread.read_with(cx, |thread, _| {
1475        assert_eq!(
1476            thread.to_markdown(),
1477            indoc! {"
1478                ## User
1479
1480                Hello
1481            "}
1482        );
1483        assert_eq!(thread.latest_token_usage(), None);
1484    });
1485
1486    fake_model.send_last_completion_stream_text_chunk("Hey!");
1487    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
1488        language_model::TokenUsage {
1489            input_tokens: 32_000,
1490            output_tokens: 16_000,
1491            cache_creation_input_tokens: 0,
1492            cache_read_input_tokens: 0,
1493        },
1494    ));
1495    cx.run_until_parked();
1496    thread.read_with(cx, |thread, _| {
1497        assert_eq!(
1498            thread.to_markdown(),
1499            indoc! {"
1500                ## User
1501
1502                Hello
1503
1504                ## Assistant
1505
1506                Hey!
1507            "}
1508        );
1509        assert_eq!(
1510            thread.latest_token_usage(),
1511            Some(acp_thread::TokenUsage {
1512                used_tokens: 32_000 + 16_000,
1513                max_tokens: 1_000_000,
1514            })
1515        );
1516    });
1517
1518    thread
1519        .update(cx, |thread, cx| thread.truncate(message_id, cx))
1520        .unwrap();
1521    cx.run_until_parked();
1522    thread.read_with(cx, |thread, _| {
1523        assert_eq!(thread.to_markdown(), "");
1524        assert_eq!(thread.latest_token_usage(), None);
1525    });
1526
1527    // Ensure we can still send a new message after truncation.
1528    thread
1529        .update(cx, |thread, cx| {
1530            thread.send(UserMessageId::new(), ["Hi"], cx)
1531        })
1532        .unwrap();
1533    thread.update(cx, |thread, _cx| {
1534        assert_eq!(
1535            thread.to_markdown(),
1536            indoc! {"
1537                ## User
1538
1539                Hi
1540            "}
1541        );
1542    });
1543    cx.run_until_parked();
1544    fake_model.send_last_completion_stream_text_chunk("Ahoy!");
1545    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
1546        language_model::TokenUsage {
1547            input_tokens: 40_000,
1548            output_tokens: 20_000,
1549            cache_creation_input_tokens: 0,
1550            cache_read_input_tokens: 0,
1551        },
1552    ));
1553    cx.run_until_parked();
1554    thread.read_with(cx, |thread, _| {
1555        assert_eq!(
1556            thread.to_markdown(),
1557            indoc! {"
1558                ## User
1559
1560                Hi
1561
1562                ## Assistant
1563
1564                Ahoy!
1565            "}
1566        );
1567
1568        assert_eq!(
1569            thread.latest_token_usage(),
1570            Some(acp_thread::TokenUsage {
1571                used_tokens: 40_000 + 20_000,
1572                max_tokens: 1_000_000,
1573            })
1574        );
1575    });
1576}
1577
1578#[gpui::test]
1579async fn test_truncate_second_message(cx: &mut TestAppContext) {
1580    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1581    let fake_model = model.as_fake();
1582
1583    thread
1584        .update(cx, |thread, cx| {
1585            thread.send(UserMessageId::new(), ["Message 1"], cx)
1586        })
1587        .unwrap();
1588    cx.run_until_parked();
1589    fake_model.send_last_completion_stream_text_chunk("Message 1 response");
1590    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
1591        language_model::TokenUsage {
1592            input_tokens: 32_000,
1593            output_tokens: 16_000,
1594            cache_creation_input_tokens: 0,
1595            cache_read_input_tokens: 0,
1596        },
1597    ));
1598    fake_model.end_last_completion_stream();
1599    cx.run_until_parked();
1600
1601    let assert_first_message_state = |cx: &mut TestAppContext| {
1602        thread.clone().read_with(cx, |thread, _| {
1603            assert_eq!(
1604                thread.to_markdown(),
1605                indoc! {"
1606                    ## User
1607
1608                    Message 1
1609
1610                    ## Assistant
1611
1612                    Message 1 response
1613                "}
1614            );
1615
1616            assert_eq!(
1617                thread.latest_token_usage(),
1618                Some(acp_thread::TokenUsage {
1619                    used_tokens: 32_000 + 16_000,
1620                    max_tokens: 1_000_000,
1621                })
1622            );
1623        });
1624    };
1625
1626    assert_first_message_state(cx);
1627
1628    let second_message_id = UserMessageId::new();
1629    thread
1630        .update(cx, |thread, cx| {
1631            thread.send(second_message_id.clone(), ["Message 2"], cx)
1632        })
1633        .unwrap();
1634    cx.run_until_parked();
1635
1636    fake_model.send_last_completion_stream_text_chunk("Message 2 response");
1637    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
1638        language_model::TokenUsage {
1639            input_tokens: 40_000,
1640            output_tokens: 20_000,
1641            cache_creation_input_tokens: 0,
1642            cache_read_input_tokens: 0,
1643        },
1644    ));
1645    fake_model.end_last_completion_stream();
1646    cx.run_until_parked();
1647
1648    thread.read_with(cx, |thread, _| {
1649        assert_eq!(
1650            thread.to_markdown(),
1651            indoc! {"
1652                ## User
1653
1654                Message 1
1655
1656                ## Assistant
1657
1658                Message 1 response
1659
1660                ## User
1661
1662                Message 2
1663
1664                ## Assistant
1665
1666                Message 2 response
1667            "}
1668        );
1669
1670        assert_eq!(
1671            thread.latest_token_usage(),
1672            Some(acp_thread::TokenUsage {
1673                used_tokens: 40_000 + 20_000,
1674                max_tokens: 1_000_000,
1675            })
1676        );
1677    });
1678
1679    thread
1680        .update(cx, |thread, cx| thread.truncate(second_message_id, cx))
1681        .unwrap();
1682    cx.run_until_parked();
1683
1684    assert_first_message_state(cx);
1685}
1686
1687#[gpui::test]
1688async fn test_title_generation(cx: &mut TestAppContext) {
1689    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1690    let fake_model = model.as_fake();
1691
1692    let summary_model = Arc::new(FakeLanguageModel::default());
1693    thread.update(cx, |thread, cx| {
1694        thread.set_summarization_model(Some(summary_model.clone()), cx)
1695    });
1696
1697    let send = thread
1698        .update(cx, |thread, cx| {
1699            thread.send(UserMessageId::new(), ["Hello"], cx)
1700        })
1701        .unwrap();
1702    cx.run_until_parked();
1703
1704    fake_model.send_last_completion_stream_text_chunk("Hey!");
1705    fake_model.end_last_completion_stream();
1706    cx.run_until_parked();
1707    thread.read_with(cx, |thread, _| assert_eq!(thread.title(), "New Thread"));
1708
1709    // Ensure the summary model has been invoked to generate a title.
1710    summary_model.send_last_completion_stream_text_chunk("Hello ");
1711    summary_model.send_last_completion_stream_text_chunk("world\nG");
1712    summary_model.send_last_completion_stream_text_chunk("oodnight Moon");
1713    summary_model.end_last_completion_stream();
1714    send.collect::<Vec<_>>().await;
1715    cx.run_until_parked();
1716    thread.read_with(cx, |thread, _| assert_eq!(thread.title(), "Hello world"));
1717
1718    // Send another message, ensuring no title is generated this time.
1719    let send = thread
1720        .update(cx, |thread, cx| {
1721            thread.send(UserMessageId::new(), ["Hello again"], cx)
1722        })
1723        .unwrap();
1724    cx.run_until_parked();
1725    fake_model.send_last_completion_stream_text_chunk("Hey again!");
1726    fake_model.end_last_completion_stream();
1727    cx.run_until_parked();
1728    assert_eq!(summary_model.pending_completions(), Vec::new());
1729    send.collect::<Vec<_>>().await;
1730    thread.read_with(cx, |thread, _| assert_eq!(thread.title(), "Hello world"));
1731}
1732
1733#[gpui::test]
1734async fn test_building_request_with_pending_tools(cx: &mut TestAppContext) {
1735    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
1736    let fake_model = model.as_fake();
1737
1738    let _events = thread
1739        .update(cx, |thread, cx| {
1740            thread.add_tool(ToolRequiringPermission);
1741            thread.add_tool(EchoTool);
1742            thread.send(UserMessageId::new(), ["Hey!"], cx)
1743        })
1744        .unwrap();
1745    cx.run_until_parked();
1746
1747    let permission_tool_use = LanguageModelToolUse {
1748        id: "tool_id_1".into(),
1749        name: ToolRequiringPermission::name().into(),
1750        raw_input: "{}".into(),
1751        input: json!({}),
1752        is_input_complete: true,
1753    };
1754    let echo_tool_use = LanguageModelToolUse {
1755        id: "tool_id_2".into(),
1756        name: EchoTool::name().into(),
1757        raw_input: json!({"text": "test"}).to_string(),
1758        input: json!({"text": "test"}),
1759        is_input_complete: true,
1760    };
1761    fake_model.send_last_completion_stream_text_chunk("Hi!");
1762    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
1763        permission_tool_use,
1764    ));
1765    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
1766        echo_tool_use.clone(),
1767    ));
1768    fake_model.end_last_completion_stream();
1769    cx.run_until_parked();
1770
1771    // Ensure pending tools are skipped when building a request.
1772    let request = thread
1773        .read_with(cx, |thread, cx| {
1774            thread.build_completion_request(CompletionIntent::EditFile, cx)
1775        })
1776        .unwrap();
1777    assert_eq!(
1778        request.messages[1..],
1779        vec![
1780            LanguageModelRequestMessage {
1781                role: Role::User,
1782                content: vec!["Hey!".into()],
1783                cache: true
1784            },
1785            LanguageModelRequestMessage {
1786                role: Role::Assistant,
1787                content: vec![
1788                    MessageContent::Text("Hi!".into()),
1789                    MessageContent::ToolUse(echo_tool_use.clone())
1790                ],
1791                cache: false
1792            },
1793            LanguageModelRequestMessage {
1794                role: Role::User,
1795                content: vec![MessageContent::ToolResult(LanguageModelToolResult {
1796                    tool_use_id: echo_tool_use.id.clone(),
1797                    tool_name: echo_tool_use.name,
1798                    is_error: false,
1799                    content: "test".into(),
1800                    output: Some("test".into())
1801                })],
1802                cache: false
1803            },
1804        ],
1805    );
1806}
1807
1808#[gpui::test]
1809async fn test_agent_connection(cx: &mut TestAppContext) {
1810    cx.update(settings::init);
1811    let templates = Templates::new();
1812
1813    // Initialize language model system with test provider
1814    cx.update(|cx| {
1815        gpui_tokio::init(cx);
1816        client::init_settings(cx);
1817
1818        let http_client = FakeHttpClient::with_404_response();
1819        let clock = Arc::new(clock::FakeSystemClock::new());
1820        let client = Client::new(clock, http_client, cx);
1821        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1822        Project::init_settings(cx);
1823        agent_settings::init(cx);
1824        language_model::init(client.clone(), cx);
1825        language_models::init(user_store, client.clone(), cx);
1826        LanguageModelRegistry::test(cx);
1827    });
1828    cx.executor().forbid_parking();
1829
1830    // Create a project for new_thread
1831    let fake_fs = cx.update(|cx| fs::FakeFs::new(cx.background_executor().clone()));
1832    fake_fs.insert_tree(path!("/test"), json!({})).await;
1833    let project = Project::test(fake_fs.clone(), [Path::new("/test")], cx).await;
1834    let cwd = Path::new("/test");
1835    let context_store = cx.new(|cx| assistant_context::ContextStore::fake(project.clone(), cx));
1836    let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1837
1838    // Create agent and connection
1839    let agent = NativeAgent::new(
1840        project.clone(),
1841        history_store,
1842        templates.clone(),
1843        None,
1844        fake_fs.clone(),
1845        &mut cx.to_async(),
1846    )
1847    .await
1848    .unwrap();
1849    let connection = NativeAgentConnection(agent.clone());
1850
1851    // Test model_selector returns Some
1852    let selector_opt = connection.model_selector();
1853    assert!(
1854        selector_opt.is_some(),
1855        "agent2 should always support ModelSelector"
1856    );
1857    let selector = selector_opt.unwrap();
1858
1859    // Test list_models
1860    let listed_models = cx
1861        .update(|cx| selector.list_models(cx))
1862        .await
1863        .expect("list_models should succeed");
1864    let AgentModelList::Grouped(listed_models) = listed_models else {
1865        panic!("Unexpected model list type");
1866    };
1867    assert!(!listed_models.is_empty(), "should have at least one model");
1868    assert_eq!(
1869        listed_models[&AgentModelGroupName("Fake".into())][0].id.0,
1870        "fake/fake"
1871    );
1872
1873    // Create a thread using new_thread
1874    let connection_rc = Rc::new(connection.clone());
1875    let acp_thread = cx
1876        .update(|cx| connection_rc.new_thread(project, cwd, cx))
1877        .await
1878        .expect("new_thread should succeed");
1879
1880    // Get the session_id from the AcpThread
1881    let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
1882
1883    // Test selected_model returns the default
1884    let model = cx
1885        .update(|cx| selector.selected_model(&session_id, cx))
1886        .await
1887        .expect("selected_model should succeed");
1888    let model = cx
1889        .update(|cx| agent.read(cx).models().model_from_id(&model.id))
1890        .unwrap();
1891    let model = model.as_fake();
1892    assert_eq!(model.id().0, "fake", "should return default model");
1893
1894    let request = acp_thread.update(cx, |thread, cx| thread.send(vec!["abc".into()], cx));
1895    cx.run_until_parked();
1896    model.send_last_completion_stream_text_chunk("def");
1897    cx.run_until_parked();
1898    acp_thread.read_with(cx, |thread, cx| {
1899        assert_eq!(
1900            thread.to_markdown(cx),
1901            indoc! {"
1902                ## User
1903
1904                abc
1905
1906                ## Assistant
1907
1908                def
1909
1910            "}
1911        )
1912    });
1913
1914    // Test cancel
1915    cx.update(|cx| connection.cancel(&session_id, cx));
1916    request.await.expect("prompt should fail gracefully");
1917
1918    // Ensure that dropping the ACP thread causes the native thread to be
1919    // dropped as well.
1920    cx.update(|_| drop(acp_thread));
1921    let result = cx
1922        .update(|cx| {
1923            connection.prompt(
1924                Some(acp_thread::UserMessageId::new()),
1925                acp::PromptRequest {
1926                    session_id: session_id.clone(),
1927                    prompt: vec!["ghi".into()],
1928                },
1929                cx,
1930            )
1931        })
1932        .await;
1933    assert_eq!(
1934        result.as_ref().unwrap_err().to_string(),
1935        "Session not found",
1936        "unexpected result: {:?}",
1937        result
1938    );
1939}
1940
1941#[gpui::test]
1942async fn test_tool_updates_to_completion(cx: &mut TestAppContext) {
1943    let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
1944    thread.update(cx, |thread, _cx| thread.add_tool(ThinkingTool));
1945    let fake_model = model.as_fake();
1946
1947    let mut events = thread
1948        .update(cx, |thread, cx| {
1949            thread.send(UserMessageId::new(), ["Think"], cx)
1950        })
1951        .unwrap();
1952    cx.run_until_parked();
1953
1954    // Simulate streaming partial input.
1955    let input = json!({});
1956    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
1957        LanguageModelToolUse {
1958            id: "1".into(),
1959            name: ThinkingTool::name().into(),
1960            raw_input: input.to_string(),
1961            input,
1962            is_input_complete: false,
1963        },
1964    ));
1965
1966    // Input streaming completed
1967    let input = json!({ "content": "Thinking hard!" });
1968    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
1969        LanguageModelToolUse {
1970            id: "1".into(),
1971            name: "thinking".into(),
1972            raw_input: input.to_string(),
1973            input,
1974            is_input_complete: true,
1975        },
1976    ));
1977    fake_model.end_last_completion_stream();
1978    cx.run_until_parked();
1979
1980    let tool_call = expect_tool_call(&mut events).await;
1981    assert_eq!(
1982        tool_call,
1983        acp::ToolCall {
1984            id: acp::ToolCallId("1".into()),
1985            title: "Thinking".into(),
1986            kind: acp::ToolKind::Think,
1987            status: acp::ToolCallStatus::Pending,
1988            content: vec![],
1989            locations: vec![],
1990            raw_input: Some(json!({})),
1991            raw_output: None,
1992        }
1993    );
1994    let update = expect_tool_call_update_fields(&mut events).await;
1995    assert_eq!(
1996        update,
1997        acp::ToolCallUpdate {
1998            id: acp::ToolCallId("1".into()),
1999            fields: acp::ToolCallUpdateFields {
2000                title: Some("Thinking".into()),
2001                kind: Some(acp::ToolKind::Think),
2002                raw_input: Some(json!({ "content": "Thinking hard!" })),
2003                ..Default::default()
2004            },
2005        }
2006    );
2007    let update = expect_tool_call_update_fields(&mut events).await;
2008    assert_eq!(
2009        update,
2010        acp::ToolCallUpdate {
2011            id: acp::ToolCallId("1".into()),
2012            fields: acp::ToolCallUpdateFields {
2013                status: Some(acp::ToolCallStatus::InProgress),
2014                ..Default::default()
2015            },
2016        }
2017    );
2018    let update = expect_tool_call_update_fields(&mut events).await;
2019    assert_eq!(
2020        update,
2021        acp::ToolCallUpdate {
2022            id: acp::ToolCallId("1".into()),
2023            fields: acp::ToolCallUpdateFields {
2024                content: Some(vec!["Thinking hard!".into()]),
2025                ..Default::default()
2026            },
2027        }
2028    );
2029    let update = expect_tool_call_update_fields(&mut events).await;
2030    assert_eq!(
2031        update,
2032        acp::ToolCallUpdate {
2033            id: acp::ToolCallId("1".into()),
2034            fields: acp::ToolCallUpdateFields {
2035                status: Some(acp::ToolCallStatus::Completed),
2036                raw_output: Some("Finished thinking.".into()),
2037                ..Default::default()
2038            },
2039        }
2040    );
2041}
2042
2043#[gpui::test]
2044async fn test_send_no_retry_on_success(cx: &mut TestAppContext) {
2045    let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
2046    let fake_model = model.as_fake();
2047
2048    let mut events = thread
2049        .update(cx, |thread, cx| {
2050            thread.set_completion_mode(agent_settings::CompletionMode::Burn, cx);
2051            thread.send(UserMessageId::new(), ["Hello!"], cx)
2052        })
2053        .unwrap();
2054    cx.run_until_parked();
2055
2056    fake_model.send_last_completion_stream_text_chunk("Hey!");
2057    fake_model.end_last_completion_stream();
2058
2059    let mut retry_events = Vec::new();
2060    while let Some(Ok(event)) = events.next().await {
2061        match event {
2062            ThreadEvent::Retry(retry_status) => {
2063                retry_events.push(retry_status);
2064            }
2065            ThreadEvent::Stop(..) => break,
2066            _ => {}
2067        }
2068    }
2069
2070    assert_eq!(retry_events.len(), 0);
2071    thread.read_with(cx, |thread, _cx| {
2072        assert_eq!(
2073            thread.to_markdown(),
2074            indoc! {"
2075                ## User
2076
2077                Hello!
2078
2079                ## Assistant
2080
2081                Hey!
2082            "}
2083        )
2084    });
2085}
2086
2087#[gpui::test]
2088async fn test_send_retry_on_error(cx: &mut TestAppContext) {
2089    let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
2090    let fake_model = model.as_fake();
2091
2092    let mut events = thread
2093        .update(cx, |thread, cx| {
2094            thread.set_completion_mode(agent_settings::CompletionMode::Burn, cx);
2095            thread.send(UserMessageId::new(), ["Hello!"], cx)
2096        })
2097        .unwrap();
2098    cx.run_until_parked();
2099
2100    fake_model.send_last_completion_stream_text_chunk("Hey,");
2101    fake_model.send_last_completion_stream_error(LanguageModelCompletionError::ServerOverloaded {
2102        provider: LanguageModelProviderName::new("Anthropic"),
2103        retry_after: Some(Duration::from_secs(3)),
2104    });
2105    fake_model.end_last_completion_stream();
2106
2107    cx.executor().advance_clock(Duration::from_secs(3));
2108    cx.run_until_parked();
2109
2110    fake_model.send_last_completion_stream_text_chunk("there!");
2111    fake_model.end_last_completion_stream();
2112    cx.run_until_parked();
2113
2114    let mut retry_events = Vec::new();
2115    while let Some(Ok(event)) = events.next().await {
2116        match event {
2117            ThreadEvent::Retry(retry_status) => {
2118                retry_events.push(retry_status);
2119            }
2120            ThreadEvent::Stop(..) => break,
2121            _ => {}
2122        }
2123    }
2124
2125    assert_eq!(retry_events.len(), 1);
2126    assert!(matches!(
2127        retry_events[0],
2128        acp_thread::RetryStatus { attempt: 1, .. }
2129    ));
2130    thread.read_with(cx, |thread, _cx| {
2131        assert_eq!(
2132            thread.to_markdown(),
2133            indoc! {"
2134                ## User
2135
2136                Hello!
2137
2138                ## Assistant
2139
2140                Hey,
2141
2142                [resume]
2143
2144                ## Assistant
2145
2146                there!
2147            "}
2148        )
2149    });
2150}
2151
2152#[gpui::test]
2153async fn test_send_retry_finishes_tool_calls_on_error(cx: &mut TestAppContext) {
2154    let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
2155    let fake_model = model.as_fake();
2156
2157    let events = thread
2158        .update(cx, |thread, cx| {
2159            thread.set_completion_mode(agent_settings::CompletionMode::Burn, cx);
2160            thread.add_tool(EchoTool);
2161            thread.send(UserMessageId::new(), ["Call the echo tool!"], cx)
2162        })
2163        .unwrap();
2164    cx.run_until_parked();
2165
2166    let tool_use_1 = LanguageModelToolUse {
2167        id: "tool_1".into(),
2168        name: EchoTool::name().into(),
2169        raw_input: json!({"text": "test"}).to_string(),
2170        input: json!({"text": "test"}),
2171        is_input_complete: true,
2172    };
2173    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
2174        tool_use_1.clone(),
2175    ));
2176    fake_model.send_last_completion_stream_error(LanguageModelCompletionError::ServerOverloaded {
2177        provider: LanguageModelProviderName::new("Anthropic"),
2178        retry_after: Some(Duration::from_secs(3)),
2179    });
2180    fake_model.end_last_completion_stream();
2181
2182    cx.executor().advance_clock(Duration::from_secs(3));
2183    let completion = fake_model.pending_completions().pop().unwrap();
2184    assert_eq!(
2185        completion.messages[1..],
2186        vec![
2187            LanguageModelRequestMessage {
2188                role: Role::User,
2189                content: vec!["Call the echo tool!".into()],
2190                cache: false
2191            },
2192            LanguageModelRequestMessage {
2193                role: Role::Assistant,
2194                content: vec![language_model::MessageContent::ToolUse(tool_use_1.clone())],
2195                cache: false
2196            },
2197            LanguageModelRequestMessage {
2198                role: Role::User,
2199                content: vec![language_model::MessageContent::ToolResult(
2200                    LanguageModelToolResult {
2201                        tool_use_id: tool_use_1.id.clone(),
2202                        tool_name: tool_use_1.name.clone(),
2203                        is_error: false,
2204                        content: "test".into(),
2205                        output: Some("test".into())
2206                    }
2207                )],
2208                cache: true
2209            },
2210        ]
2211    );
2212
2213    fake_model.send_last_completion_stream_text_chunk("Done");
2214    fake_model.end_last_completion_stream();
2215    cx.run_until_parked();
2216    events.collect::<Vec<_>>().await;
2217    thread.read_with(cx, |thread, _cx| {
2218        assert_eq!(
2219            thread.last_message(),
2220            Some(Message::Agent(AgentMessage {
2221                content: vec![AgentMessageContent::Text("Done".into())],
2222                tool_results: IndexMap::default()
2223            }))
2224        );
2225    })
2226}
2227
2228#[gpui::test]
2229async fn test_send_max_retries_exceeded(cx: &mut TestAppContext) {
2230    let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
2231    let fake_model = model.as_fake();
2232
2233    let mut events = thread
2234        .update(cx, |thread, cx| {
2235            thread.set_completion_mode(agent_settings::CompletionMode::Burn, cx);
2236            thread.send(UserMessageId::new(), ["Hello!"], cx)
2237        })
2238        .unwrap();
2239    cx.run_until_parked();
2240
2241    for _ in 0..crate::thread::MAX_RETRY_ATTEMPTS + 1 {
2242        fake_model.send_last_completion_stream_error(
2243            LanguageModelCompletionError::ServerOverloaded {
2244                provider: LanguageModelProviderName::new("Anthropic"),
2245                retry_after: Some(Duration::from_secs(3)),
2246            },
2247        );
2248        fake_model.end_last_completion_stream();
2249        cx.executor().advance_clock(Duration::from_secs(3));
2250        cx.run_until_parked();
2251    }
2252
2253    let mut errors = Vec::new();
2254    let mut retry_events = Vec::new();
2255    while let Some(event) = events.next().await {
2256        match event {
2257            Ok(ThreadEvent::Retry(retry_status)) => {
2258                retry_events.push(retry_status);
2259            }
2260            Ok(ThreadEvent::Stop(..)) => break,
2261            Err(error) => errors.push(error),
2262            _ => {}
2263        }
2264    }
2265
2266    assert_eq!(
2267        retry_events.len(),
2268        crate::thread::MAX_RETRY_ATTEMPTS as usize
2269    );
2270    for i in 0..crate::thread::MAX_RETRY_ATTEMPTS as usize {
2271        assert_eq!(retry_events[i].attempt, i + 1);
2272    }
2273    assert_eq!(errors.len(), 1);
2274    let error = errors[0]
2275        .downcast_ref::<LanguageModelCompletionError>()
2276        .unwrap();
2277    assert!(matches!(
2278        error,
2279        LanguageModelCompletionError::ServerOverloaded { .. }
2280    ));
2281}
2282
2283/// Filters out the stop events for asserting against in tests
2284fn stop_events(result_events: Vec<Result<ThreadEvent>>) -> Vec<acp::StopReason> {
2285    result_events
2286        .into_iter()
2287        .filter_map(|event| match event.unwrap() {
2288            ThreadEvent::Stop(stop_reason) => Some(stop_reason),
2289            _ => None,
2290        })
2291        .collect()
2292}
2293
2294struct ThreadTest {
2295    model: Arc<dyn LanguageModel>,
2296    thread: Entity<Thread>,
2297    project_context: Entity<ProjectContext>,
2298    context_server_store: Entity<ContextServerStore>,
2299    fs: Arc<FakeFs>,
2300}
2301
2302enum TestModel {
2303    Sonnet4,
2304    Fake,
2305}
2306
2307impl TestModel {
2308    fn id(&self) -> LanguageModelId {
2309        match self {
2310            TestModel::Sonnet4 => LanguageModelId("claude-sonnet-4-latest".into()),
2311            TestModel::Fake => unreachable!(),
2312        }
2313    }
2314}
2315
2316async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
2317    cx.executor().allow_parking();
2318
2319    let fs = FakeFs::new(cx.background_executor.clone());
2320    fs.create_dir(paths::settings_file().parent().unwrap())
2321        .await
2322        .unwrap();
2323    fs.insert_file(
2324        paths::settings_file(),
2325        json!({
2326            "agent": {
2327                "default_profile": "test-profile",
2328                "profiles": {
2329                    "test-profile": {
2330                        "name": "Test Profile",
2331                        "tools": {
2332                            EchoTool::name(): true,
2333                            DelayTool::name(): true,
2334                            WordListTool::name(): true,
2335                            ToolRequiringPermission::name(): true,
2336                            InfiniteTool::name(): true,
2337                            ThinkingTool::name(): true,
2338                        }
2339                    }
2340                }
2341            }
2342        })
2343        .to_string()
2344        .into_bytes(),
2345    )
2346    .await;
2347
2348    cx.update(|cx| {
2349        settings::init(cx);
2350        Project::init_settings(cx);
2351        agent_settings::init(cx);
2352        gpui_tokio::init(cx);
2353        let http_client = ReqwestClient::user_agent("agent tests").unwrap();
2354        cx.set_http_client(Arc::new(http_client));
2355
2356        client::init_settings(cx);
2357        let client = Client::production(cx);
2358        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2359        language_model::init(client.clone(), cx);
2360        language_models::init(user_store, client.clone(), cx);
2361
2362        watch_settings(fs.clone(), cx);
2363    });
2364
2365    let templates = Templates::new();
2366
2367    fs.insert_tree(path!("/test"), json!({})).await;
2368    let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
2369
2370    let model = cx
2371        .update(|cx| {
2372            if let TestModel::Fake = model {
2373                Task::ready(Arc::new(FakeLanguageModel::default()) as Arc<_>)
2374            } else {
2375                let model_id = model.id();
2376                let models = LanguageModelRegistry::read_global(cx);
2377                let model = models
2378                    .available_models(cx)
2379                    .find(|model| model.id() == model_id)
2380                    .unwrap();
2381
2382                let provider = models.provider(&model.provider_id()).unwrap();
2383                let authenticated = provider.authenticate(cx);
2384
2385                cx.spawn(async move |_cx| {
2386                    authenticated.await.unwrap();
2387                    model
2388                })
2389            }
2390        })
2391        .await;
2392
2393    let project_context = cx.new(|_cx| ProjectContext::default());
2394    let context_server_store = project.read_with(cx, |project, _| project.context_server_store());
2395    let context_server_registry =
2396        cx.new(|cx| ContextServerRegistry::new(context_server_store.clone(), cx));
2397    let thread = cx.new(|cx| {
2398        Thread::new(
2399            project,
2400            project_context.clone(),
2401            context_server_registry,
2402            templates,
2403            Some(model.clone()),
2404            cx,
2405        )
2406    });
2407    ThreadTest {
2408        model,
2409        thread,
2410        project_context,
2411        context_server_store,
2412        fs,
2413    }
2414}
2415
2416#[cfg(test)]
2417#[ctor::ctor]
2418fn init_logger() {
2419    if std::env::var("RUST_LOG").is_ok() {
2420        env_logger::init();
2421    }
2422}
2423
2424fn watch_settings(fs: Arc<dyn Fs>, cx: &mut App) {
2425    let fs = fs.clone();
2426    cx.spawn({
2427        async move |cx| {
2428            let mut new_settings_content_rx = settings::watch_config_file(
2429                cx.background_executor(),
2430                fs,
2431                paths::settings_file().clone(),
2432            );
2433
2434            while let Some(new_settings_content) = new_settings_content_rx.next().await {
2435                cx.update(|cx| {
2436                    SettingsStore::update_global(cx, |settings, cx| {
2437                        settings.set_user_settings(&new_settings_content, cx)
2438                    })
2439                })
2440                .ok();
2441            }
2442        }
2443    })
2444    .detach();
2445}
2446
2447fn tool_names_for_completion(completion: &LanguageModelRequest) -> Vec<String> {
2448    completion
2449        .tools
2450        .iter()
2451        .map(|tool| tool.name.clone())
2452        .collect()
2453}
2454
2455fn setup_context_server(
2456    name: &'static str,
2457    tools: Vec<context_server::types::Tool>,
2458    context_server_store: &Entity<ContextServerStore>,
2459    cx: &mut TestAppContext,
2460) -> mpsc::UnboundedReceiver<(
2461    context_server::types::CallToolParams,
2462    oneshot::Sender<context_server::types::CallToolResponse>,
2463)> {
2464    cx.update(|cx| {
2465        let mut settings = ProjectSettings::get_global(cx).clone();
2466        settings.context_servers.insert(
2467            name.into(),
2468            project::project_settings::ContextServerSettings::Custom {
2469                enabled: true,
2470                command: ContextServerCommand {
2471                    path: "somebinary".into(),
2472                    args: Vec::new(),
2473                    env: None,
2474                },
2475            },
2476        );
2477        ProjectSettings::override_global(settings, cx);
2478    });
2479
2480    let (mcp_tool_calls_tx, mcp_tool_calls_rx) = mpsc::unbounded();
2481    let fake_transport = context_server::test::create_fake_transport(name, cx.executor())
2482        .on_request::<context_server::types::requests::Initialize, _>(move |_params| async move {
2483            context_server::types::InitializeResponse {
2484                protocol_version: context_server::types::ProtocolVersion(
2485                    context_server::types::LATEST_PROTOCOL_VERSION.to_string(),
2486                ),
2487                server_info: context_server::types::Implementation {
2488                    name: name.into(),
2489                    version: "1.0.0".to_string(),
2490                },
2491                capabilities: context_server::types::ServerCapabilities {
2492                    tools: Some(context_server::types::ToolsCapabilities {
2493                        list_changed: Some(true),
2494                    }),
2495                    ..Default::default()
2496                },
2497                meta: None,
2498            }
2499        })
2500        .on_request::<context_server::types::requests::ListTools, _>(move |_params| {
2501            let tools = tools.clone();
2502            async move {
2503                context_server::types::ListToolsResponse {
2504                    tools,
2505                    next_cursor: None,
2506                    meta: None,
2507                }
2508            }
2509        })
2510        .on_request::<context_server::types::requests::CallTool, _>(move |params| {
2511            let mcp_tool_calls_tx = mcp_tool_calls_tx.clone();
2512            async move {
2513                let (response_tx, response_rx) = oneshot::channel();
2514                mcp_tool_calls_tx
2515                    .unbounded_send((params, response_tx))
2516                    .unwrap();
2517                response_rx.await.unwrap()
2518            }
2519        });
2520    context_server_store.update(cx, |store, cx| {
2521        store.start_server(
2522            Arc::new(ContextServer::new(
2523                ContextServerId(name.into()),
2524                Arc::new(fake_transport),
2525            )),
2526            cx,
2527        );
2528    });
2529    cx.run_until_parked();
2530    mcp_tool_calls_rx
2531}