example.rs

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