eval.rs

  1mod assertions;
  2mod example;
  3mod examples;
  4mod explorer;
  5mod ids;
  6mod instance;
  7mod tool_metrics;
  8
  9use assertions::{AssertionsReport, display_error_row};
 10use instance::{ExampleInstance, JudgeOutput, RunOutput, run_git};
 11use language_extension::LspAccess;
 12pub(crate) use tool_metrics::*;
 13
 14use ::fs::RealFs;
 15use clap::Parser;
 16use client::{Client, ProxySettings, UserStore};
 17use collections::{HashMap, HashSet};
 18use extension::ExtensionHostProxy;
 19use futures::future;
 20use gpui::http_client::read_proxy_from_env;
 21use gpui::{App, AppContext, Application, AsyncApp, Entity, UpdateGlobal};
 22use gpui_tokio::Tokio;
 23use language::LanguageRegistry;
 24use language_model::{ConfiguredModel, LanguageModel, LanguageModelRegistry, SelectedModel};
 25use node_runtime::{NodeBinaryOptions, NodeRuntime};
 26use project::Project;
 27use project::project_settings::ProjectSettings;
 28use prompt_store::PromptBuilder;
 29use release_channel::AppVersion;
 30use reqwest_client::ReqwestClient;
 31use settings::{Settings, SettingsStore};
 32use std::cell::RefCell;
 33use std::collections::VecDeque;
 34use std::env;
 35use std::path::{Path, PathBuf};
 36use std::rc::Rc;
 37use std::str::FromStr;
 38use std::sync::{Arc, LazyLock};
 39use util::ResultExt as _;
 40
 41static CARGO_MANIFEST_DIR: LazyLock<PathBuf> =
 42    LazyLock::new(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
 43
 44#[derive(Parser, Debug)]
 45#[command(name = "eval", disable_version_flag = true)]
 46struct Args {
 47    /// Runs all examples and threads that contain these substrings. If unspecified, all examples and threads are run.
 48    #[arg(value_name = "EXAMPLE_SUBSTRING")]
 49    filter: Vec<String>,
 50    /// provider/model to use for agent
 51    #[arg(long, default_value = "anthropic/claude-3-7-sonnet-latest")]
 52    model: String,
 53    /// provider/model to use for judges
 54    #[arg(long, default_value = "anthropic/claude-3-7-sonnet-latest")]
 55    judge_model: String,
 56    #[arg(long, value_delimiter = ',', default_value = "rs,ts,py")]
 57    languages: Vec<String>,
 58    /// How many times to run each example.
 59    #[arg(long, default_value = "8")]
 60    repetitions: usize,
 61    /// Maximum number of examples to run concurrently.
 62    #[arg(long, default_value = "4")]
 63    concurrency: usize,
 64}
 65
 66fn main() {
 67    dotenvy::from_filename(CARGO_MANIFEST_DIR.join(".env")).ok();
 68
 69    env_logger::init();
 70
 71    let system_id = ids::get_or_create_id(&ids::eval_system_id_path()).ok();
 72    let installation_id = ids::get_or_create_id(&ids::eval_installation_id_path()).ok();
 73    let session_id = uuid::Uuid::new_v4().to_string();
 74    let run_timestamp = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
 75    let run_id = match env::var("GITHUB_RUN_ID") {
 76        Ok(run_id) => format!("github/{}", run_id),
 77        Err(_) => format!("local/{}", run_timestamp),
 78    };
 79
 80    let root_dir = Path::new(std::env!("CARGO_MANIFEST_DIR"))
 81        .parent()
 82        .unwrap()
 83        .parent()
 84        .unwrap()
 85        .canonicalize()
 86        .unwrap();
 87    let eval_crate_dir = root_dir.join("crates").join("eval");
 88    let repos_dir = eval_crate_dir.join("repos");
 89    let worktrees_dir = eval_crate_dir.join("worktrees");
 90    let examples_dir = eval_crate_dir.join("src").join("examples");
 91    let run_dir = eval_crate_dir
 92        .join("runs")
 93        .join(format!("{}", run_timestamp));
 94    std::fs::create_dir_all(&run_dir).unwrap();
 95    std::fs::create_dir_all(&repos_dir).unwrap();
 96    std::fs::create_dir_all(&worktrees_dir).unwrap();
 97    std::fs::create_dir_all(&examples_dir).unwrap();
 98    std::fs::create_dir_all(&paths::config_dir()).unwrap();
 99
100    let zed_commit_sha = commit_sha_for_path(&root_dir);
101    let zed_branch_name = git_branch_for_path(&root_dir);
102    let args = Args::parse();
103    let languages: HashSet<String> = args.languages.into_iter().collect();
104
105    let http_client = Arc::new(ReqwestClient::new());
106    let app = Application::headless().with_http_client(http_client);
107    let all_threads = examples::all(&examples_dir);
108
109    app.run(move |cx| {
110        let app_state = init(cx);
111
112        let telemetry = app_state.client.telemetry();
113        telemetry.start(system_id, installation_id, session_id, cx);
114
115        let enable_telemetry = env::var("ZED_EVAL_TELEMETRY").is_ok_and(|value| value == "1")
116            && telemetry.has_checksum_seed();
117        if enable_telemetry {
118            println!("Telemetry enabled");
119            telemetry::event!(
120                "Agent Eval Started",
121                zed_commit_sha = zed_commit_sha,
122                zed_branch_name = zed_branch_name,
123                run_id = run_id,
124            );
125        }
126
127        let mut cumulative_tool_metrics = ToolMetrics::default();
128
129        let agent_model = load_model(&args.model, cx).unwrap();
130        let judge_model = load_model(&args.judge_model, cx).unwrap();
131
132        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
133            registry.set_default_model(Some(agent_model.clone()), cx);
134        });
135
136        let auth1 = agent_model.provider.authenticate(cx);
137        let auth2 = judge_model.provider.authenticate(cx);
138
139        cx.spawn(async move |cx| {
140            auth1.await?;
141            auth2.await?;
142
143            let mut examples = Vec::new();
144
145            const COLORS: [&str; 12] = [
146                "\x1b[31m", // Red
147                "\x1b[32m", // Green
148                "\x1b[33m", // Yellow
149                "\x1b[34m", // Blue
150                "\x1b[35m", // Magenta
151                "\x1b[36m", // Cyan
152                "\x1b[91m", // Bright Red
153                "\x1b[92m", // Bright Green
154                "\x1b[93m", // Bright Yellow
155                "\x1b[94m", // Bright Blue
156                "\x1b[95m", // Bright Magenta
157                "\x1b[96m", // Bright Cyan
158            ];
159
160            let mut skipped = Vec::new();
161
162            for thread in all_threads {
163                let meta = thread.meta();
164                if !args.filter.is_empty() && !args.filter.iter().any(|sub| meta.name.contains(sub))
165                {
166                    skipped.push(meta.name);
167                    continue;
168                }
169
170                if let Some(language) = meta.language_server
171                    && !languages.contains(&language.file_extension) {
172                        panic!(
173                            "Eval for {:?} could not be run because no language server was found for extension {:?}",
174                            meta.name,
175                            language.file_extension
176                        );
177                    }
178
179                // TODO: This creates a worktree per repetition. Ideally these examples should
180                // either be run sequentially on the same worktree, or reuse worktrees when there
181                // are more examples to run than the concurrency limit.
182                for repetition_number in 0..args.repetitions {
183                    let example_instance = ExampleInstance::new(
184                        thread.clone(),
185                        &repos_dir,
186                        &run_dir,
187                        &worktrees_dir,
188                        repetition_number,
189                    );
190
191                    examples.push(example_instance);
192                }
193            }
194
195            if !skipped.is_empty() {
196                println!("Skipped threads: {}", skipped.join(", "));
197            }
198
199            if examples.is_empty() {
200                eprintln!("Filter matched no examples");
201                return cx.update(|cx| cx.quit());
202            }
203
204            let mut repo_urls = HashSet::default();
205            let mut clone_tasks = Vec::new();
206
207            let max_name_width = examples
208                .iter()
209                .map(|e| e.worktree_name().len())
210                .max()
211                .unwrap_or(0);
212
213            for (i, example_instance) in examples.iter_mut().enumerate() {
214                let color = COLORS[i % COLORS.len()].to_string();
215                example_instance.set_log_prefix_style(&color, max_name_width);
216
217                println!(
218                    "{}Logging to: {}",
219                    example_instance.log_prefix,
220                    example_instance.run_directory.display()
221                );
222
223                let repo_url = example_instance.repo_url();
224                if repo_urls.insert(repo_url.clone()) {
225                    let repo_path = example_instance.repo_path.clone();
226
227                    if !repo_path.join(".git").is_dir() {
228                        println!(
229                            "{:<width$} < {}",
230                            "↓ Cloning",
231                            repo_url,
232                            width = max_name_width
233                        );
234
235                        let git_task = cx.spawn(async move |_cx| {
236                            std::fs::create_dir_all(&repo_path)?;
237                            run_git(&repo_path, &["init"]).await?;
238                            run_git(&repo_path, &["remote", "add", "origin", &repo_url]).await
239                        });
240
241                        clone_tasks.push(git_task);
242                    } else {
243                        println!(
244                            "{:<width$}  < {}",
245                            "✔︎ Already cloned",
246                            repo_url,
247                            width = max_name_width
248                        );
249
250                        let actual_origin =
251                            run_git(&repo_path, &["remote", "get-url", "origin"]).await?;
252                        anyhow::ensure!(
253                            actual_origin == repo_url,
254                            "remote origin {actual_origin} does not match expected origin {repo_url}"
255                        );
256                    }
257                }
258            }
259
260            future::join_all(clone_tasks).await;
261
262            for example_instance in examples.iter_mut() {
263                example_instance.fetch().await?;
264            }
265
266            let examples = Rc::new(RefCell::new(VecDeque::from(examples)));
267            let results_by_example_name = Rc::new(RefCell::new(HashMap::default()));
268
269            future::join_all((0..args.concurrency).map(|_| {
270                let app_state = app_state.clone();
271                let model = agent_model.model.clone();
272                let judge_model = judge_model.model.clone();
273                let zed_commit_sha = zed_commit_sha.clone();
274                let zed_branch_name = zed_branch_name.clone();
275                let run_id = run_id.clone();
276                let examples = examples.clone();
277                let results = results_by_example_name.clone();
278                cx.spawn(async move |cx| {
279                    loop {
280                        let Some(mut example) = examples.borrow_mut().pop_front() else {
281                            break;
282                        };
283                        let result = async {
284                            example.setup().await?;
285                            let run_output = cx
286                                .update(|cx| example.run(model.clone(), app_state.clone(), cx))?
287                                .await?;
288                            let judge_output = judge_example(
289                                example.clone(),
290                                judge_model.clone(),
291                                &zed_commit_sha,
292                                &zed_branch_name,
293                                &run_id,
294                                &run_output,
295                                enable_telemetry,
296                                cx,
297                            )
298                            .await;
299                            anyhow::Ok((run_output, judge_output))
300                        }
301                        .await;
302                        results
303                            .borrow_mut()
304                            .entry(example.name.clone())
305                            .or_insert(Vec::new())
306                            .push((example.clone(), result));
307                    }
308                })
309            }))
310            .await;
311
312            print_report(
313                &mut results_by_example_name.borrow_mut(),
314                &mut cumulative_tool_metrics,
315                &run_dir,
316            )?;
317
318            app_state.client.telemetry().flush_events().await;
319
320            cx.update(|cx| cx.quit())
321        })
322        .detach_and_log_err(cx);
323    });
324}
325
326/// Subset of `workspace::AppState` needed by `HeadlessAssistant`, with additional fields.
327pub struct AgentAppState {
328    pub languages: Arc<LanguageRegistry>,
329    pub client: Arc<Client>,
330    pub user_store: Entity<UserStore>,
331    pub fs: Arc<dyn fs::Fs>,
332    pub node_runtime: NodeRuntime,
333
334    // Additional fields not present in `workspace::AppState`.
335    pub prompt_builder: Arc<PromptBuilder>,
336}
337
338pub fn init(cx: &mut App) -> Arc<AgentAppState> {
339    let app_version = AppVersion::load(env!("ZED_PKG_VERSION"));
340    release_channel::init(app_version, cx);
341    gpui_tokio::init(cx);
342
343    let mut settings_store = SettingsStore::new(cx);
344    settings_store
345        .set_default_settings(settings::default_settings().as_ref(), cx)
346        .unwrap();
347    cx.set_global(settings_store);
348    client::init_settings(cx);
349
350    // Set User-Agent so we can download language servers from GitHub
351    let user_agent = format!(
352        "Zed Agent Eval/{} ({}; {})",
353        app_version,
354        std::env::consts::OS,
355        std::env::consts::ARCH
356    );
357    let proxy_str = ProxySettings::get_global(cx).proxy.to_owned();
358    let proxy_url = proxy_str
359        .as_ref()
360        .and_then(|input| input.parse().ok())
361        .or_else(read_proxy_from_env);
362    let http = {
363        let _guard = Tokio::handle(cx).enter();
364
365        ReqwestClient::proxy_and_user_agent(proxy_url, &user_agent)
366            .expect("could not start HTTP client")
367    };
368    cx.set_http_client(Arc::new(http));
369
370    Project::init_settings(cx);
371
372    let client = Client::production(cx);
373    cx.set_http_client(client.http_client());
374
375    let git_binary_path = None;
376    let fs = Arc::new(RealFs::new(
377        git_binary_path,
378        cx.background_executor().clone(),
379    ));
380
381    let mut languages = LanguageRegistry::new(cx.background_executor().clone());
382    languages.set_language_server_download_dir(paths::languages_dir().clone());
383    let languages = Arc::new(languages);
384
385    let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
386
387    extension::init(cx);
388
389    let (mut tx, rx) = watch::channel(None);
390    cx.observe_global::<SettingsStore>(move |cx| {
391        let settings = &ProjectSettings::get_global(cx).node;
392        let options = NodeBinaryOptions {
393            allow_path_lookup: !settings.ignore_system_version,
394            allow_binary_download: true,
395            use_paths: settings.path.as_ref().map(|node_path| {
396                let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
397                let npm_path = settings
398                    .npm_path
399                    .as_ref()
400                    .map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
401                (
402                    node_path.clone(),
403                    npm_path.unwrap_or_else(|| {
404                        let base_path = PathBuf::new();
405                        node_path.parent().unwrap_or(&base_path).join("npm")
406                    }),
407                )
408            }),
409        };
410        tx.send(Some(options)).log_err();
411    })
412    .detach();
413    let node_runtime = NodeRuntime::new(client.http_client(), None, rx);
414
415    let extension_host_proxy = ExtensionHostProxy::global(cx);
416
417    language::init(cx);
418    debug_adapter_extension::init(extension_host_proxy.clone(), cx);
419    language_extension::init(LspAccess::Noop, extension_host_proxy, languages.clone());
420    language_model::init(client.clone(), cx);
421    language_models::init(user_store.clone(), client.clone(), cx);
422    languages::init(languages.clone(), fs.clone(), node_runtime.clone(), cx);
423    prompt_store::init(cx);
424    terminal_view::init(cx);
425    let stdout_is_a_pty = false;
426    let prompt_builder = PromptBuilder::load(fs.clone(), stdout_is_a_pty, cx);
427    agent_ui::init(
428        fs.clone(),
429        client.clone(),
430        prompt_builder.clone(),
431        languages.clone(),
432        true,
433        cx,
434    );
435    assistant_tools::init(client.http_client(), cx);
436
437    SettingsStore::update_global(cx, |store, cx| {
438        store.set_user_settings(include_str!("../runner_settings.json"), cx)
439    })
440    .unwrap();
441
442    Arc::new(AgentAppState {
443        languages,
444        client,
445        user_store,
446        fs,
447        node_runtime,
448        prompt_builder,
449    })
450}
451
452pub fn find_model(
453    model_name: &str,
454    model_registry: &LanguageModelRegistry,
455    cx: &App,
456) -> anyhow::Result<Arc<dyn LanguageModel>> {
457    let selected = SelectedModel::from_str(model_name).map_err(|e| anyhow::anyhow!(e))?;
458    model_registry
459        .available_models(cx)
460        .find(|model| model.id() == selected.model && model.provider_id() == selected.provider)
461        .ok_or_else(|| {
462            anyhow::anyhow!(
463                "No language model with ID {}/{} was available. Available models: {}",
464                selected.model.0,
465                selected.provider.0,
466                model_registry
467                    .available_models(cx)
468                    .map(|model| format!("{}/{}", model.provider_id().0, model.id().0))
469                    .collect::<Vec<_>>()
470                    .join(", ")
471            )
472        })
473}
474
475pub fn load_model(model_name: &str, cx: &mut App) -> anyhow::Result<ConfiguredModel> {
476    let model = {
477        let model_registry = LanguageModelRegistry::read_global(cx);
478        find_model(model_name, model_registry, cx)?
479    };
480
481    let provider = {
482        let model_registry = LanguageModelRegistry::read_global(cx);
483        model_registry
484            .provider(&model.provider_id())
485            .ok_or_else(|| anyhow::anyhow!("Provider not found: {}", model.provider_id()))?
486    };
487
488    Ok(ConfiguredModel {
489        provider: provider.clone(),
490        model: model.clone(),
491    })
492}
493
494pub fn commit_sha_for_path(repo_path: &Path) -> String {
495    futures::executor::block_on(run_git(repo_path, &["rev-parse", "HEAD"])).unwrap()
496}
497
498pub fn git_branch_for_path(repo_path: &Path) -> String {
499    match std::env::var("GITHUB_REF_NAME") {
500        Ok(branch) => branch,
501        Err(_) => {
502            futures::executor::block_on(run_git(repo_path, &["rev-parse", "--abbrev-ref", "HEAD"]))
503                .unwrap_or_else(|_| "unknown".to_string())
504        }
505    }
506}
507
508async fn judge_example(
509    example: ExampleInstance,
510    model: Arc<dyn LanguageModel>,
511    zed_commit_sha: &str,
512    zed_branch_name: &str,
513    run_id: &str,
514    run_output: &RunOutput,
515    enable_telemetry: bool,
516    cx: &AsyncApp,
517) -> JudgeOutput {
518    let judge_output = example.judge(model.clone(), run_output, cx).await;
519
520    if enable_telemetry {
521        telemetry::event!(
522            "Agent Example Evaluated",
523            zed_commit_sha = zed_commit_sha,
524            zed_branch_name = zed_branch_name,
525            run_id = run_id,
526            example_name = example.name.clone(),
527            example_repetition = example.repetition,
528            diff_evaluation = judge_output.diff.clone(),
529            thread_evaluation = judge_output.thread,
530            tool_metrics = run_output.tool_metrics,
531            response_count = run_output.response_count,
532            token_usage = run_output.token_usage,
533            model = model.telemetry_id(),
534            model_provider = model.provider_id().to_string(),
535            repository_url = example.repo_url(),
536            repository_revision = example.revision(),
537            diagnostic_summary_before = run_output.diagnostic_summary_before,
538            diagnostic_summary_after = run_output.diagnostic_summary_after,
539            diagnostics_before = run_output.diagnostics_before,
540            diagnostics_after = run_output.diagnostics_after,
541        );
542    }
543
544    judge_output
545}
546
547const HEADER_WIDTH: usize = 65;
548
549fn print_h1(header: &str) {
550    println!("\n\n{:=^HEADER_WIDTH$}", "");
551    println!("{:^HEADER_WIDTH$}", header);
552    println!("{:=^HEADER_WIDTH$}\n", "");
553}
554
555fn print_h2(header: &str) {
556    println!("\n{:-^HEADER_WIDTH$}", "");
557    println!("{:^HEADER_WIDTH$}", header);
558    println!("{:-^HEADER_WIDTH$}\n", "");
559}
560
561fn print_report(
562    results_by_example_name: &mut HashMap<
563        String,
564        Vec<(ExampleInstance, anyhow::Result<(RunOutput, JudgeOutput)>)>,
565    >,
566    cumulative_tool_metrics: &mut ToolMetrics,
567    run_dir: &Path,
568) -> anyhow::Result<()> {
569    print_h1("EVAL RESULTS");
570
571    let mut diff_scores = Vec::new();
572    let mut thread_scores = Vec::new();
573    let mut programmatic_scores = Vec::new();
574    let mut error_count = 0;
575
576    for (example_name, results) in results_by_example_name.iter_mut() {
577        print_h2(example_name);
578
579        results.sort_unstable_by_key(|(example, _)| example.repetition);
580        let mut example_cumulative_tool_metrics = ToolMetrics::default();
581
582        let mut table_rows = String::new();
583
584        for (example, result) in results.iter() {
585            match result {
586                Err(err) => {
587                    display_error_row(&mut table_rows, example.repetition, err.to_string())?;
588                    error_count += 1;
589                    programmatic_scores.push(0.0);
590                    diff_scores.push(0.0);
591                    thread_scores.push(0.0);
592                }
593                Ok((run_output, judge_output)) => {
594                    cumulative_tool_metrics.merge(&run_output.tool_metrics);
595                    example_cumulative_tool_metrics.merge(&run_output.tool_metrics);
596
597                    if run_output.programmatic_assertions.total_count() > 0 {
598                        for assertion in &run_output.programmatic_assertions.ran {
599                            assertions::display_table_row(
600                                &mut table_rows,
601                                example.repetition,
602                                assertion,
603                            )?;
604                        }
605
606                        programmatic_scores
607                            .push(run_output.programmatic_assertions.passed_percentage())
608                    }
609
610                    if !judge_output.diff.is_empty() {
611                        diff_scores.push(judge_output.diff.passed_percentage());
612
613                        for assertion in &judge_output.diff.ran {
614                            assertions::display_table_row(
615                                &mut table_rows,
616                                example.repetition,
617                                assertion,
618                            )?;
619                        }
620                    }
621
622                    if !judge_output.thread.is_empty() {
623                        thread_scores.push(judge_output.thread.passed_percentage());
624
625                        for assertion in &judge_output.thread.ran {
626                            assertions::display_table_row(
627                                &mut table_rows,
628                                example.repetition,
629                                assertion,
630                            )?;
631                        }
632                    }
633                }
634            }
635        }
636
637        let mut all_asserts = Vec::new();
638
639        if !table_rows.is_empty() {
640            assertions::print_table_header();
641            print!("{}", table_rows);
642
643            assertions::print_table_divider();
644
645            for (example, result) in results.iter() {
646                if let Ok((run_output, judge_output)) = result {
647                    let asserts = [
648                        run_output.programmatic_assertions.clone(),
649                        judge_output.diff.clone(),
650                        judge_output.thread.clone(),
651                    ];
652                    all_asserts.extend_from_slice(&asserts);
653                    assertions::print_table_round_summary(
654                        &example.repetition.to_string(),
655                        asserts.iter(),
656                    )
657                } else if let Err(err) = result {
658                    let assert = AssertionsReport::error(err.to_string());
659                    all_asserts.push(assert.clone());
660                    assertions::print_table_round_summary(
661                        &example.repetition.to_string(),
662                        [assert].iter(),
663                    )
664                }
665            }
666
667            assertions::print_table_divider();
668
669            assertions::print_table_round_summary("avg", all_asserts.iter());
670
671            assertions::print_table_footer();
672        }
673
674        if !example_cumulative_tool_metrics.is_empty() {
675            println!("{}", &example_cumulative_tool_metrics);
676        }
677    }
678
679    if results_by_example_name.len() > 1 {
680        print_h1("AGGREGATE");
681
682        if error_count > 0 {
683            println!("\n{error_count} examples failed to run!");
684        }
685
686        let programmatic_score_count = programmatic_scores.len();
687        if programmatic_score_count > 0 {
688            let average_programmatic_score = (programmatic_scores.into_iter().sum::<f32>()
689                / (programmatic_score_count as f32))
690                .floor();
691            println!("Average programmatic score: {average_programmatic_score}%");
692        }
693
694        let diff_score_count = diff_scores.len();
695        if diff_score_count > 0 {
696            let average_diff_score =
697                (diff_scores.into_iter().sum::<f32>() / (diff_score_count as f32)).floor();
698            println!("Average diff score: {average_diff_score}%");
699        }
700
701        let thread_score_count = thread_scores.len();
702
703        if thread_score_count > 0 {
704            let average_thread_score =
705                (thread_scores.into_iter().sum::<f32>() / (thread_score_count as f32)).floor();
706            println!("Average thread score: {average_thread_score}%");
707        }
708
709        println!();
710
711        print_h2("CUMULATIVE TOOL METRICS");
712        println!("{}", cumulative_tool_metrics);
713    }
714
715    let explorer_output_path = run_dir.join("overview.html");
716    let mut json_paths: Vec<PathBuf> = results_by_example_name
717        .values()
718        .flat_map(|results| {
719            results.iter().map(|(example, _)| {
720                let absolute_path = run_dir.join(example.run_directory.join("last.messages.json"));
721                let cwd = std::env::current_dir().expect("Can't get current dir");
722                pathdiff::diff_paths(&absolute_path, cwd).unwrap_or_else(|| absolute_path.clone())
723            })
724        })
725        .collect::<Vec<_>>();
726    json_paths.sort();
727    if let Err(err) = explorer::generate_explorer_html(&json_paths, &explorer_output_path) {
728        eprintln!("Failed to generate explorer HTML: {}", err);
729    }
730
731    Ok(())
732}