instance.rs

   1use agent::ContextServerRegistry;
   2use agent_client_protocol as acp;
   3use anyhow::{Context as _, Result, anyhow, bail};
   4use client::proto::LspWorkProgress;
   5use futures::channel::mpsc;
   6use futures::future::Shared;
   7use futures::{FutureExt as _, StreamExt as _, future};
   8use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
   9use handlebars::Handlebars;
  10use language::{Buffer, DiagnosticSeverity, OffsetRangeExt as _};
  11use language_model::{
  12    LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
  13    LanguageModelRequestMessage, LanguageModelToolResultContent, MessageContent, Role, TokenUsage,
  14};
  15use project::{DiagnosticSummary, Project, ProjectPath, lsp_store::OpenLspBufferHandle};
  16use prompt_store::{ProjectContext, WorktreeContext};
  17use rand::{distr, prelude::*};
  18use serde::{Deserialize, Serialize};
  19use std::{
  20    fmt::Write as _,
  21    fs::{self, File},
  22    io::Write as _,
  23    path::{Path, PathBuf},
  24    rc::Rc,
  25    sync::{Arc, Mutex},
  26    time::Duration,
  27};
  28use unindent::Unindent as _;
  29use util::{ResultExt as _, command::new_smol_command, markdown::MarkdownCodeBlock};
  30
  31use crate::{
  32    AgentAppState, ToolMetrics,
  33    assertions::{AssertionsReport, RanAssertion, RanAssertionResult},
  34    example::{Example, ExampleContext, FailedAssertion, JudgeAssertion},
  35};
  36
  37pub const ZED_REPO_URL: &str = "https://github.com/zed-industries/zed.git";
  38
  39#[derive(Clone)]
  40pub struct ExampleInstance {
  41    pub thread: Rc<dyn Example>,
  42    pub name: String,
  43    pub run_directory: PathBuf,
  44    pub log_prefix: String,
  45    /// The repetition number for this example (0-based)
  46    /// When running multiple repetitions of the same example, each instance is assigned a unique repetition number.
  47    /// This affects the worktree path and log prefix to avoid clobbering results between runs.
  48    pub repetition: usize,
  49    pub repo_path: PathBuf,
  50    /// Path to the directory containing the requests and responses for the agentic loop
  51    worktrees_dir: PathBuf,
  52}
  53
  54#[derive(Debug, Serialize, Clone)]
  55pub struct RunOutput {
  56    pub repository_diff: String,
  57    pub diagnostic_summary_before: DiagnosticSummary,
  58    pub diagnostic_summary_after: DiagnosticSummary,
  59    pub diagnostics_before: Option<String>,
  60    pub diagnostics_after: Option<String>,
  61    pub token_usage: TokenUsage,
  62    pub tool_metrics: ToolMetrics,
  63    pub thread_markdown: String,
  64    pub programmatic_assertions: AssertionsReport,
  65}
  66
  67#[derive(Debug, Clone, Serialize, Deserialize)]
  68pub struct JudgeDiffInput {
  69    pub repository_diff: String,
  70    pub assertion: String,
  71}
  72
  73#[derive(Debug, Clone, Serialize, Deserialize)]
  74pub struct JudgeThreadInput {
  75    pub messages: String,
  76    pub assertion: String,
  77}
  78
  79#[derive(Debug, Clone, Serialize, Deserialize)]
  80pub struct JudgeOutput {
  81    pub thread: AssertionsReport,
  82    pub diff: AssertionsReport,
  83}
  84
  85impl ExampleInstance {
  86    pub fn new(
  87        thread: Rc<dyn Example>,
  88        repos_dir: &Path,
  89        run_dir: &Path,
  90        worktrees_dir: &Path,
  91        repetition: usize,
  92    ) -> Self {
  93        let name = thread.meta().name;
  94        let run_directory = run_dir.join(&name).join(repetition.to_string());
  95
  96        let repo_path = repo_path_for_url(repos_dir, &thread.meta().url);
  97
  98        Self {
  99            name,
 100            thread,
 101            log_prefix: String::new(),
 102            run_directory,
 103            repetition,
 104            repo_path,
 105            worktrees_dir: worktrees_dir.to_path_buf(),
 106        }
 107    }
 108
 109    pub fn repo_url(&self) -> String {
 110        self.thread.meta().url
 111    }
 112
 113    pub fn revision(&self) -> String {
 114        self.thread.meta().revision
 115    }
 116
 117    pub fn worktree_name(&self) -> String {
 118        format!("{}-{}", self.name, self.repetition)
 119    }
 120
 121    pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
 122        self.log_prefix = format!(
 123            "{}{:<width$}\x1b[0m | ",
 124            color,
 125            self.worktree_name(),
 126            width = name_width
 127        );
 128    }
 129
 130    /// Set up the example by checking out the specified Git revision
 131    pub async fn fetch(&mut self) -> Result<()> {
 132        let meta = self.thread.meta();
 133
 134        let revision_exists = run_git(
 135            &self.repo_path,
 136            &["rev-parse", &format!("{}^{{commit}}", &meta.revision)],
 137        )
 138        .await
 139        .is_ok();
 140
 141        if !revision_exists {
 142            println!("{}Fetching revision {}", self.log_prefix, &meta.revision);
 143            run_git(
 144                &self.repo_path,
 145                &["fetch", "--depth", "1", "origin", &meta.revision],
 146            )
 147            .await?;
 148        }
 149        Ok(())
 150    }
 151
 152    /// Set up the example by checking out the specified Git revision
 153    pub async fn setup(&mut self) -> Result<()> {
 154        let worktree_path = self.worktree_path();
 155        let meta = self.thread.meta();
 156        if worktree_path.is_dir() {
 157            println!("{}Resetting existing worktree", self.log_prefix);
 158
 159            // TODO: consider including "-x" to remove ignored files. The downside of this is that
 160            // it will also remove build artifacts, and so prevent incremental reuse there.
 161            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
 162            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
 163            run_git(&worktree_path, &["checkout", &meta.revision]).await?;
 164        } else {
 165            println!("{}Creating worktree", self.log_prefix);
 166
 167            let worktree_path_string = worktree_path.to_string_lossy().into_owned();
 168
 169            run_git(
 170                &self.repo_path,
 171                &[
 172                    "worktree",
 173                    "add",
 174                    "-f",
 175                    &worktree_path_string,
 176                    &meta.revision,
 177                ],
 178            )
 179            .await?;
 180        }
 181
 182        if meta.url == ZED_REPO_URL {
 183            std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
 184        }
 185
 186        std::fs::create_dir_all(&self.run_directory)?;
 187
 188        Ok(())
 189    }
 190
 191    pub fn worktree_path(&self) -> PathBuf {
 192        self.worktrees_dir
 193            .join(self.worktree_name())
 194            .join(self.thread.meta().repo_name())
 195    }
 196
 197    pub fn run(&self, app_state: Arc<AgentAppState>, cx: &mut App) -> Task<Result<RunOutput>> {
 198        let project = Project::local(
 199            app_state.client.clone(),
 200            app_state.node_runtime.clone(),
 201            app_state.user_store.clone(),
 202            app_state.languages.clone(),
 203            app_state.fs.clone(),
 204            None,
 205            cx,
 206        );
 207
 208        let worktree = project.update(cx, |project, cx| {
 209            project.create_worktree(self.worktree_path(), true, cx)
 210        });
 211
 212        let meta = self.thread.meta();
 213        let this = self.clone();
 214
 215        cx.spawn(async move |cx| {
 216            let worktree = worktree.await?;
 217
 218            // Wait for worktree scan to finish before choosing a file to open.
 219            worktree
 220                .update(cx, |worktree, _cx| {
 221                    worktree.as_local().unwrap().scan_complete()
 222                })?
 223                .await;
 224
 225            struct LanguageServerState {
 226                _lsp_open_handle: OpenLspBufferHandle,
 227                language_file_buffer: Entity<Buffer>,
 228            }
 229
 230            let mut diagnostics_before = None;
 231            let mut diagnostic_summary_before = DiagnosticSummary::default();
 232
 233            let lsp = if let Some(language_server) = &meta.language_server {
 234                // Open a file that matches the language to cause LSP to start.
 235                let language_file = worktree.read_with(cx, |worktree, _cx| {
 236                    worktree
 237                        .files(false, 0)
 238                        .find_map(|e| {
 239                            if e.path.clone().extension()
 240                                == Some(&language_server.file_extension)
 241                            {
 242                                Some(ProjectPath {
 243                                    worktree_id: worktree.id(),
 244                                    path: e.path.clone(),
 245                                })
 246                            } else {
 247                                None
 248                            }
 249                        })
 250                        .context("Failed to find a file for example language")
 251                })??;
 252
 253                let open_language_file_buffer_task = project.update(cx, |project, cx| {
 254                    project.open_buffer(language_file.clone(), cx)
 255                })?;
 256
 257                let language_file_buffer = open_language_file_buffer_task.await?;
 258
 259                let lsp_open_handle = project.update(cx, |project, cx| {
 260                    project.register_buffer_with_language_servers(&language_file_buffer, cx)
 261                })?;
 262
 263                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 264
 265                diagnostic_summary_before = project.read_with(cx, |project, cx| {
 266                      project.diagnostic_summary(false, cx)
 267                })?;
 268
 269                diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
 270                if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
 271                    anyhow::bail!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`");
 272                }
 273
 274                Some(LanguageServerState {
 275                    _lsp_open_handle: lsp_open_handle,
 276                    language_file_buffer,
 277                })
 278            } else {
 279                None
 280            };
 281
 282            anyhow::ensure!(std::env::var("ZED_EVAL_SETUP_ONLY").is_err(), "Setup only mode");
 283
 284            let last_diff_file_path = this.run_directory.join("last.diff");
 285
 286            // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
 287            // history using undo/redo.
 288            std::fs::write(&last_diff_file_path, "")?;
 289
 290            let thread = cx.update(|cx| {
 291                //todo: Do we want to load rules files here?
 292                let worktrees = project.read(cx).visible_worktrees(cx).map(|worktree| {
 293                    let root_name = worktree.read(cx).root_name_str().into();
 294                    let abs_path = worktree.read(cx).abs_path();
 295
 296                    WorktreeContext {
 297                        root_name,
 298                        abs_path,
 299                        rules_file: None,
 300                    }
 301                }).collect::<Vec<_>>();
 302                let project_context = cx.new(|_cx| ProjectContext::new(worktrees, vec![]));
 303                let context_server_registry = cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 304
 305                let thread = if let Some(json) = &meta.existing_thread_json {
 306                    let session_id = acp::SessionId::new(
 307                        rand::rng()
 308                            .sample_iter(&distr::Alphanumeric)
 309                            .take(7)
 310                            .map(char::from)
 311                            .collect::<String>(),
 312                    );
 313
 314                    let db_thread = agent::DbThread::from_json(json.as_bytes()).expect("Can't read serialized thread");
 315                    cx.new(|cx| agent::Thread::from_db(session_id, db_thread, project.clone(), project_context, context_server_registry, agent::Templates::new(), cx))
 316                } else {
 317                    cx.new(|cx| agent::Thread::new(project.clone(), project_context, context_server_registry, agent::Templates::new(), None, cx))
 318                };
 319
 320                thread.update(cx, |thread, cx| {
 321                    thread.add_default_tools(Rc::new(EvalThreadEnvironment {
 322                        project: project.clone(),
 323                    }), cx);
 324                    thread.set_profile(meta.profile_id.clone(), cx);
 325                    thread.set_model(
 326                        LanguageModelInterceptor::new(
 327                            LanguageModelRegistry::read_global(cx).default_model().expect("Missing model").model.clone(),
 328                            this.run_directory.clone(),
 329                            last_diff_file_path.clone(),
 330                            this.run_directory.join("last.messages.json"),
 331                            this.worktree_path(),
 332                            this.repo_url(),
 333                        ),
 334                        cx,
 335                    );
 336                });
 337
 338                thread
 339            }).unwrap();
 340
 341            let mut example_cx = ExampleContext::new(
 342                meta.clone(),
 343                this.log_prefix.clone(),
 344                thread.clone(),
 345                cx.clone(),
 346            );
 347            let result = this.thread.conversation(&mut example_cx).await;
 348
 349            if let Err(err) = result
 350                && !err.is::<FailedAssertion>() {
 351                    return Err(err);
 352                }
 353
 354            println!("{}Stopped", this.log_prefix);
 355
 356            println!("{}Getting repository diff", this.log_prefix);
 357            let repository_diff = Self::repository_diff(this.worktree_path(), &this.repo_url()).await?;
 358
 359            std::fs::write(last_diff_file_path, &repository_diff)?;
 360
 361
 362            let mut diagnostics_after = None;
 363            let mut diagnostic_summary_after = Default::default();
 364
 365            if let Some(language_server_state) = lsp {
 366                wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
 367
 368                println!("{}Getting diagnostics", this.log_prefix);
 369                diagnostics_after = cx
 370                    .update(|cx| {
 371                        let project = project.clone();
 372                        cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 373                    })?
 374                    .await?;
 375                println!("{}Got diagnostics", this.log_prefix);
 376
 377                diagnostic_summary_after = project.read_with(cx, |project, cx| {
 378                      project.diagnostic_summary(false, cx)
 379                })?;
 380
 381            }
 382
 383            if let Some(diagnostics_before) = &diagnostics_before {
 384                fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
 385            }
 386
 387            if let Some(diagnostics_after) = &diagnostics_after {
 388                fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
 389            }
 390
 391            thread.update(cx, |thread, _cx| {
 392                RunOutput {
 393                    repository_diff,
 394                    diagnostic_summary_before,
 395                    diagnostic_summary_after,
 396                    diagnostics_before,
 397                    diagnostics_after,
 398                    token_usage: thread.latest_request_token_usage().unwrap(),
 399                    tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
 400                    thread_markdown: thread.to_markdown(),
 401                    programmatic_assertions: example_cx.assertions,
 402                }
 403            })
 404        })
 405    }
 406
 407    async fn repository_diff(repository_path: PathBuf, repository_url: &str) -> Result<String> {
 408        run_git(&repository_path, &["add", "."]).await?;
 409        let mut diff_args = vec!["diff", "--staged"];
 410        if repository_url == ZED_REPO_URL {
 411            diff_args.push(":(exclude).rules");
 412        }
 413        run_git(&repository_path, &diff_args).await
 414    }
 415
 416    pub async fn judge(
 417        &self,
 418        model: Arc<dyn LanguageModel>,
 419        run_output: &RunOutput,
 420        cx: &AsyncApp,
 421    ) -> JudgeOutput {
 422        let mut output_file =
 423            File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
 424
 425        let diff_task = self.judge_diff(model.clone(), run_output, cx);
 426        let thread_task = self.judge_thread(model.clone(), run_output, cx);
 427
 428        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 429
 430        let (diff_response, diff_output) = diff_result;
 431        let (thread_response, thread_output) = thread_result;
 432
 433        writeln!(
 434            &mut output_file,
 435            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 436        )
 437        .log_err();
 438
 439        JudgeOutput {
 440            thread: thread_output,
 441            diff: diff_output,
 442        }
 443    }
 444
 445    async fn judge_diff(
 446        &self,
 447        model: Arc<dyn LanguageModel>,
 448        run_output: &RunOutput,
 449        cx: &AsyncApp,
 450    ) -> (String, AssertionsReport) {
 451        let diff_assertions = self.thread.diff_assertions();
 452
 453        if diff_assertions.is_empty() {
 454            return (
 455                "No diff assertions".to_string(),
 456                AssertionsReport::default(),
 457            );
 458        }
 459
 460        println!("{}Running diff judge", self.log_prefix);
 461
 462        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 463        let judge_diff_prompt_name = "judge_diff_prompt";
 464        let mut hbs = Handlebars::new();
 465        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
 466            .unwrap();
 467
 468        let to_prompt = |assertion: String| {
 469            hbs.render(
 470                judge_diff_prompt_name,
 471                &JudgeDiffInput {
 472                    repository_diff: run_output.repository_diff.clone(),
 473                    assertion,
 474                },
 475            )
 476            .unwrap()
 477        };
 478
 479        let (responses, report) = self
 480            .judge_assertions(model, diff_assertions, to_prompt, cx)
 481            .await;
 482
 483        println!(
 484            "{}Judge - Diff score: {}%",
 485            self.log_prefix,
 486            report.passed_percentage()
 487        );
 488
 489        (responses, report)
 490    }
 491
 492    async fn judge_thread(
 493        &self,
 494        model: Arc<dyn LanguageModel>,
 495        run_output: &RunOutput,
 496        cx: &AsyncApp,
 497    ) -> (String, AssertionsReport) {
 498        let thread_assertions = self.thread.thread_assertions();
 499
 500        if thread_assertions.is_empty() {
 501            return (
 502                "No thread assertions".to_string(),
 503                AssertionsReport::default(),
 504            );
 505        }
 506
 507        let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 508        let judge_thread_prompt_name = "judge_thread_prompt";
 509        let mut hbs = Handlebars::new();
 510        hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)
 511            .unwrap();
 512
 513        let complete_messages = &run_output.thread_markdown;
 514        let to_prompt = |assertion: String| {
 515            hbs.render(
 516                judge_thread_prompt_name,
 517                &JudgeThreadInput {
 518                    messages: complete_messages.clone(),
 519                    assertion,
 520                },
 521            )
 522            .unwrap()
 523        };
 524
 525        let (responses, report) = self
 526            .judge_assertions(model, thread_assertions, to_prompt, cx)
 527            .await;
 528
 529        println!(
 530            "{}Judge - Thread score: {}%",
 531            self.log_prefix,
 532            report.passed_percentage()
 533        );
 534
 535        (responses, report)
 536    }
 537
 538    async fn judge_assertions(
 539        &self,
 540        model: Arc<dyn LanguageModel>,
 541        assertions: Vec<JudgeAssertion>,
 542        to_prompt: impl Fn(String) -> String,
 543        cx: &AsyncApp,
 544    ) -> (String, AssertionsReport) {
 545        let assertions = assertions.into_iter().map(|assertion| {
 546            let request = LanguageModelRequest {
 547                thread_id: None,
 548                prompt_id: None,
 549                mode: None,
 550                intent: None,
 551                messages: vec![LanguageModelRequestMessage {
 552                    role: Role::User,
 553                    content: vec![MessageContent::Text(to_prompt(assertion.description))],
 554                    cache: false,
 555                    reasoning_details: None,
 556                }],
 557                temperature: None,
 558                tools: Vec::new(),
 559                tool_choice: None,
 560                stop: Vec::new(),
 561                thinking_allowed: true,
 562            };
 563
 564            let model = model.clone();
 565            let log_prefix = self.log_prefix.clone();
 566            async move {
 567                let response = send_language_model_request(model, request, cx).await;
 568
 569                let (response, result) = match response {
 570                    Ok(response) => (
 571                        response.clone(),
 572                        parse_assertion_result(&response).map_err(|err| err.to_string()),
 573                    ),
 574                    Err(err) => (err.to_string(), Err(err.to_string())),
 575                };
 576
 577                if result.is_ok() {
 578                    println!("{}{}", log_prefix, assertion.id);
 579                } else {
 580                    println!("{}{}", log_prefix, assertion.id);
 581                }
 582
 583                (
 584                    response,
 585                    RanAssertion {
 586                        id: assertion.id,
 587                        result,
 588                    },
 589                )
 590            }
 591        });
 592
 593        let mut responses = String::new();
 594        let mut report = AssertionsReport::default();
 595
 596        for (response, assertion) in future::join_all(assertions).await {
 597            writeln!(&mut responses, "# {}", assertion.id).unwrap();
 598            writeln!(&mut responses, "{}\n\n", response).unwrap();
 599            report.ran.push(assertion);
 600        }
 601
 602        (responses, report)
 603    }
 604}
 605
 606struct EvalThreadEnvironment {
 607    project: Entity<Project>,
 608}
 609
 610struct EvalTerminalHandle {
 611    terminal: Entity<acp_thread::Terminal>,
 612}
 613
 614impl agent::TerminalHandle for EvalTerminalHandle {
 615    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
 616        self.terminal.read_with(cx, |term, _cx| term.id().clone())
 617    }
 618
 619    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
 620        self.terminal
 621            .read_with(cx, |term, _cx| term.wait_for_exit())
 622    }
 623
 624    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
 625        self.terminal
 626            .read_with(cx, |term, cx| term.current_output(cx))
 627    }
 628
 629    fn kill(&self, cx: &AsyncApp) -> Result<()> {
 630        cx.update(|cx| {
 631            self.terminal.update(cx, |terminal, cx| {
 632                terminal.kill(cx);
 633            });
 634        })?;
 635        Ok(())
 636    }
 637}
 638
 639impl agent::ThreadEnvironment for EvalThreadEnvironment {
 640    fn create_terminal(
 641        &self,
 642        command: String,
 643        cwd: Option<PathBuf>,
 644        output_byte_limit: Option<u64>,
 645        cx: &mut AsyncApp,
 646    ) -> Task<Result<Rc<dyn agent::TerminalHandle>>> {
 647        let project = self.project.clone();
 648        cx.spawn(async move |cx| {
 649            let language_registry =
 650                project.read_with(cx, |project, _cx| project.languages().clone())?;
 651            let id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
 652            let terminal =
 653                acp_thread::create_terminal_entity(command, &[], vec![], cwd.clone(), &project, cx)
 654                    .await?;
 655            let terminal = cx.new(|cx| {
 656                acp_thread::Terminal::new(
 657                    id,
 658                    "",
 659                    cwd,
 660                    output_byte_limit.map(|limit| limit as usize),
 661                    terminal,
 662                    language_registry,
 663                    cx,
 664                )
 665            })?;
 666            Ok(Rc::new(EvalTerminalHandle { terminal }) as Rc<dyn agent::TerminalHandle>)
 667        })
 668    }
 669}
 670
 671struct LanguageModelInterceptor {
 672    model: Arc<dyn LanguageModel>,
 673    request_count: Arc<Mutex<usize>>,
 674    previous_diff: Arc<Mutex<String>>,
 675    example_output_dir: PathBuf,
 676    last_diff_file_path: PathBuf,
 677    messages_json_file_path: PathBuf,
 678    repository_path: PathBuf,
 679    repository_url: String,
 680}
 681
 682impl LanguageModelInterceptor {
 683    fn new(
 684        model: Arc<dyn LanguageModel>,
 685        example_output_dir: PathBuf,
 686        last_diff_file_path: PathBuf,
 687        messages_json_file_path: PathBuf,
 688        repository_path: PathBuf,
 689        repository_url: String,
 690    ) -> Arc<Self> {
 691        Arc::new(Self {
 692            model,
 693            request_count: Arc::new(Mutex::new(0)),
 694            previous_diff: Arc::new(Mutex::new("".to_string())),
 695            example_output_dir,
 696            last_diff_file_path,
 697            messages_json_file_path,
 698            repository_path,
 699            repository_url,
 700        })
 701    }
 702}
 703
 704impl language_model::LanguageModel for LanguageModelInterceptor {
 705    fn id(&self) -> language_model::LanguageModelId {
 706        self.model.id()
 707    }
 708
 709    fn name(&self) -> language_model::LanguageModelName {
 710        self.model.name()
 711    }
 712
 713    fn provider_id(&self) -> language_model::LanguageModelProviderId {
 714        self.model.provider_id()
 715    }
 716
 717    fn provider_name(&self) -> language_model::LanguageModelProviderName {
 718        self.model.provider_name()
 719    }
 720
 721    fn telemetry_id(&self) -> String {
 722        self.model.telemetry_id()
 723    }
 724
 725    fn supports_images(&self) -> bool {
 726        self.model.supports_images()
 727    }
 728
 729    fn supports_tools(&self) -> bool {
 730        self.model.supports_tools()
 731    }
 732
 733    fn supports_tool_choice(&self, choice: language_model::LanguageModelToolChoice) -> bool {
 734        self.model.supports_tool_choice(choice)
 735    }
 736
 737    fn max_token_count(&self) -> u64 {
 738        self.model.max_token_count()
 739    }
 740
 741    fn count_tokens(
 742        &self,
 743        request: LanguageModelRequest,
 744        cx: &App,
 745    ) -> future::BoxFuture<'static, Result<u64>> {
 746        self.model.count_tokens(request, cx)
 747    }
 748
 749    fn stream_completion(
 750        &self,
 751        request: LanguageModelRequest,
 752        cx: &AsyncApp,
 753    ) -> future::BoxFuture<
 754        'static,
 755        Result<
 756            futures::stream::BoxStream<
 757                'static,
 758                Result<LanguageModelCompletionEvent, language_model::LanguageModelCompletionError>,
 759            >,
 760            language_model::LanguageModelCompletionError,
 761        >,
 762    > {
 763        let stream = self.model.stream_completion(request.clone(), cx);
 764        let request_count = self.request_count.clone();
 765        let previous_diff = self.previous_diff.clone();
 766        let example_output_dir = self.example_output_dir.clone();
 767        let last_diff_file_path = self.last_diff_file_path.clone();
 768        let messages_json_file_path = self.messages_json_file_path.clone();
 769        let repository_path = self.repository_path.clone();
 770        let repository_url = self.repository_url.clone();
 771
 772        Box::pin(async move {
 773            let stream = stream.await?;
 774
 775            let response_events = Arc::new(Mutex::new(Vec::new()));
 776            let request_clone = request.clone();
 777
 778            let wrapped_stream = stream.then(move |event| {
 779                let response_events = response_events.clone();
 780                let request = request_clone.clone();
 781                let request_count = request_count.clone();
 782                let previous_diff = previous_diff.clone();
 783                let example_output_dir = example_output_dir.clone();
 784                let last_diff_file_path = last_diff_file_path.clone();
 785                let messages_json_file_path = messages_json_file_path.clone();
 786                let repository_path = repository_path.clone();
 787                let repository_url = repository_url.clone();
 788
 789                async move {
 790                    let event_result = match &event {
 791                        Ok(ev) => Ok(ev.clone()),
 792                        Err(err) => Err(err.to_string()),
 793                    };
 794                    response_events.lock().unwrap().push(event_result);
 795
 796                    let should_execute = matches!(
 797                        &event,
 798                        Ok(LanguageModelCompletionEvent::Stop { .. }) | Err(_)
 799                    );
 800
 801                    if should_execute {
 802                        let current_request_count = {
 803                            let mut count = request_count.lock().unwrap();
 804                            *count += 1;
 805                            *count
 806                        };
 807
 808                        let messages_file_path =
 809                            example_output_dir.join(format!("{current_request_count}.messages.md"));
 810                        let diff_file_path =
 811                            example_output_dir.join(format!("{current_request_count}.diff"));
 812                        let last_messages_file_path = example_output_dir.join("last.messages.md");
 813
 814                        let collected_events = response_events.lock().unwrap().clone();
 815                        let request_markdown = RequestMarkdown::new(&request);
 816                        let response_events_markdown =
 817                            response_events_to_markdown(&collected_events);
 818                        let dialog = ThreadDialog::new(&request, &collected_events);
 819                        let dialog_json =
 820                            serde_json::to_string_pretty(&dialog.to_combined_request())
 821                                .unwrap_or_default();
 822
 823                        let messages = format!(
 824                            "{}\n\n{}",
 825                            request_markdown.messages, response_events_markdown
 826                        );
 827                        fs::write(&messages_file_path, messages.clone())
 828                            .expect("failed to write messages file");
 829                        fs::write(&last_messages_file_path, messages)
 830                            .expect("failed to write last messages file");
 831                        fs::write(&messages_json_file_path, dialog_json)
 832                            .expect("failed to write last.messages.json");
 833
 834                        // Get repository diff
 835                        let diff_result =
 836                            ExampleInstance::repository_diff(repository_path, &repository_url)
 837                                .await;
 838
 839                        match diff_result {
 840                            Ok(diff) => {
 841                                let prev_diff = previous_diff.lock().unwrap().clone();
 842                                if diff != prev_diff {
 843                                    fs::write(&diff_file_path, &diff)
 844                                        .expect("failed to write diff file");
 845                                    fs::write(&last_diff_file_path, &diff)
 846                                        .expect("failed to write last diff file");
 847                                    *previous_diff.lock().unwrap() = diff;
 848                                }
 849                            }
 850                            Err(err) => {
 851                                let error_message = format!("{err:?}");
 852                                fs::write(&diff_file_path, &error_message)
 853                                    .expect("failed to write diff error to file");
 854                                fs::write(&last_diff_file_path, &error_message)
 855                                    .expect("failed to write last diff file");
 856                            }
 857                        }
 858
 859                        if current_request_count == 1 {
 860                            let tools_file_path = example_output_dir.join("tools.md");
 861                            fs::write(tools_file_path, request_markdown.tools)
 862                                .expect("failed to write tools file");
 863                        }
 864                    }
 865
 866                    event
 867                }
 868            });
 869
 870            Ok(Box::pin(wrapped_stream)
 871                as futures::stream::BoxStream<
 872                    'static,
 873                    Result<
 874                        LanguageModelCompletionEvent,
 875                        language_model::LanguageModelCompletionError,
 876                    >,
 877                >)
 878        })
 879    }
 880}
 881
 882pub fn wait_for_lang_server(
 883    project: &Entity<Project>,
 884    buffer: &Entity<Buffer>,
 885    log_prefix: String,
 886    cx: &mut AsyncApp,
 887) -> Task<Result<()>> {
 888    if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
 889        return Task::ready(Ok(()));
 890    }
 891
 892    println!("{}⏵ Waiting for language server", log_prefix);
 893
 894    let (mut tx, mut rx) = mpsc::channel(1);
 895
 896    let lsp_store = project
 897        .read_with(cx, |project, _| project.lsp_store())
 898        .unwrap();
 899
 900    let has_lang_server = buffer
 901        .update(cx, |buffer, cx| {
 902            lsp_store.update(cx, |lsp_store, cx| {
 903                lsp_store
 904                    .running_language_servers_for_local_buffer(buffer, cx)
 905                    .next()
 906                    .is_some()
 907            })
 908        })
 909        .unwrap_or(false);
 910
 911    if has_lang_server {
 912        project
 913            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 914            .unwrap()
 915            .detach();
 916    }
 917
 918    let subscriptions =
 919        [
 920            cx.subscribe(&lsp_store, {
 921                let log_prefix = log_prefix.clone();
 922                move |_, event, _| {
 923                    if let project::LspStoreEvent::LanguageServerUpdate {
 924                        message:
 925                            client::proto::update_language_server::Variant::WorkProgress(
 926                                LspWorkProgress {
 927                                    message: Some(message),
 928                                    ..
 929                                },
 930                            ),
 931                        ..
 932                    } = event
 933                    {
 934                        println!("{}{message}", log_prefix)
 935                    }
 936                }
 937            }),
 938            cx.subscribe(project, {
 939                let buffer = buffer.clone();
 940                move |project, event, cx| match event {
 941                    project::Event::LanguageServerAdded(_, _, _) => {
 942                        let buffer = buffer.clone();
 943                        project
 944                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 945                            .detach();
 946                    }
 947                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 948                        tx.try_send(()).ok();
 949                    }
 950                    _ => {}
 951                }
 952            }),
 953        ];
 954
 955    cx.spawn(async move |cx| {
 956        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 957        let result = futures::select! {
 958            _ = rx.next() => {
 959                println!("{}⚑ Language server idle", log_prefix);
 960                anyhow::Ok(())
 961            },
 962            _ = timeout.fuse() => {
 963                anyhow::bail!("LSP wait timed out after 5 minutes");
 964            }
 965        };
 966        drop(subscriptions);
 967        result
 968    })
 969}
 970
 971pub async fn query_lsp_diagnostics(
 972    project: Entity<Project>,
 973    cx: &mut AsyncApp,
 974) -> Result<Option<String>> {
 975    let paths_with_diagnostics = project.update(cx, |project, cx| {
 976        project
 977            .diagnostic_summaries(true, cx)
 978            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 979            .map(|(project_path, _, _)| project_path)
 980            .collect::<Vec<_>>()
 981    })?;
 982
 983    if paths_with_diagnostics.is_empty() {
 984        return Ok(None);
 985    }
 986
 987    let mut output = String::new();
 988    for project_path in paths_with_diagnostics {
 989        let buffer = project
 990            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 991            .await?;
 992        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 993
 994        for (_, group) in snapshot.diagnostic_groups(None) {
 995            let entry = &group.entries[group.primary_ix];
 996            let range = entry.range.to_point(&snapshot);
 997            let severity = match entry.diagnostic.severity {
 998                DiagnosticSeverity::ERROR => "error",
 999                DiagnosticSeverity::WARNING => "warning",
1000                _ => continue,
1001            };
1002
1003            writeln!(
1004                output,
1005                "{} at line {}: {}",
1006                severity,
1007                range.start.row + 1,
1008                entry.diagnostic.message
1009            )?;
1010        }
1011    }
1012    anyhow::Ok(Some(output))
1013}
1014
1015fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
1016    let analysis = get_tag("analysis", response)?;
1017    let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
1018        "true" => true,
1019        "false" => false,
1020        value @ _ => bail!("invalid judge `passed` tag: {value}"),
1021    };
1022    Ok(RanAssertionResult {
1023        analysis: Some(analysis),
1024        passed,
1025    })
1026}
1027
1028fn get_tag(name: &'static str, response: &str) -> Result<String> {
1029    let start_tag = format!("<{}>", name);
1030    let end_tag = format!("</{}>", name);
1031
1032    let start_ix = response
1033        .find(&start_tag)
1034        .context(format!("{} start tag not found", name))?;
1035    let content_start_ix = start_ix + start_tag.len();
1036
1037    let end_ix = content_start_ix
1038        + response[content_start_ix..]
1039            .find(&end_tag)
1040            .context(format!("{} end tag not found", name))?;
1041
1042    let content = response[content_start_ix..end_ix].trim().unindent();
1043
1044    anyhow::Ok(content)
1045}
1046
1047pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
1048    let repo_name = repo_url
1049        .trim_start_matches("https://")
1050        .replace(|c: char| !c.is_alphanumeric(), "-");
1051    Path::new(repos_dir).join(repo_name)
1052}
1053
1054pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
1055    let output = new_smol_command("git")
1056        .current_dir(repo_path)
1057        .args(args)
1058        .output()
1059        .await?;
1060
1061    anyhow::ensure!(
1062        output.status.success(),
1063        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
1064        args.join(" "),
1065        repo_path.display(),
1066        output.status,
1067        String::from_utf8_lossy(&output.stderr),
1068        String::from_utf8_lossy(&output.stdout),
1069    );
1070    Ok(String::from_utf8(output.stdout)?.trim().to_string())
1071}
1072
1073fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
1074    match role {
1075        Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
1076        Role::User => buf.push_str("# 👤 USER\n\n"),
1077        Role::Assistant => {
1078            buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
1079            *assistant_message_number = *assistant_message_number + 1;
1080        }
1081    }
1082}
1083
1084pub async fn send_language_model_request(
1085    model: Arc<dyn LanguageModel>,
1086    request: LanguageModelRequest,
1087    cx: &AsyncApp,
1088) -> anyhow::Result<String> {
1089    match model.stream_completion_text(request, cx).await {
1090        Ok(mut stream) => {
1091            let mut full_response = String::new();
1092            while let Some(chunk_result) = stream.stream.next().await {
1093                match chunk_result {
1094                    Ok(chunk_str) => {
1095                        full_response.push_str(&chunk_str);
1096                    }
1097                    Err(err) => {
1098                        anyhow::bail!("Error receiving response from language model: {err}");
1099                    }
1100                }
1101            }
1102            Ok(full_response)
1103        }
1104        Err(err) => Err(anyhow!(
1105            "Failed to get response from language model. Error was: {err}"
1106        )),
1107    }
1108}
1109
1110pub struct RequestMarkdown {
1111    pub tools: String,
1112    pub messages: String,
1113}
1114
1115impl RequestMarkdown {
1116    pub fn new(request: &LanguageModelRequest) -> Self {
1117        let mut tools = String::new();
1118        let mut messages = String::new();
1119        let mut assistant_message_number: u32 = 1;
1120
1121        // Print the tools
1122        if !request.tools.is_empty() {
1123            for tool in &request.tools {
1124                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
1125                write!(&mut tools, "{}\n\n", tool.description).unwrap();
1126                writeln!(
1127                    &mut tools,
1128                    "{}",
1129                    MarkdownCodeBlock {
1130                        tag: "json",
1131                        text: &format!("{:#}", tool.input_schema)
1132                    }
1133                )
1134                .unwrap();
1135            }
1136        }
1137
1138        // Print the messages
1139        for message in &request.messages {
1140            push_role(&message.role, &mut messages, &mut assistant_message_number);
1141
1142            for content in &message.content {
1143                match content {
1144                    MessageContent::Text(text) => {
1145                        messages.push_str(text);
1146                        messages.push_str("\n\n");
1147                    }
1148                    MessageContent::Image(_) => {
1149                        messages.push_str("[IMAGE DATA]\n\n");
1150                    }
1151                    MessageContent::Thinking { text, signature } => {
1152                        messages.push_str("**Thinking**:\n\n");
1153                        if let Some(sig) = signature {
1154                            messages.push_str(&format!("Signature: {}\n\n", sig));
1155                        }
1156                        messages.push_str(text);
1157                        messages.push_str("\n");
1158                    }
1159                    MessageContent::RedactedThinking(items) => {
1160                        messages.push_str(&format!(
1161                            "**Redacted Thinking**: {} item(s)\n\n",
1162                            items.len()
1163                        ));
1164                    }
1165                    MessageContent::ToolUse(tool_use) => {
1166                        messages.push_str(&format!(
1167                            "**Tool Use**: {} (ID: {})\n",
1168                            tool_use.name, tool_use.id
1169                        ));
1170                        messages.push_str(&format!(
1171                            "{}\n",
1172                            MarkdownCodeBlock {
1173                                tag: "json",
1174                                text: &format!("{:#}", tool_use.input)
1175                            }
1176                        ));
1177                    }
1178                    MessageContent::ToolResult(tool_result) => {
1179                        messages.push_str(&format!(
1180                            "**Tool Result**: {} (ID: {})\n\n",
1181                            tool_result.tool_name, tool_result.tool_use_id
1182                        ));
1183                        if tool_result.is_error {
1184                            messages.push_str("**ERROR:**\n");
1185                        }
1186
1187                        match &tool_result.content {
1188                            LanguageModelToolResultContent::Text(text) => {
1189                                writeln!(messages, "{text}\n").ok();
1190                            }
1191                            LanguageModelToolResultContent::Image(image) => {
1192                                writeln!(messages, "![Image](data:base64,{})\n", image.source).ok();
1193                            }
1194                        }
1195
1196                        if let Some(output) = tool_result.output.as_ref() {
1197                            writeln!(
1198                                messages,
1199                                "**Debug Output**:\n\n```json\n{}\n```\n",
1200                                serde_json::to_string_pretty(output).unwrap()
1201                            )
1202                            .unwrap();
1203                        }
1204                    }
1205                }
1206            }
1207        }
1208
1209        Self { tools, messages }
1210    }
1211}
1212
1213pub fn response_events_to_markdown(
1214    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1215) -> String {
1216    let mut response = String::new();
1217    // Print the response events if any
1218    response.push_str("# Response\n\n");
1219    let mut text_buffer = String::new();
1220    let mut thinking_buffer = String::new();
1221
1222    let flush_buffers =
1223        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
1224            if !text_buffer.is_empty() {
1225                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
1226                text_buffer.clear();
1227            }
1228            if !thinking_buffer.is_empty() {
1229                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
1230                thinking_buffer.clear();
1231            }
1232        };
1233
1234    for event in response_events {
1235        match event {
1236            Ok(LanguageModelCompletionEvent::Text(text)) => {
1237                text_buffer.push_str(text);
1238            }
1239            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1240                thinking_buffer.push_str(text);
1241            }
1242            Ok(LanguageModelCompletionEvent::RedactedThinking { .. }) => {}
1243            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1244                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1245                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1246            }
1247            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1248                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1249                response.push_str(&format!(
1250                    "**Tool Use**: {} (ID: {})\n",
1251                    tool_use.name, tool_use.id
1252                ));
1253                response.push_str(&format!(
1254                    "{}\n",
1255                    MarkdownCodeBlock {
1256                        tag: "json",
1257                        text: &format!("{:#}", tool_use.input)
1258                    }
1259                ));
1260            }
1261            Ok(
1262                LanguageModelCompletionEvent::UsageUpdate(_)
1263                | LanguageModelCompletionEvent::ToolUseLimitReached
1264                | LanguageModelCompletionEvent::StartMessage { .. }
1265                | LanguageModelCompletionEvent::UsageUpdated { .. }
1266                | LanguageModelCompletionEvent::Queued { .. }
1267                | LanguageModelCompletionEvent::Started
1268                | LanguageModelCompletionEvent::ReasoningDetails(_),
1269            ) => {}
1270            Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
1271                json_parse_error, ..
1272            }) => {
1273                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1274                response.push_str(&format!(
1275                    "**Error**: parse error in tool use JSON: {}\n\n",
1276                    json_parse_error
1277                ));
1278            }
1279            Err(error) => {
1280                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1281                response.push_str(&format!("**Error**: {}\n\n", error));
1282            }
1283        }
1284    }
1285
1286    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1287
1288    response
1289}
1290
1291#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1292pub struct ThreadDialog {
1293    pub request: LanguageModelRequest,
1294    pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1295}
1296
1297impl ThreadDialog {
1298    pub fn new(
1299        request: &LanguageModelRequest,
1300        response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1301    ) -> Self {
1302        Self {
1303            request: request.clone(),
1304            response_events: response_events.to_vec(),
1305        }
1306    }
1307
1308    /// Represents all request and response messages in a unified format.
1309    ///
1310    /// Specifically, it appends the assistant's response (derived from response events)
1311    /// as a new message to existing messages in the request.
1312    pub fn to_combined_request(&self) -> LanguageModelRequest {
1313        let mut request = self.request.clone();
1314        if let Some(assistant_message) = self.response_events_to_message() {
1315            request.messages.push(assistant_message);
1316        }
1317        request
1318    }
1319    fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1320        let response_events = &self.response_events;
1321        let mut content: Vec<MessageContent> = Vec::new();
1322        let mut current_text = String::new();
1323
1324        let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1325            if !text.is_empty() {
1326                content.push(MessageContent::Text(std::mem::take(text)));
1327            }
1328        };
1329
1330        for event in response_events {
1331            match event {
1332                Ok(LanguageModelCompletionEvent::Text(text)) => {
1333                    current_text.push_str(text);
1334                }
1335
1336                Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1337                    flush_text(&mut current_text, &mut content);
1338                    if tool_use.is_input_complete {
1339                        content.push(MessageContent::ToolUse(tool_use.clone()));
1340                    }
1341                }
1342                Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1343                    flush_text(&mut current_text, &mut content);
1344                    content.push(MessageContent::Thinking {
1345                        text: text.clone(),
1346                        signature: signature.clone(),
1347                    });
1348                }
1349
1350                // Skip these
1351                Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1352                | Ok(LanguageModelCompletionEvent::RedactedThinking { .. })
1353                | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1354                | Ok(LanguageModelCompletionEvent::ReasoningDetails(_))
1355                | Ok(LanguageModelCompletionEvent::Stop(_))
1356                | Ok(LanguageModelCompletionEvent::Queued { .. })
1357                | Ok(LanguageModelCompletionEvent::Started)
1358                | Ok(LanguageModelCompletionEvent::UsageUpdated { .. })
1359                | Ok(LanguageModelCompletionEvent::ToolUseLimitReached) => {}
1360
1361                Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
1362                    json_parse_error,
1363                    ..
1364                }) => {
1365                    flush_text(&mut current_text, &mut content);
1366                    content.push(MessageContent::Text(format!(
1367                        "ERROR: parse error in tool use JSON: {}",
1368                        json_parse_error
1369                    )));
1370                }
1371
1372                Err(error) => {
1373                    flush_text(&mut current_text, &mut content);
1374                    content.push(MessageContent::Text(format!("ERROR: {}", error)));
1375                }
1376            }
1377        }
1378
1379        flush_text(&mut current_text, &mut content);
1380
1381        if !content.is_empty() {
1382            Some(LanguageModelRequestMessage {
1383                role: Role::Assistant,
1384                content,
1385                cache: false,
1386                reasoning_details: None,
1387            })
1388        } else {
1389            None
1390        }
1391    }
1392}
1393
1394#[cfg(test)]
1395mod test {
1396    use super::*;
1397
1398    #[test]
1399    fn test_parse_judge_output() {
1400        let response = r#"
1401            <analysis>The model did a good job but there were still compilations errors.</analysis>
1402            <passed>true</passed>
1403        "#
1404        .unindent();
1405
1406        let output = parse_assertion_result(&response).unwrap();
1407        assert_eq!(
1408            output.analysis,
1409            Some("The model did a good job but there were still compilations errors.".into())
1410        );
1411        assert!(output.passed);
1412
1413        let response = r#"
1414            Text around ignored
1415
1416            <analysis>
1417                Failed to compile:
1418                - Error 1
1419                - Error 2
1420            </analysis>
1421
1422            <passed>false</passed>
1423        "#
1424        .unindent();
1425
1426        let output = parse_assertion_result(&response).unwrap();
1427        assert_eq!(
1428            output.analysis,
1429            Some("Failed to compile:\n- Error 1\n- Error 2".into())
1430        );
1431        assert!(!output.passed);
1432    }
1433}