example.rs

   1use crate::{AgentAppState, ToolMetrics};
   2use agent::{ThreadEvent, ThreadStore};
   3use anyhow::{Context as _, Result, anyhow};
   4use assistant_tool::ToolWorkingSet;
   5use client::proto::LspWorkProgress;
   6use dap::DapRegistry;
   7use futures::channel::mpsc;
   8use futures::{FutureExt, StreamExt as _, select_biased};
   9use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
  10use handlebars::Handlebars;
  11use language::{Buffer, DiagnosticSeverity, OffsetRangeExt};
  12use language_model::{
  13    LanguageModel, LanguageModelCompletionEvent, LanguageModelRequest, LanguageModelRequestMessage,
  14    MessageContent, Role, StopReason, TokenUsage,
  15};
  16use project::{Project, ProjectPath};
  17use serde::{Deserialize, Serialize};
  18use std::cell::RefCell;
  19use std::fmt::Write as _;
  20use std::fs::File;
  21use std::io::Write as _;
  22use std::rc::Rc;
  23use std::sync::{Arc, Mutex};
  24use std::time::Duration;
  25use std::{
  26    fs,
  27    path::{Path, PathBuf},
  28};
  29use unindent::Unindent as _;
  30use util::ResultExt as _;
  31use util::command::new_smol_command;
  32use util::markdown::MarkdownString;
  33use util::serde::default_true;
  34
  35pub const EXAMPLES_DIR: &str = "./crates/eval/examples";
  36pub const REPOS_DIR: &str = "./crates/eval/repos";
  37pub const WORKTREES_DIR: &str = "./crates/eval/worktrees";
  38
  39const THREAD_EVENT_TIMEOUT: Duration = Duration::from_secs(60 * 2);
  40
  41#[derive(Clone, Debug, Deserialize)]
  42pub struct ExampleBase {
  43    pub url: String,
  44    pub revision: String,
  45    pub language_extension: Option<String>,
  46    pub insert_id: Option<String>,
  47    #[serde(default = "default_true")]
  48    pub require_lsp: bool,
  49    #[serde(default)]
  50    pub allow_preexisting_diagnostics: bool,
  51}
  52
  53impl ExampleBase {
  54    pub fn repo_name(&self) -> String {
  55        self.url
  56            .split('/')
  57            .next_back()
  58            .unwrap_or(&"")
  59            .trim_end_matches(".git")
  60            .into()
  61    }
  62}
  63
  64#[derive(Clone, Debug)]
  65pub struct Example {
  66    pub name: String,
  67    /// Content of `base.toml`
  68    pub base: ExampleBase,
  69    /// Content of `prompt.md`
  70    pub prompt: String,
  71    /// Content of `diff_criteria.md`
  72    pub diff_criteria: String,
  73    /// Content of `thread_criteria.md`, if that file exists (it's optional)
  74    pub thread_criteria: Option<String>,
  75    /// Path to the directory containing the requests and responses for the agentic loop
  76    pub run_directory_path: PathBuf,
  77    /// Prefix used for logging that identifies this example
  78    pub log_prefix: String,
  79}
  80
  81#[derive(Debug, Serialize, Deserialize, Clone)]
  82pub struct RunOutput {
  83    pub repository_diff: String,
  84    pub ran_diagnostics_check: bool,
  85    pub diagnostics_before: Option<String>,
  86    pub diagnostics_after: Option<String>,
  87    pub response_count: usize,
  88    pub token_usage: TokenUsage,
  89    pub tool_metrics: ToolMetrics,
  90    pub last_request: LanguageModelRequest,
  91}
  92
  93#[derive(Debug, Clone, Serialize, Deserialize)]
  94pub struct JudgeDiffInput {
  95    pub repository_diff: String,
  96    pub ran_diagnostics_check: bool,
  97    #[serde(skip_serializing_if = "Option::is_none")]
  98    pub diagnostics_before: Option<String>,
  99    #[serde(skip_serializing_if = "Option::is_none")]
 100    pub diagnostics_after: Option<String>,
 101    pub criteria: String,
 102}
 103
 104#[derive(Debug, Clone, Serialize, Deserialize)]
 105pub struct JudgeThreadInput {
 106    pub messages: String,
 107    pub criteria: String,
 108}
 109
 110#[derive(Debug, Clone, Serialize, Deserialize)]
 111pub struct JudgeResponse {
 112    pub analysis: String,
 113    pub score: u32,
 114}
 115
 116#[derive(Debug, Clone, Serialize, Deserialize)]
 117pub struct JudgeOutput {
 118    pub thread: Option<JudgeResponse>,
 119    pub diff: JudgeResponse,
 120}
 121
 122impl Example {
 123    /// Load an example from a directory containing base.toml, prompt.md, and criteria.md
 124    pub fn load_from_directory(dir_path: &Path, run_dir: &Path) -> Result<Self> {
 125        let name = Self::name_from_path(dir_path);
 126        let base_path = dir_path.join("base.toml");
 127        let prompt_path = dir_path.join("prompt.md");
 128        let diff_criteria_path = dir_path.join("diff_criteria.md");
 129        let thread_criteria_path = dir_path.join("thread_criteria.md");
 130        let thread_criteria = if thread_criteria_path.exists() {
 131            Some(fs::read_to_string(thread_criteria_path.clone())?)
 132        } else {
 133            None
 134        };
 135
 136        Ok(Example {
 137            name: name.clone(),
 138            base: toml::from_str(&fs::read_to_string(&base_path)?)?,
 139            prompt: fs::read_to_string(prompt_path.clone())?,
 140            thread_criteria,
 141            diff_criteria: fs::read_to_string(diff_criteria_path.clone())?,
 142            run_directory_path: run_dir.to_path_buf(),
 143            log_prefix: name,
 144        })
 145    }
 146
 147    pub fn set_repetition_number(&mut self, repetition_number: u32) {
 148        if repetition_number > 0 {
 149            self.name = format!("{}-{}", self.name, repetition_number);
 150        }
 151    }
 152
 153    pub fn example_output_directory(&self) -> PathBuf {
 154        self.run_directory_path.join(&self.name)
 155    }
 156
 157    pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
 158        self.log_prefix = format!(
 159            "{}{:<width$}\x1b[0m | ",
 160            color,
 161            self.name,
 162            width = name_width
 163        );
 164    }
 165
 166    pub fn name_from_path(path: &Path) -> String {
 167        path.file_name().unwrap().to_string_lossy().to_string()
 168    }
 169
 170    pub fn worktree_path(&self) -> PathBuf {
 171        Path::new(WORKTREES_DIR)
 172            .canonicalize()
 173            .context(format!("No such directory {WORKTREES_DIR}"))
 174            .unwrap()
 175            .join(&self.name)
 176            .join(self.base.repo_name())
 177    }
 178
 179    /// Set up the example by checking out the specified Git revision
 180    pub async fn setup(&mut self) -> Result<()> {
 181        let repo_path = repo_path_for_url(&self.base.url);
 182
 183        let revision_exists = run_git(
 184            &repo_path,
 185            &["rev-parse", &format!("{}^{{commit}}", self.base.revision)],
 186        )
 187        .await
 188        .is_ok();
 189
 190        if !revision_exists {
 191            println!(
 192                "{}Fetching revision {}",
 193                self.log_prefix, &self.base.revision
 194            );
 195            run_git(
 196                &repo_path,
 197                &["fetch", "--depth", "1", "origin", &self.base.revision],
 198            )
 199            .await?;
 200        }
 201
 202        let worktree_path = self.worktree_path();
 203
 204        if worktree_path.is_dir() {
 205            println!("{}Resetting existing worktree", self.log_prefix);
 206
 207            // TODO: consider including "-x" to remove ignored files. The downside of this is that
 208            // it will also remove build artifacts, and so prevent incremental reuse there.
 209            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
 210            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
 211            run_git(&worktree_path, &["checkout", &self.base.revision]).await?;
 212        } else {
 213            println!("{}Creating worktree", self.log_prefix);
 214
 215            let worktree_path_string = worktree_path.to_string_lossy().to_string();
 216
 217            run_git(
 218                &repo_path,
 219                &[
 220                    "worktree",
 221                    "add",
 222                    "-f",
 223                    &worktree_path_string,
 224                    &self.base.revision,
 225                ],
 226            )
 227            .await?;
 228        }
 229
 230        std::fs::create_dir_all(self.example_output_directory())?;
 231
 232        Ok(())
 233    }
 234
 235    pub fn run(
 236        &self,
 237        model: Arc<dyn LanguageModel>,
 238        app_state: Arc<AgentAppState>,
 239        cx: &mut App,
 240    ) -> Task<Result<RunOutput>> {
 241        let project = Project::local(
 242            app_state.client.clone(),
 243            app_state.node_runtime.clone(),
 244            app_state.user_store.clone(),
 245            app_state.languages.clone(),
 246            Arc::new(DapRegistry::default()),
 247            app_state.fs.clone(),
 248            None,
 249            cx,
 250        );
 251
 252        let worktree_path = self.worktree_path();
 253        let worktree = project.update(cx, |project, cx| {
 254            project.create_worktree(&worktree_path, true, cx)
 255        });
 256
 257        let tools = cx.new(|_| ToolWorkingSet::default());
 258        let thread_store =
 259            ThreadStore::load(project.clone(), tools, app_state.prompt_builder.clone(), cx);
 260        let this = self.clone();
 261
 262        cx.spawn(async move |cx| {
 263            let worktree = worktree.await?;
 264
 265            // Wait for worktree scan to finish before choosing a file to open.
 266            worktree
 267                .update(cx, |worktree, _cx| {
 268                    worktree.as_local().unwrap().scan_complete()
 269                })?
 270                .await;
 271
 272            let lsp = if this.base.require_lsp {
 273                let language_extension = this.base.language_extension.as_deref().context(
 274                    "language_extension field is required in base.toml when `require_lsp == true`",
 275                )?;
 276
 277                // Open a file that matches the language to cause LSP to start.
 278                let language_file = worktree.read_with(cx, |worktree, _cx| {
 279                    worktree
 280                        .files(false, 0)
 281                        .find_map(|e| {
 282                            if e.path.clone().extension().and_then(|ext| ext.to_str())
 283                                == Some(language_extension)
 284                            {
 285                                Some(ProjectPath {
 286                                    worktree_id: worktree.id(),
 287                                    path: e.path.clone(),
 288                                })
 289                            } else {
 290                                None
 291                            }
 292                        })
 293                        .context("Failed to find a file for example language")
 294                })??;
 295
 296                let open_language_file_buffer_task = project.update(cx, |project, cx| {
 297                    project.open_buffer(language_file.clone(), cx)
 298                })?;
 299
 300                let language_file_buffer = open_language_file_buffer_task.await?;
 301
 302                let lsp_open_handle = project.update(cx, |project, cx| {
 303                    project.register_buffer_with_language_servers(&language_file_buffer, cx)
 304                })?;
 305
 306                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 307
 308                Some((lsp_open_handle, language_file_buffer))
 309            } else {
 310                None
 311            };
 312
 313            let diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
 314            if diagnostics_before.is_some() && !this.base.allow_preexisting_diagnostics {
 315                return Err(anyhow!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`"));
 316            }
 317
 318            if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
 319                return Err(anyhow!("Setup only mode"));
 320            }
 321
 322            let thread_store = thread_store.await?;
 323            let thread =
 324                thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
 325            let last_request = Rc::new(RefCell::new(None));
 326
 327            thread.update(cx, |thread, _cx| {
 328                let mut request_count = 0;
 329                let example_dir_path = this.example_output_directory();
 330
 331                let last_request = Rc::clone(&last_request);
 332                thread.set_request_callback(move |request, response_events| {
 333                    *last_request.borrow_mut() = Some(request.clone());
 334
 335                    request_count += 1;
 336                    let messages_file_path = example_dir_path.join(format!("{request_count}.messages.md"));
 337                    let last_messages_file_path = example_dir_path.join("last.messages.md");
 338                    let request_markdown = RequestMarkdown::new(request);
 339                    let response_events_markdown = response_events_to_markdown(response_events);
 340
 341                    let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
 342                    fs::write(messages_file_path, messages.clone()).expect("failed to write messages file");
 343                    fs::write(last_messages_file_path, messages).expect("failed to write last messages file");
 344
 345                    if request_count == 1 {
 346                        let tools_file_path = example_dir_path.join("tools.md");
 347                        fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
 348                    }
 349                });
 350            })?;
 351
 352            let tool_metrics = Arc::new(Mutex::new(ToolMetrics::default()));
 353
 354            let (thread_event_tx, mut thread_event_rx) = mpsc::unbounded();
 355
 356            let subscription = cx.subscribe(&thread, move |_thread, event: &ThreadEvent, _cx| {
 357                thread_event_tx.unbounded_send(event.clone()).log_err();
 358            });
 359
 360            let event_handler_task = cx.spawn({
 361                let log_prefix = this.log_prefix.clone();
 362                let tool_metrics = tool_metrics.clone();
 363                let thread = thread.downgrade();
 364                async move |cx| {
 365                    loop {
 366                        let event = select_biased! {
 367                            event = thread_event_rx.next() => event,
 368                            _ = cx.background_executor().timer(THREAD_EVENT_TIMEOUT).fuse() => {
 369                                return Err(anyhow!("Agentic loop stalled - waited {:?} without any events", THREAD_EVENT_TIMEOUT));
 370                            }
 371                        };
 372                        let Some(event) = event else {
 373                            return Err(anyhow!("ThreadEvent channel ended early"));
 374                        };
 375
 376                        match event {
 377                            ThreadEvent::Stopped(reason) => match reason {
 378                                Ok(StopReason::EndTurn) => {
 379                                    return Ok(());
 380                                }
 381                                Ok(StopReason::MaxTokens) => {
 382                                    return Err(anyhow!("Exceeded maximum tokens"));
 383                                }
 384                                Ok(StopReason::ToolUse) => {
 385                                    if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 386                                        println!("{}StopReason: Tool use", log_prefix);
 387                                    }
 388                                }
 389                                Err(error) => {
 390                                    return Err(anyhow!(error.clone()));
 391                                }
 392                            },
 393                            ThreadEvent::ShowError(thread_error) => {
 394                                break Err(anyhow!(thread_error.clone()));
 395                            }
 396                            ThreadEvent::StreamedAssistantText(_, _)| ThreadEvent::StreamedAssistantThinking(_, _) | ThreadEvent::UsePendingTools { .. } => {
 397                            }
 398                            ThreadEvent::ToolFinished {
 399                                tool_use_id,
 400                                pending_tool_use,
 401                                ..
 402                            } => {
 403                                thread.update(cx, |thread, _cx| {
 404                                    if let Some(tool_use) = pending_tool_use {
 405                                        let mut tool_metrics = tool_metrics.lock().unwrap();
 406                                        if let Some(tool_result) = thread.tool_result(&tool_use_id) {
 407                                            let message = if tool_result.is_error {
 408                                                format!("TOOL FAILED: {}", tool_use.name)
 409                                            } else {
 410                                                format!("TOOL FINISHED: {}", tool_use.name)
 411                                            };
 412                                            println!("{log_prefix}{message}");
 413                                            tool_metrics.insert(tool_result.tool_name.clone(), !tool_result.is_error);
 414                                        } else {
 415                                            let message = format!("TOOL FINISHED WITHOUT RESULT: {}", tool_use.name);
 416                                            println!("{log_prefix}{message}");
 417                                            tool_metrics.insert(tool_use.name.clone(), true);
 418                                        }
 419                                    }
 420                                })?;
 421                            }
 422                            ThreadEvent::ToolConfirmationNeeded => {
 423                                panic!("{}Bug: Tool confirmation should not be required in eval", log_prefix);
 424                            },
 425                            ThreadEvent::StreamedCompletion |
 426                            ThreadEvent::MessageAdded(_) |
 427                            ThreadEvent::MessageEdited(_) |
 428                            ThreadEvent::MessageDeleted(_) |
 429                            ThreadEvent::SummaryChanged |
 430                            ThreadEvent::SummaryGenerated |
 431                            ThreadEvent::CheckpointChanged |
 432                            ThreadEvent::UsageUpdated(_) => {
 433                                if std::env::var("ZED_EVAL_DEBUG").is_ok() {
 434                                    println!("{}Event: {:#?}", log_prefix, event);
 435                                }
 436                            }
 437                        }
 438                    }
 439                }
 440            });
 441
 442            thread.update(cx, |thread, cx| {
 443                let context = vec![];
 444                thread.insert_user_message(this.prompt.clone(), context, None, cx);
 445                thread.send_to_model(model, cx);
 446            })?;
 447
 448            event_handler_task.await?;
 449
 450            println!("{}Stopped", this.log_prefix);
 451
 452            if let Some((_, language_file_buffer)) = lsp.as_ref() {
 453                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 454            }
 455
 456            println!("{}Getting repository diff", this.log_prefix);
 457            let repository_diff = this.repository_diff().await?;
 458
 459            let example_output_dir = this.example_output_directory();
 460            let repository_diff_path = example_output_dir.join("patch.diff");
 461            let mut repository_diff_output_file = File::create(&repository_diff_path)?;
 462            writeln!(&mut repository_diff_output_file, "{}", &repository_diff).log_err();
 463
 464            println!("{}Getting diagnostics", this.log_prefix);
 465            let diagnostics_after = cx
 466                .update(move |cx| {
 467                    cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 468                })?
 469                .await?;
 470            println!("{}Got diagnostics", this.log_prefix);
 471
 472            let Some(last_request) = last_request.borrow_mut().take() else {
 473                return Err(anyhow!("No requests ran."));
 474            };
 475
 476            drop(subscription);
 477            drop(lsp);
 478
 479            if let Some(diagnostics_before) = &diagnostics_before {
 480                fs::write(example_output_dir.join("diagnostics_before.txt"), diagnostics_before)?;
 481            }
 482
 483            if let Some(diagnostics_after) = &diagnostics_after {
 484                fs::write(example_output_dir.join("diagnostics_after.txt"), diagnostics_after)?;
 485            }
 486
 487
 488            thread.update(cx, |thread, _cx| {
 489                let response_count = thread
 490                    .messages()
 491                    .filter(|message| message.role == language_model::Role::Assistant)
 492                    .count();
 493                RunOutput {
 494                    repository_diff,
 495                    ran_diagnostics_check: this.base.require_lsp,
 496                    diagnostics_before,
 497                    diagnostics_after,
 498                    response_count,
 499                    token_usage: thread.cumulative_token_usage(),
 500                    tool_metrics: tool_metrics.lock().unwrap().clone(),
 501                    last_request,
 502                }
 503            })
 504        })
 505    }
 506
 507    async fn judge_diff(
 508        &self,
 509        model: Arc<dyn LanguageModel>,
 510        run_output: &RunOutput,
 511        judge_number: u32,
 512        cx: &AsyncApp,
 513    ) -> Result<(String, JudgeResponse)> {
 514        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 515        let judge_diff_prompt_name = "judge_diff_prompt";
 516        let mut hbs = Handlebars::new();
 517        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)?;
 518
 519        let diff_prompt = hbs.render(
 520            judge_diff_prompt_name,
 521            &JudgeDiffInput {
 522                repository_diff: run_output.repository_diff.clone(),
 523                ran_diagnostics_check: run_output.ran_diagnostics_check,
 524                diagnostics_before: run_output.diagnostics_before.clone(),
 525                diagnostics_after: run_output.diagnostics_after.clone(),
 526                criteria: self.diff_criteria.clone(),
 527            },
 528        )?;
 529
 530        let request = LanguageModelRequest {
 531            thread_id: None,
 532            prompt_id: None,
 533            messages: vec![LanguageModelRequestMessage {
 534                role: Role::User,
 535                content: vec![MessageContent::Text(diff_prompt)],
 536                cache: false,
 537            }],
 538            temperature: None,
 539            tools: Vec::new(),
 540            stop: Vec::new(),
 541        };
 542
 543        let diff_response = send_language_model_request(model, request, cx).await?;
 544        let diff_output = JudgeResponse::parse(&diff_response)?;
 545
 546        println!(
 547            "{}Judge #{judge_number} - Diff score: {}",
 548            self.log_prefix, diff_output.score
 549        );
 550
 551        Ok((diff_response, diff_output))
 552    }
 553
 554    async fn judge_thread(
 555        &self,
 556        model: Arc<dyn LanguageModel>,
 557        run_output: &RunOutput,
 558        judge_number: u32,
 559        cx: &AsyncApp,
 560    ) -> Result<(String, Option<JudgeResponse>)> {
 561        if let Some(criteria) = self.thread_criteria.clone() {
 562            let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 563            let judge_thread_prompt_name = "judge_thread_prompt";
 564            let mut hbs = Handlebars::new();
 565            hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)?;
 566
 567            let request_markdown = RequestMarkdown::new(&run_output.last_request);
 568            let thread_prompt = hbs.render(
 569                judge_thread_prompt_name,
 570                &JudgeThreadInput {
 571                    messages: request_markdown.messages,
 572                    criteria,
 573                },
 574            )?;
 575
 576            let request = LanguageModelRequest {
 577                thread_id: None,
 578                prompt_id: None,
 579                messages: vec![LanguageModelRequestMessage {
 580                    role: Role::User,
 581                    content: vec![MessageContent::Text(thread_prompt)],
 582                    cache: false,
 583                }],
 584                temperature: None,
 585                tools: Vec::new(),
 586                stop: Vec::new(),
 587            };
 588
 589            let thread_response = send_language_model_request(model, request, cx).await?;
 590            let thread_output = JudgeResponse::parse(&thread_response)?;
 591
 592            println!(
 593                "{}Judge #{judge_number} - Thread score: {}",
 594                self.log_prefix, thread_output.score
 595            );
 596
 597            Ok((thread_response, Some(thread_output)))
 598        } else {
 599            let msg = "There were no criteria specified for this thread, so this example was not judged on its thread.".to_string();
 600            Ok((msg, None))
 601        }
 602    }
 603
 604    pub async fn judge(
 605        &self,
 606        model: Arc<dyn LanguageModel>,
 607        run_output: &RunOutput,
 608        judge_number: u32,
 609        cx: &AsyncApp,
 610    ) -> Result<JudgeOutput> {
 611        let mut output_file = File::create(
 612            self.example_output_directory()
 613                .join(format!("judge_{}.md", judge_number)),
 614        )
 615        .expect("failed to create judge.md");
 616
 617        println!("{}Running judge #{judge_number}", self.log_prefix);
 618
 619        let diff_task = self.judge_diff(model.clone(), &run_output, judge_number, cx);
 620        let thread_task = self.judge_thread(model.clone(), &run_output, judge_number, cx);
 621
 622        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 623
 624        let (diff_response, diff_output) = diff_result?;
 625        let (thread_response, thread_output) = thread_result?;
 626
 627        writeln!(
 628            &mut output_file,
 629            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 630        )
 631        .log_err();
 632
 633        Ok(JudgeOutput {
 634            thread: thread_output,
 635            diff: diff_output,
 636        })
 637    }
 638
 639    async fn repository_diff(&self) -> Result<String> {
 640        let worktree_path = self.worktree_path();
 641        run_git(&worktree_path, &["add", "."]).await?;
 642        run_git(&worktree_path, &["diff", "--staged"]).await
 643    }
 644}
 645
 646fn wait_for_lang_server(
 647    project: &Entity<Project>,
 648    buffer: &Entity<Buffer>,
 649    log_prefix: String,
 650    cx: &mut AsyncApp,
 651) -> Task<Result<()>> {
 652    println!("{}⏵ Waiting for language server", log_prefix);
 653
 654    let (mut tx, mut rx) = mpsc::channel(1);
 655
 656    let lsp_store = project
 657        .update(cx, |project, _| project.lsp_store())
 658        .unwrap();
 659
 660    let has_lang_server = buffer
 661        .update(cx, |buffer, cx| {
 662            lsp_store.update(cx, |lsp_store, cx| {
 663                lsp_store
 664                    .language_servers_for_local_buffer(&buffer, cx)
 665                    .next()
 666                    .is_some()
 667            })
 668        })
 669        .unwrap_or(false);
 670
 671    if has_lang_server {
 672        project
 673            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 674            .unwrap()
 675            .detach();
 676    }
 677
 678    let subscriptions =
 679        [
 680            cx.subscribe(&lsp_store, {
 681                let log_prefix = log_prefix.clone();
 682                move |_, event, _| match event {
 683                    project::LspStoreEvent::LanguageServerUpdate {
 684                        message:
 685                            client::proto::update_language_server::Variant::WorkProgress(
 686                                LspWorkProgress {
 687                                    message: Some(message),
 688                                    ..
 689                                },
 690                            ),
 691                        ..
 692                    } => println!("{}{message}", log_prefix),
 693                    _ => {}
 694                }
 695            }),
 696            cx.subscribe(&project, {
 697                let buffer = buffer.clone();
 698                move |project, event, cx| match event {
 699                    project::Event::LanguageServerAdded(_, _, _) => {
 700                        let buffer = buffer.clone();
 701                        project
 702                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 703                            .detach();
 704                    }
 705                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 706                        tx.try_send(()).ok();
 707                    }
 708                    _ => {}
 709                }
 710            }),
 711        ];
 712
 713    cx.spawn(async move |cx| {
 714        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 715        let result = futures::select! {
 716            _ = rx.next() => {
 717                println!("{}⚑ Language server idle", log_prefix);
 718                anyhow::Ok(())
 719            },
 720            _ = timeout.fuse() => {
 721                Err(anyhow!("LSP wait timed out after 5 minutes"))
 722            }
 723        };
 724        drop(subscriptions);
 725        result
 726    })
 727}
 728
 729async fn query_lsp_diagnostics(
 730    project: Entity<Project>,
 731    cx: &mut AsyncApp,
 732) -> Result<Option<String>> {
 733    let paths_with_diagnostics = project.update(cx, |project, cx| {
 734        project
 735            .diagnostic_summaries(true, cx)
 736            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 737            .map(|(project_path, _, _)| project_path)
 738            .collect::<Vec<_>>()
 739    })?;
 740
 741    if paths_with_diagnostics.is_empty() {
 742        return Ok(None);
 743    }
 744
 745    let mut output = String::new();
 746    for project_path in paths_with_diagnostics {
 747        let buffer = project
 748            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 749            .await?;
 750        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 751
 752        for (_, group) in snapshot.diagnostic_groups(None) {
 753            let entry = &group.entries[group.primary_ix];
 754            let range = entry.range.to_point(&snapshot);
 755            let severity = match entry.diagnostic.severity {
 756                DiagnosticSeverity::ERROR => "error",
 757                DiagnosticSeverity::WARNING => "warning",
 758                _ => continue,
 759            };
 760
 761            writeln!(
 762                output,
 763                "{} at line {}: {}",
 764                severity,
 765                range.start.row + 1,
 766                entry.diagnostic.message
 767            )?;
 768        }
 769    }
 770    anyhow::Ok(Some(output))
 771}
 772
 773impl JudgeResponse {
 774    fn parse(response: &str) -> Result<Self> {
 775        let analysis = get_tag("analysis", response)?.to_string();
 776        let score = get_tag("score", response)?
 777            .parse()
 778            .context("error parsing score")?;
 779
 780        Ok(Self { analysis, score })
 781    }
 782}
 783
 784fn get_tag(name: &'static str, response: &str) -> Result<String> {
 785    let start_tag = format!("<{}>", name);
 786    let end_tag = format!("</{}>", name);
 787
 788    let start_ix = response
 789        .find(&start_tag)
 790        .context(format!("{} start tag not found", name))?;
 791    let content_start_ix = start_ix + start_tag.len();
 792
 793    let end_ix = content_start_ix
 794        + response[content_start_ix..]
 795            .find(&end_tag)
 796            .context(format!("{} end tag not found", name))?;
 797
 798    let content = response[content_start_ix..end_ix].trim().unindent();
 799
 800    anyhow::Ok(content)
 801}
 802
 803pub fn repo_path_for_url(repo_url: &str) -> PathBuf {
 804    let repo_name = repo_url
 805        .trim_start_matches("https://")
 806        .replace(|c: char| !c.is_alphanumeric(), "-");
 807    Path::new(REPOS_DIR)
 808        .canonicalize()
 809        .context(format!("No such directory {REPOS_DIR}"))
 810        .unwrap()
 811        .join(repo_name)
 812}
 813
 814pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 815    let output = new_smol_command("git")
 816        .current_dir(repo_path)
 817        .args(args)
 818        .output()
 819        .await?;
 820
 821    if output.status.success() {
 822        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 823    } else {
 824        Err(anyhow!(
 825            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 826            args.join(" "),
 827            repo_path.display(),
 828            output.status,
 829            String::from_utf8_lossy(&output.stderr),
 830            String::from_utf8_lossy(&output.stdout),
 831        ))
 832    }
 833}
 834
 835pub async fn send_language_model_request(
 836    model: Arc<dyn LanguageModel>,
 837    request: LanguageModelRequest,
 838    cx: &AsyncApp,
 839) -> anyhow::Result<String> {
 840    match model.stream_completion_text(request, &cx).await {
 841        Ok(mut stream) => {
 842            let mut full_response = String::new();
 843            while let Some(chunk_result) = stream.stream.next().await {
 844                match chunk_result {
 845                    Ok(chunk_str) => {
 846                        full_response.push_str(&chunk_str);
 847                    }
 848                    Err(err) => {
 849                        return Err(anyhow!(
 850                            "Error receiving response from language model: {err}"
 851                        ));
 852                    }
 853                }
 854            }
 855            Ok(full_response)
 856        }
 857        Err(err) => Err(anyhow!(
 858            "Failed to get response from language model. Error was: {err}"
 859        )),
 860    }
 861}
 862
 863struct RequestMarkdown {
 864    tools: String,
 865    messages: String,
 866}
 867
 868impl RequestMarkdown {
 869    fn new(request: &LanguageModelRequest) -> Self {
 870        let mut tools = String::new();
 871        let mut messages = String::new();
 872        let mut assistant_message_number: u32 = 1;
 873
 874        // Print the tools
 875        if !request.tools.is_empty() {
 876            for tool in &request.tools {
 877                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 878                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 879                write!(
 880                    &mut tools,
 881                    "{}\n",
 882                    MarkdownString::code_block("json", &format!("{:#}", tool.input_schema))
 883                )
 884                .unwrap();
 885            }
 886        }
 887
 888        // Print the messages
 889        for message in &request.messages {
 890            match message.role {
 891                Role::System => messages.push_str("# ⚙️ SYSTEM\n\n"),
 892                Role::User => messages.push_str("# 👤 USER\n\n"),
 893                Role::Assistant => {
 894                    messages.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 895                    assistant_message_number += 1;
 896                }
 897            };
 898
 899            for content in &message.content {
 900                match content {
 901                    MessageContent::Text(text) => {
 902                        messages.push_str(text);
 903                        messages.push_str("\n\n");
 904                    }
 905                    MessageContent::Image(_) => {
 906                        messages.push_str("[IMAGE DATA]\n\n");
 907                    }
 908                    MessageContent::Thinking { text, signature } => {
 909                        messages.push_str("**Thinking**:\n\n");
 910                        if let Some(sig) = signature {
 911                            messages.push_str(&format!("Signature: {}\n\n", sig));
 912                        }
 913                        messages.push_str(text);
 914                        messages.push_str("\n");
 915                    }
 916                    MessageContent::RedactedThinking(items) => {
 917                        messages.push_str(&format!(
 918                            "**Redacted Thinking**: {} item(s)\n\n",
 919                            items.len()
 920                        ));
 921                    }
 922                    MessageContent::ToolUse(tool_use) => {
 923                        messages.push_str(&format!(
 924                            "**Tool Use**: {} (ID: {})\n",
 925                            tool_use.name, tool_use.id
 926                        ));
 927                        messages.push_str(&format!(
 928                            "{}\n",
 929                            MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
 930                        ));
 931                    }
 932                    MessageContent::ToolResult(tool_result) => {
 933                        messages.push_str(&format!(
 934                            "**Tool Result**: {} (ID: {})\n\n",
 935                            tool_result.tool_name, tool_result.tool_use_id
 936                        ));
 937                        if tool_result.is_error {
 938                            messages.push_str("**ERROR:**\n");
 939                        }
 940                        messages.push_str(&format!("{}\n\n", tool_result.content));
 941                    }
 942                }
 943            }
 944        }
 945
 946        Self { tools, messages }
 947    }
 948}
 949
 950fn response_events_to_markdown(
 951    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 952) -> String {
 953    let mut response = String::new();
 954    // Print the response events if any
 955    response.push_str("# Response\n\n");
 956    let mut text_buffer = String::new();
 957    let mut thinking_buffer = String::new();
 958
 959    let flush_buffers =
 960        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 961            if !text_buffer.is_empty() {
 962                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 963                text_buffer.clear();
 964            }
 965            if !thinking_buffer.is_empty() {
 966                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 967                thinking_buffer.clear();
 968            }
 969        };
 970
 971    for event in response_events {
 972        match event {
 973            Ok(LanguageModelCompletionEvent::Text(text)) => {
 974                text_buffer.push_str(text);
 975            }
 976            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
 977                thinking_buffer.push_str(text);
 978            }
 979            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
 980                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 981                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
 982            }
 983            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 984                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 985                response.push_str(&format!(
 986                    "**Tool Use**: {} (ID: {})\n",
 987                    tool_use.name, tool_use.id
 988                ));
 989                response.push_str(&format!(
 990                    "{}\n",
 991                    MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
 992                ));
 993            }
 994            Ok(
 995                LanguageModelCompletionEvent::UsageUpdate(_)
 996                | LanguageModelCompletionEvent::StartMessage { .. },
 997            ) => {}
 998            Err(error) => {
 999                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1000                response.push_str(&format!("**Error**: {}\n\n", error));
1001            }
1002        }
1003    }
1004
1005    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1006
1007    response
1008}
1009
1010#[cfg(test)]
1011mod test {
1012    use super::*;
1013    use handlebars::Handlebars;
1014
1015    #[test]
1016    fn test_parse_judge_output() {
1017        let response = r#"
1018            <analysis>The model did a good job but there were still compilations errors.</analysis>
1019            <score>3</score>
1020        "#
1021        .unindent();
1022
1023        let output = JudgeResponse::parse(&response).unwrap();
1024        assert_eq!(
1025            output.analysis,
1026            "The model did a good job but there were still compilations errors."
1027        );
1028        assert_eq!(output.score, 3);
1029
1030        let response = r#"
1031            Text around ignored
1032
1033            <analysis>
1034                Failed to compile:
1035                - Error 1
1036                - Error 2
1037            </analysis>
1038
1039            <score>1</score>
1040        "#
1041        .unindent();
1042
1043        let output = JudgeResponse::parse(&response).unwrap();
1044        assert_eq!(output.analysis, "Failed to compile:\n- Error 1\n- Error 2");
1045        assert_eq!(output.score, 1);
1046    }
1047
1048    #[test]
1049    fn test_judge_prompt_with_diagnostics() {
1050        // Case 1: Both diagnostics before and after are present
1051        let input = JudgeDiffInput {
1052            repository_diff: "diff content goes here".to_string(),
1053            ran_diagnostics_check: true,
1054            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1055            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1056            criteria: "Fix all bugs".to_string(),
1057        };
1058
1059        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1060
1061        let expected_diagnostics_section = r#"
1062            Take into account the diagnostics before and after applying the change:
1063
1064            <diagnostics_before>
1065            Error at line 10: variable not found
1066            </diagnostics_before>
1067
1068            <diagnostics_after>
1069            Error at line 15: missing semicolon
1070            </diagnostics_after>
1071            "#
1072        .unindent();
1073
1074        assert!(rendered.contains(&expected_diagnostics_section));
1075    }
1076
1077    #[test]
1078    fn test_judge_prompt_with_empty_diagnostics() {
1079        // Case 2: Diagnostics check run but no diagnostics found
1080        let input = JudgeDiffInput {
1081            repository_diff: "diff content goes here".to_string(),
1082            ran_diagnostics_check: true,
1083            diagnostics_before: None,
1084            diagnostics_after: None,
1085            criteria: "Fix all bugs".to_string(),
1086        };
1087
1088        let rendered = templates().render(JUDGE_PROMPT_NAME, &input).unwrap();
1089
1090        let expected_diagnostics_section = r#"
1091            Take into account the diagnostics before and after applying the change:
1092
1093            <diagnostics_before>
1094            No diagnostics before applying the edits.
1095            </diagnostics_before>
1096
1097            <diagnostics_after>
1098            No diagnostics after applying the edits.
1099            </diagnostics_after>
1100            "#
1101        .unindent();
1102
1103        assert!(rendered.contains(&expected_diagnostics_section));
1104    }
1105
1106    #[test]
1107    fn test_judge_prompt_with_mixed_diagnostics() {
1108        let templates = templates();
1109
1110        // Case 3: Before diagnostics present, after diagnostics absent
1111        let input = JudgeDiffInput {
1112            repository_diff: "diff content goes here".to_string(),
1113            ran_diagnostics_check: true,
1114            diagnostics_before: Some("Error at line 10: variable not found".to_string()),
1115            diagnostics_after: None,
1116            criteria: "Fix all bugs".to_string(),
1117        };
1118
1119        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1120
1121        let expected_diagnostics_section = r#"
1122            Take into account the diagnostics before and after applying the change:
1123
1124            <diagnostics_before>
1125            Error at line 10: variable not found
1126            </diagnostics_before>
1127
1128            <diagnostics_after>
1129            No diagnostics after applying the edits.
1130            </diagnostics_after>
1131            "#
1132        .unindent();
1133
1134        assert!(rendered.contains(&expected_diagnostics_section));
1135
1136        // Case 4: Before diagnostics absent, after diagnostics present
1137        let input = JudgeDiffInput {
1138            repository_diff: "diff content goes here".to_string(),
1139            ran_diagnostics_check: true,
1140            diagnostics_before: None,
1141            diagnostics_after: Some("Error at line 15: missing semicolon".to_string()),
1142            criteria: "Fix all bugs".to_string(),
1143        };
1144
1145        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1146
1147        let expected_diagnostics_section = r#"
1148            Take into account the diagnostics before and after applying the change:
1149
1150            <diagnostics_before>
1151            No diagnostics before applying the edits.
1152            </diagnostics_before>
1153
1154            <diagnostics_after>
1155            Error at line 15: missing semicolon
1156            </diagnostics_after>
1157            "#
1158        .unindent();
1159
1160        assert!(rendered.contains(&expected_diagnostics_section));
1161    }
1162
1163    #[test]
1164    fn test_judge_prompt_without_diagnostics() {
1165        let templates = templates();
1166
1167        // Case 5: No diagnostics check run
1168        let input = JudgeDiffInput {
1169            repository_diff: "diff content goes here".to_string(),
1170            ran_diagnostics_check: false,
1171            diagnostics_before: None,
1172            diagnostics_after: None,
1173            criteria: "Fix all bugs".to_string(),
1174        };
1175
1176        let rendered = templates.render(JUDGE_PROMPT_NAME, &input).unwrap();
1177
1178        // Check for the message when no diagnostics were performed
1179        let diagnostics_message = "No diagnostic checks were performed.";
1180
1181        assert!(rendered.contains(diagnostics_message));
1182        assert!(!rendered.contains("<diagnostics_before>"));
1183        assert!(!rendered.contains("<diagnostics_after>"));
1184    }
1185
1186    const JUDGE_PROMPT_NAME: &str = "judge_prompt";
1187
1188    fn templates() -> Handlebars<'static> {
1189        let mut judge_prompt = include_str!("judge_diff_prompt.hbs").to_string();
1190        language::LineEnding::normalize(&mut judge_prompt);
1191        let mut handlebars = Handlebars::new();
1192        handlebars
1193            .register_template_string(JUDGE_PROMPT_NAME, judge_prompt)
1194            .unwrap();
1195        handlebars
1196    }
1197}