agent_panel.rs

   1use std::{
   2    path::PathBuf,
   3    rc::Rc,
   4    sync::{
   5        Arc,
   6        atomic::{AtomicBool, Ordering},
   7    },
   8    time::Duration,
   9};
  10
  11use acp_thread::{AcpThread, MentionUri, ThreadStatus};
  12use agent::{ContextServerRegistry, SharedThread, ThreadStore};
  13use agent_client_protocol as acp;
  14use agent_servers::AgentServer;
  15use collections::HashSet;
  16use db::kvp::{Dismissable, KeyValueStore};
  17use itertools::Itertools;
  18use project::AgentId;
  19use serde::{Deserialize, Serialize};
  20use settings::{LanguageModelProviderSetting, LanguageModelSelection};
  21
  22use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
  23use zed_actions::agent::{
  24    AddSelectionToThread, ConflictContent, ReauthenticateAgent, ResolveConflictedFilesWithAgent,
  25    ResolveConflictsWithAgent, ReviewBranchDiff,
  26};
  27
  28use crate::thread_metadata_store::ThreadMetadataStore;
  29use crate::{
  30    AddContextServer, AgentDiffPane, ConversationView, CopyThreadToClipboard, CycleStartThreadIn,
  31    Follow, InlineAssistant, LoadThreadFromClipboard, NewThread, NewWorktreeBranchTarget,
  32    OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,
  33    StartThreadIn, ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,
  34    agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
  35    conversation_view::{AcpThreadViewEvent, ThreadView},
  36    thread_branch_picker::ThreadBranchPicker,
  37    thread_worktree_picker::ThreadWorktreePicker,
  38    ui::EndTrialUpsell,
  39};
  40use crate::{
  41    Agent, AgentInitialContent, ExternalSourcePrompt, NewExternalAgentThread,
  42    NewNativeAgentThreadFromSummary,
  43};
  44use crate::{DEFAULT_THREAD_TITLE, ui::AcpOnboardingModal};
  45use crate::{ExpandMessageEditor, ThreadHistoryView};
  46use crate::{ManageProfiles, ThreadHistoryViewEvent};
  47use crate::{ThreadHistory, agent_connection_store::AgentConnectionStore};
  48use agent_settings::AgentSettings;
  49use ai_onboarding::AgentPanelOnboarding;
  50use anyhow::{Context as _, Result, anyhow};
  51use client::UserStore;
  52use cloud_api_types::Plan;
  53use collections::HashMap;
  54use editor::Editor;
  55use extension::ExtensionEvents;
  56use extension_host::ExtensionStore;
  57use fs::Fs;
  58use gpui::{
  59    Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext, ClipboardItem, Corner,
  60    DismissEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, KeyContext, Pixels,
  61    Subscription, Task, UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
  62};
  63use language::LanguageRegistry;
  64use language_model::LanguageModelRegistry;
  65use project::project_settings::ProjectSettings;
  66use project::{Project, ProjectPath, Worktree};
  67use prompt_store::{PromptStore, UserPromptId};
  68use rules_library::{RulesLibrary, open_rules_library};
  69use settings::TerminalDockPosition;
  70use settings::{Settings, update_settings_file};
  71use terminal::terminal_settings::TerminalSettings;
  72use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
  73use theme_settings::ThemeSettings;
  74use ui::{
  75    Button, Callout, CommonAnimationExt, ContextMenu, ContextMenuEntry, PopoverMenu,
  76    PopoverMenuHandle, Tab, Tooltip, prelude::*, utils::WithRemSize,
  77};
  78use util::{ResultExt as _, debug_panic};
  79use workspace::{
  80    CollaboratorId, DraggedSelection, DraggedTab, OpenMode, OpenResult, PathList,
  81    SerializedPathList, ToggleWorkspaceSidebar, ToggleZoom, Workspace, WorkspaceId,
  82    dock::{DockPosition, Panel, PanelEvent},
  83};
  84use zed_actions::{
  85    DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
  86    agent::{OpenAcpOnboardingModal, OpenSettings, ResetAgentZoom, ResetOnboarding},
  87    assistant::{OpenRulesLibrary, Toggle, ToggleFocus},
  88};
  89
  90const AGENT_PANEL_KEY: &str = "agent_panel";
  91const RECENTLY_UPDATED_MENU_LIMIT: usize = 6;
  92const LAST_USED_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
  93
  94#[derive(Serialize, Deserialize)]
  95struct LastUsedAgent {
  96    agent: Agent,
  97}
  98
  99/// Reads the most recently used agent across all workspaces. Used as a fallback
 100/// when opening a workspace that has no per-workspace agent preference yet.
 101fn read_global_last_used_agent(kvp: &KeyValueStore) -> Option<Agent> {
 102    kvp.read_kvp(LAST_USED_AGENT_KEY)
 103        .log_err()
 104        .flatten()
 105        .and_then(|json| serde_json::from_str::<LastUsedAgent>(&json).log_err())
 106        .map(|entry| entry.agent)
 107}
 108
 109async fn write_global_last_used_agent(kvp: KeyValueStore, agent: Agent) {
 110    if let Some(json) = serde_json::to_string(&LastUsedAgent { agent }).log_err() {
 111        kvp.write_kvp(LAST_USED_AGENT_KEY.to_string(), json)
 112            .await
 113            .log_err();
 114    }
 115}
 116
 117fn read_serialized_panel(
 118    workspace_id: workspace::WorkspaceId,
 119    kvp: &KeyValueStore,
 120) -> Option<SerializedAgentPanel> {
 121    let scope = kvp.scoped(AGENT_PANEL_KEY);
 122    let key = i64::from(workspace_id).to_string();
 123    scope
 124        .read(&key)
 125        .log_err()
 126        .flatten()
 127        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
 128}
 129
 130async fn save_serialized_panel(
 131    workspace_id: workspace::WorkspaceId,
 132    panel: SerializedAgentPanel,
 133    kvp: KeyValueStore,
 134) -> Result<()> {
 135    let scope = kvp.scoped(AGENT_PANEL_KEY);
 136    let key = i64::from(workspace_id).to_string();
 137    scope.write(key, serde_json::to_string(&panel)?).await?;
 138    Ok(())
 139}
 140
 141/// Migration: reads the original single-panel format stored under the
 142/// `"agent_panel"` KVP key before per-workspace keying was introduced.
 143fn read_legacy_serialized_panel(kvp: &KeyValueStore) -> Option<SerializedAgentPanel> {
 144    kvp.read_kvp(AGENT_PANEL_KEY)
 145        .log_err()
 146        .flatten()
 147        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
 148}
 149
 150#[derive(Serialize, Deserialize, Debug)]
 151struct SerializedAgentPanel {
 152    selected_agent: Option<Agent>,
 153    #[serde(default)]
 154    last_active_thread: Option<SerializedActiveThread>,
 155    #[serde(default)]
 156    start_thread_in: Option<StartThreadIn>,
 157}
 158
 159#[derive(Serialize, Deserialize, Debug)]
 160struct SerializedActiveThread {
 161    session_id: String,
 162    agent_type: Agent,
 163    title: Option<String>,
 164    work_dirs: Option<SerializedPathList>,
 165}
 166
 167pub fn init(cx: &mut App) {
 168    cx.observe_new(
 169        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
 170            workspace
 171                .register_action(|workspace, action: &NewThread, window, cx| {
 172                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 173                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
 174                        workspace.focus_panel::<AgentPanel>(window, cx);
 175                    }
 176                })
 177                .register_action(
 178                    |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {
 179                        if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 180                            panel.update(cx, |panel, cx| {
 181                                panel.new_native_agent_thread_from_summary(action, window, cx)
 182                            });
 183                            workspace.focus_panel::<AgentPanel>(window, cx);
 184                        }
 185                    },
 186                )
 187                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
 188                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 189                        workspace.focus_panel::<AgentPanel>(window, cx);
 190                        panel.update(cx, |panel, cx| panel.expand_message_editor(window, cx));
 191                    }
 192                })
 193                .register_action(|workspace, _: &OpenHistory, window, cx| {
 194                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 195                        workspace.focus_panel::<AgentPanel>(window, cx);
 196                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
 197                    }
 198                })
 199                .register_action(|workspace, _: &OpenSettings, window, cx| {
 200                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 201                        workspace.focus_panel::<AgentPanel>(window, cx);
 202                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
 203                    }
 204                })
 205                .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
 206                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 207                        workspace.focus_panel::<AgentPanel>(window, cx);
 208                        panel.update(cx, |panel, cx| {
 209                            panel.external_thread(
 210                                action.agent.clone(),
 211                                None,
 212                                None,
 213                                None,
 214                                None,
 215                                true,
 216                                window,
 217                                cx,
 218                            )
 219                        });
 220                    }
 221                })
 222                .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
 223                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 224                        workspace.focus_panel::<AgentPanel>(window, cx);
 225                        panel.update(cx, |panel, cx| {
 226                            panel.deploy_rules_library(action, window, cx)
 227                        });
 228                    }
 229                })
 230                .register_action(|workspace, _: &Follow, window, cx| {
 231                    workspace.follow(CollaboratorId::Agent, window, cx);
 232                })
 233                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
 234                    let thread = workspace
 235                        .panel::<AgentPanel>(cx)
 236                        .and_then(|panel| panel.read(cx).active_conversation_view().cloned())
 237                        .and_then(|conversation| {
 238                            conversation
 239                                .read(cx)
 240                                .active_thread()
 241                                .map(|r| r.read(cx).thread.clone())
 242                        });
 243
 244                    if let Some(thread) = thread {
 245                        AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
 246                    }
 247                })
 248                .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
 249                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 250                        workspace.focus_panel::<AgentPanel>(window, cx);
 251                        panel.update(cx, |panel, cx| {
 252                            panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
 253                        });
 254                    }
 255                })
 256                .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
 257                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 258                        workspace.focus_panel::<AgentPanel>(window, cx);
 259                        panel.update(cx, |panel, cx| {
 260                            panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
 261                        });
 262                    }
 263                })
 264                .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
 265                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 266                        workspace.focus_panel::<AgentPanel>(window, cx);
 267                        panel.update(cx, |panel, cx| {
 268                            panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
 269                        });
 270                    }
 271                })
 272                .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {
 273                    AcpOnboardingModal::toggle(workspace, window, cx)
 274                })
 275                .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
 276                    window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
 277                    window.refresh();
 278                })
 279                .register_action(|workspace, _: &ResetTrialUpsell, _window, cx| {
 280                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 281                        panel.update(cx, |panel, _| {
 282                            panel
 283                                .on_boarding_upsell_dismissed
 284                                .store(false, Ordering::Release);
 285                        });
 286                    }
 287                    OnboardingUpsell::set_dismissed(false, cx);
 288                })
 289                .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
 290                    TrialEndUpsell::set_dismissed(false, cx);
 291                })
 292                .register_action(|workspace, _: &ResetAgentZoom, window, cx| {
 293                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 294                        panel.update(cx, |panel, cx| {
 295                            panel.reset_agent_zoom(window, cx);
 296                        });
 297                    }
 298                })
 299                .register_action(|workspace, _: &CopyThreadToClipboard, window, cx| {
 300                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 301                        panel.update(cx, |panel, cx| {
 302                            panel.copy_thread_to_clipboard(window, cx);
 303                        });
 304                    }
 305                })
 306                .register_action(|workspace, _: &LoadThreadFromClipboard, window, cx| {
 307                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 308                        workspace.focus_panel::<AgentPanel>(window, cx);
 309                        panel.update(cx, |panel, cx| {
 310                            panel.load_thread_from_clipboard(window, cx);
 311                        });
 312                    }
 313                })
 314                .register_action(|workspace, action: &ReviewBranchDiff, window, cx| {
 315                    let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 316                        return;
 317                    };
 318
 319                    let mention_uri = MentionUri::GitDiff {
 320                        base_ref: action.base_ref.to_string(),
 321                    };
 322                    let diff_uri = mention_uri.to_uri().to_string();
 323
 324                    let content_blocks = vec![
 325                        acp::ContentBlock::Text(acp::TextContent::new(
 326                            "Please review this branch diff carefully. Point out any issues, \
 327                             potential bugs, or improvement opportunities you find.\n\n"
 328                                .to_string(),
 329                        )),
 330                        acp::ContentBlock::Resource(acp::EmbeddedResource::new(
 331                            acp::EmbeddedResourceResource::TextResourceContents(
 332                                acp::TextResourceContents::new(
 333                                    action.diff_text.to_string(),
 334                                    diff_uri,
 335                                ),
 336                            ),
 337                        )),
 338                    ];
 339
 340                    workspace.focus_panel::<AgentPanel>(window, cx);
 341
 342                    panel.update(cx, |panel, cx| {
 343                        panel.external_thread(
 344                            None,
 345                            None,
 346                            None,
 347                            None,
 348                            Some(AgentInitialContent::ContentBlock {
 349                                blocks: content_blocks,
 350                                auto_submit: true,
 351                            }),
 352                            true,
 353                            window,
 354                            cx,
 355                        );
 356                    });
 357                })
 358                .register_action(
 359                    |workspace, action: &ResolveConflictsWithAgent, window, cx| {
 360                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 361                            return;
 362                        };
 363
 364                        let content_blocks = build_conflict_resolution_prompt(&action.conflicts);
 365
 366                        workspace.focus_panel::<AgentPanel>(window, cx);
 367
 368                        panel.update(cx, |panel, cx| {
 369                            panel.external_thread(
 370                                None,
 371                                None,
 372                                None,
 373                                None,
 374                                Some(AgentInitialContent::ContentBlock {
 375                                    blocks: content_blocks,
 376                                    auto_submit: true,
 377                                }),
 378                                true,
 379                                window,
 380                                cx,
 381                            );
 382                        });
 383                    },
 384                )
 385                .register_action(
 386                    |workspace, action: &ResolveConflictedFilesWithAgent, window, cx| {
 387                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 388                            return;
 389                        };
 390
 391                        let content_blocks =
 392                            build_conflicted_files_resolution_prompt(&action.conflicted_file_paths);
 393
 394                        workspace.focus_panel::<AgentPanel>(window, cx);
 395
 396                        panel.update(cx, |panel, cx| {
 397                            panel.external_thread(
 398                                None,
 399                                None,
 400                                None,
 401                                None,
 402                                Some(AgentInitialContent::ContentBlock {
 403                                    blocks: content_blocks,
 404                                    auto_submit: true,
 405                                }),
 406                                true,
 407                                window,
 408                                cx,
 409                            );
 410                        });
 411                    },
 412                )
 413                .register_action(|workspace, action: &StartThreadIn, window, cx| {
 414                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 415                        panel.update(cx, |panel, cx| {
 416                            panel.set_start_thread_in(action, window, cx);
 417                        });
 418                    }
 419                })
 420                .register_action(|workspace, _: &CycleStartThreadIn, window, cx| {
 421                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 422                        panel.update(cx, |panel, cx| {
 423                            panel.cycle_start_thread_in(window, cx);
 424                        });
 425                    }
 426                })
 427                .register_action(
 428                    |workspace: &mut Workspace, _: &AddSelectionToThread, window, cx| {
 429                        let active_editor = workspace
 430                            .active_item(cx)
 431                            .and_then(|item| item.act_as::<Editor>(cx));
 432                        let has_editor_selection = active_editor.is_some_and(|editor| {
 433                            editor.update(cx, |editor, cx| {
 434                                editor.has_non_empty_selection(&editor.display_snapshot(cx))
 435                            })
 436                        });
 437
 438                        let has_terminal_selection = workspace
 439                            .active_item(cx)
 440                            .and_then(|item| item.act_as::<TerminalView>(cx))
 441                            .is_some_and(|terminal_view| {
 442                                terminal_view
 443                                    .read(cx)
 444                                    .terminal()
 445                                    .read(cx)
 446                                    .last_content
 447                                    .selection_text
 448                                    .as_ref()
 449                                    .is_some_and(|text| !text.is_empty())
 450                            });
 451
 452                        let has_terminal_panel_selection =
 453                            workspace.panel::<TerminalPanel>(cx).is_some_and(|panel| {
 454                                let position = match TerminalSettings::get_global(cx).dock {
 455                                    TerminalDockPosition::Left => DockPosition::Left,
 456                                    TerminalDockPosition::Bottom => DockPosition::Bottom,
 457                                    TerminalDockPosition::Right => DockPosition::Right,
 458                                };
 459                                let dock_is_open =
 460                                    workspace.dock_at_position(position).read(cx).is_open();
 461                                dock_is_open && !panel.read(cx).terminal_selections(cx).is_empty()
 462                            });
 463
 464                        if !has_editor_selection
 465                            && !has_terminal_selection
 466                            && !has_terminal_panel_selection
 467                        {
 468                            return;
 469                        }
 470
 471                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 472                            return;
 473                        };
 474
 475                        if !panel.focus_handle(cx).contains_focused(window, cx) {
 476                            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
 477                        }
 478
 479                        panel.update(cx, |_, cx| {
 480                            cx.defer_in(window, move |panel, window, cx| {
 481                                if let Some(conversation_view) = panel.active_conversation_view() {
 482                                    conversation_view.update(cx, |conversation_view, cx| {
 483                                        conversation_view.insert_selections(window, cx);
 484                                    });
 485                                }
 486                            });
 487                        });
 488                    },
 489                );
 490        },
 491    )
 492    .detach();
 493}
 494
 495fn conflict_resource_block(conflict: &ConflictContent) -> acp::ContentBlock {
 496    let mention_uri = MentionUri::MergeConflict {
 497        file_path: conflict.file_path.clone(),
 498    };
 499    acp::ContentBlock::Resource(acp::EmbeddedResource::new(
 500        acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents::new(
 501            conflict.conflict_text.clone(),
 502            mention_uri.to_uri().to_string(),
 503        )),
 504    ))
 505}
 506
 507fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::ContentBlock> {
 508    if conflicts.is_empty() {
 509        return Vec::new();
 510    }
 511
 512    let mut blocks = Vec::new();
 513
 514    if conflicts.len() == 1 {
 515        let conflict = &conflicts[0];
 516
 517        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 518            "Please resolve the following merge conflict in ",
 519        )));
 520        let mention = MentionUri::File {
 521            abs_path: PathBuf::from(conflict.file_path.clone()),
 522        };
 523        blocks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
 524            mention.name(),
 525            mention.to_uri(),
 526        )));
 527
 528        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 529            indoc::formatdoc!(
 530                "\nThe conflict is between branch `{ours}` (ours) and `{theirs}` (theirs).
 531
 532                Analyze both versions carefully and resolve the conflict by editing \
 533                the file directly. Choose the resolution that best preserves the intent \
 534                of both changes, or combine them if appropriate.
 535
 536                ",
 537                ours = conflict.ours_branch_name,
 538                theirs = conflict.theirs_branch_name,
 539            ),
 540        )));
 541    } else {
 542        let n = conflicts.len();
 543        let unique_files: HashSet<&str> = conflicts.iter().map(|c| c.file_path.as_str()).collect();
 544        let ours = &conflicts[0].ours_branch_name;
 545        let theirs = &conflicts[0].theirs_branch_name;
 546        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 547            indoc::formatdoc!(
 548                "Please resolve all {n} merge conflicts below.
 549
 550                The conflicts are between branch `{ours}` (ours) and `{theirs}` (theirs).
 551
 552                For each conflict, analyze both versions carefully and resolve them \
 553                by editing the file{suffix} directly. Choose resolutions that best preserve \
 554                the intent of both changes, or combine them if appropriate.
 555
 556                ",
 557                suffix = if unique_files.len() > 1 { "s" } else { "" },
 558            ),
 559        )));
 560    }
 561
 562    for conflict in conflicts {
 563        blocks.push(conflict_resource_block(conflict));
 564    }
 565
 566    blocks
 567}
 568
 569fn build_conflicted_files_resolution_prompt(
 570    conflicted_file_paths: &[String],
 571) -> Vec<acp::ContentBlock> {
 572    if conflicted_file_paths.is_empty() {
 573        return Vec::new();
 574    }
 575
 576    let instruction = indoc::indoc!(
 577        "The following files have unresolved merge conflicts. Please open each \
 578         file, find the conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`), \
 579         and resolve every conflict by editing the files directly.
 580
 581         Choose resolutions that best preserve the intent of both changes, \
 582         or combine them if appropriate.
 583
 584         Files with conflicts:
 585         ",
 586    );
 587
 588    let mut content = vec![acp::ContentBlock::Text(acp::TextContent::new(instruction))];
 589    for path in conflicted_file_paths {
 590        let mention = MentionUri::File {
 591            abs_path: PathBuf::from(path),
 592        };
 593        content.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
 594            mention.name(),
 595            mention.to_uri(),
 596        )));
 597        content.push(acp::ContentBlock::Text(acp::TextContent::new("\n")));
 598    }
 599    content
 600}
 601
 602enum ActiveView {
 603    Uninitialized,
 604    AgentThread {
 605        conversation_view: Entity<ConversationView>,
 606    },
 607    History {
 608        view: Entity<ThreadHistoryView>,
 609    },
 610    Configuration,
 611}
 612
 613enum WhichFontSize {
 614    AgentFont,
 615    None,
 616}
 617
 618impl StartThreadIn {
 619    fn label(&self) -> SharedString {
 620        match self {
 621            Self::LocalProject => "Current Worktree".into(),
 622            Self::NewWorktree {
 623                worktree_name: Some(worktree_name),
 624                ..
 625            } => format!("New: {worktree_name}").into(),
 626            Self::NewWorktree { .. } => "New Git Worktree".into(),
 627            Self::LinkedWorktree { display_name, .. } => format!("From: {}", &display_name).into(),
 628        }
 629    }
 630
 631    fn worktree_branch_label(&self, default_branch_label: SharedString) -> Option<SharedString> {
 632        match self {
 633            Self::NewWorktree { branch_target, .. } => match branch_target {
 634                NewWorktreeBranchTarget::CurrentBranch => Some(default_branch_label),
 635                NewWorktreeBranchTarget::ExistingBranch { name } => {
 636                    Some(format!("From: {name}").into())
 637                }
 638                NewWorktreeBranchTarget::CreateBranch { name, from_ref } => {
 639                    if let Some(from_ref) = from_ref {
 640                        Some(format!("From: {from_ref}").into())
 641                    } else {
 642                        Some(format!("From: {name}").into())
 643                    }
 644                }
 645            },
 646            _ => None,
 647        }
 648    }
 649}
 650
 651#[derive(Clone, Debug)]
 652#[allow(dead_code)]
 653pub enum WorktreeCreationStatus {
 654    Creating,
 655    Error(SharedString),
 656}
 657
 658#[derive(Clone, Debug)]
 659enum WorktreeCreationArgs {
 660    New {
 661        worktree_name: Option<String>,
 662        branch_target: NewWorktreeBranchTarget,
 663    },
 664    Linked {
 665        worktree_path: PathBuf,
 666    },
 667}
 668
 669impl ActiveView {
 670    pub fn which_font_size_used(&self) -> WhichFontSize {
 671        match self {
 672            ActiveView::Uninitialized
 673            | ActiveView::AgentThread { .. }
 674            | ActiveView::History { .. } => WhichFontSize::AgentFont,
 675            ActiveView::Configuration => WhichFontSize::None,
 676        }
 677    }
 678}
 679
 680pub struct AgentPanel {
 681    workspace: WeakEntity<Workspace>,
 682    /// Workspace id is used as a database key
 683    workspace_id: Option<WorkspaceId>,
 684    user_store: Entity<UserStore>,
 685    project: Entity<Project>,
 686    fs: Arc<dyn Fs>,
 687    language_registry: Arc<LanguageRegistry>,
 688    thread_store: Entity<ThreadStore>,
 689    prompt_store: Option<Entity<PromptStore>>,
 690    connection_store: Entity<AgentConnectionStore>,
 691    context_server_registry: Entity<ContextServerRegistry>,
 692    configuration: Option<Entity<AgentConfiguration>>,
 693    configuration_subscription: Option<Subscription>,
 694    focus_handle: FocusHandle,
 695    active_view: ActiveView,
 696    previous_view: Option<ActiveView>,
 697    background_threads: HashMap<acp::SessionId, Entity<ConversationView>>,
 698    new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
 699    start_thread_in_menu_handle: PopoverMenuHandle<ThreadWorktreePicker>,
 700    thread_branch_menu_handle: PopoverMenuHandle<ThreadBranchPicker>,
 701    agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
 702    agent_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
 703    agent_navigation_menu: Option<Entity<ContextMenu>>,
 704    _extension_subscription: Option<Subscription>,
 705    _project_subscription: Subscription,
 706    zoomed: bool,
 707    pending_serialization: Option<Task<Result<()>>>,
 708    onboarding: Entity<AgentPanelOnboarding>,
 709    selected_agent: Agent,
 710    start_thread_in: StartThreadIn,
 711    worktree_creation_status: Option<WorktreeCreationStatus>,
 712    _thread_view_subscription: Option<Subscription>,
 713    _active_thread_focus_subscription: Option<Subscription>,
 714    _worktree_creation_task: Option<Task<()>>,
 715    show_trust_workspace_message: bool,
 716    on_boarding_upsell_dismissed: AtomicBool,
 717    _active_view_observation: Option<Subscription>,
 718}
 719
 720impl AgentPanel {
 721    fn serialize(&mut self, cx: &mut App) {
 722        let Some(workspace_id) = self.workspace_id else {
 723            return;
 724        };
 725
 726        let selected_agent = self.selected_agent.clone();
 727        let start_thread_in = Some(self.start_thread_in.clone());
 728
 729        let last_active_thread = self.active_agent_thread(cx).map(|thread| {
 730            let thread = thread.read(cx);
 731            let title = thread.title();
 732            let work_dirs = thread.work_dirs().cloned();
 733            SerializedActiveThread {
 734                session_id: thread.session_id().0.to_string(),
 735                agent_type: self.selected_agent.clone(),
 736                title: title.map(|t| t.to_string()),
 737                work_dirs: work_dirs.map(|dirs| dirs.serialize()),
 738            }
 739        });
 740
 741        let kvp = KeyValueStore::global(cx);
 742        self.pending_serialization = Some(cx.background_spawn(async move {
 743            save_serialized_panel(
 744                workspace_id,
 745                SerializedAgentPanel {
 746                    selected_agent: Some(selected_agent),
 747                    last_active_thread,
 748                    start_thread_in,
 749                },
 750                kvp,
 751            )
 752            .await?;
 753            anyhow::Ok(())
 754        }));
 755    }
 756
 757    pub fn load(
 758        workspace: WeakEntity<Workspace>,
 759        mut cx: AsyncWindowContext,
 760    ) -> Task<Result<Entity<Self>>> {
 761        let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
 762        let kvp = cx.update(|_window, cx| KeyValueStore::global(cx)).ok();
 763        cx.spawn(async move |cx| {
 764            let prompt_store = match prompt_store {
 765                Ok(prompt_store) => prompt_store.await.ok(),
 766                Err(_) => None,
 767            };
 768            let workspace_id = workspace
 769                .read_with(cx, |workspace, _| workspace.database_id())
 770                .ok()
 771                .flatten();
 772
 773            let (serialized_panel, global_last_used_agent) = cx
 774                .background_spawn(async move {
 775                    match kvp {
 776                        Some(kvp) => {
 777                            let panel = workspace_id
 778                                .and_then(|id| read_serialized_panel(id, &kvp))
 779                                .or_else(|| read_legacy_serialized_panel(&kvp));
 780                            let global_agent = read_global_last_used_agent(&kvp);
 781                            (panel, global_agent)
 782                        }
 783                        None => (None, None),
 784                    }
 785                })
 786                .await;
 787
 788            let last_active_thread = if let Some(thread_info) = serialized_panel
 789                .as_ref()
 790                .and_then(|p| p.last_active_thread.as_ref())
 791            {
 792                let session_id = acp::SessionId::new(thread_info.session_id.clone());
 793                let has_metadata = cx
 794                    .update(|_window, cx| {
 795                        let store = ThreadMetadataStore::global(cx);
 796                        store.read(cx).entry(&session_id).is_some()
 797                    })
 798                    .unwrap_or(false);
 799                if has_metadata {
 800                    Some(thread_info)
 801                } else {
 802                    log::warn!(
 803                        "last active thread {} has no metadata, skipping restoration",
 804                        thread_info.session_id
 805                    );
 806                    None
 807                }
 808            } else {
 809                None
 810            };
 811
 812            let panel = workspace.update_in(cx, |workspace, window, cx| {
 813                let panel =
 814                    cx.new(|cx| Self::new(workspace, prompt_store, window, cx));
 815
 816                panel.update(cx, |panel, cx| {
 817                    let is_via_collab = panel.project.read(cx).is_via_collab();
 818
 819                    // Only apply a non-native global fallback to local projects.
 820                    // Collab workspaces only support NativeAgent, so inheriting a
 821                    // custom agent would cause set_active → new_agent_thread_inner
 822                    // to bypass the collab guard in external_thread.
 823                    let global_fallback = global_last_used_agent
 824                        .filter(|agent| !is_via_collab || agent.is_native());
 825
 826                    if let Some(serialized_panel) = &serialized_panel {
 827                        if let Some(selected_agent) = serialized_panel.selected_agent.clone() {
 828                            panel.selected_agent = selected_agent;
 829                        } else if let Some(agent) = global_fallback {
 830                            panel.selected_agent = agent;
 831                        }
 832                        if let Some(ref start_thread_in) = serialized_panel.start_thread_in {
 833                            let is_worktree_flag_enabled =
 834                                cx.has_flag::<AgentV2FeatureFlag>();
 835                            let is_valid = match &start_thread_in {
 836                                StartThreadIn::LocalProject => true,
 837                                StartThreadIn::NewWorktree { .. } => {
 838                                    let project = panel.project.read(cx);
 839                                    is_worktree_flag_enabled && !project.is_via_collab()
 840                                }
 841                                StartThreadIn::LinkedWorktree { path, .. } => {
 842                                    is_worktree_flag_enabled && path.exists()
 843                                }
 844                            };
 845                            if is_valid {
 846                                panel.start_thread_in = start_thread_in.clone();
 847                            } else {
 848                                log::info!(
 849                                    "deserialized start_thread_in {:?} is no longer valid, falling back to LocalProject",
 850                                    start_thread_in,
 851                                );
 852                            }
 853                        }
 854                    } else if let Some(agent) = global_fallback {
 855                        panel.selected_agent = agent;
 856                    }
 857                    cx.notify();
 858                });
 859
 860                if let Some(thread_info) = last_active_thread {
 861                    let agent = thread_info.agent_type.clone();
 862                    panel.update(cx, |panel, cx| {
 863                        panel.selected_agent = agent.clone();
 864                        panel.load_agent_thread(
 865                            agent,
 866                            thread_info.session_id.clone().into(),
 867                            thread_info.work_dirs.as_ref().map(|dirs| PathList::deserialize(dirs)),
 868                            thread_info.title.as_ref().map(|t| t.clone().into()),
 869                            false,
 870                            window,
 871                            cx,
 872                        );
 873                    });
 874                }
 875                panel
 876            })?;
 877
 878            Ok(panel)
 879        })
 880    }
 881
 882    pub(crate) fn new(
 883        workspace: &Workspace,
 884        prompt_store: Option<Entity<PromptStore>>,
 885        window: &mut Window,
 886        cx: &mut Context<Self>,
 887    ) -> Self {
 888        let fs = workspace.app_state().fs.clone();
 889        let user_store = workspace.app_state().user_store.clone();
 890        let project = workspace.project();
 891        let language_registry = project.read(cx).languages().clone();
 892        let client = workspace.client().clone();
 893        let workspace_id = workspace.database_id();
 894        let workspace = workspace.weak_handle();
 895
 896        let context_server_registry =
 897            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 898
 899        let thread_store = ThreadStore::global(cx);
 900
 901        let active_view = ActiveView::Uninitialized;
 902
 903        let weak_panel = cx.entity().downgrade();
 904
 905        window.defer(cx, move |window, cx| {
 906            let panel = weak_panel.clone();
 907            let agent_navigation_menu =
 908                ContextMenu::build_persistent(window, cx, move |mut menu, window, cx| {
 909                    if let Some(panel) = panel.upgrade() {
 910                        if let Some(history) = panel
 911                            .update(cx, |panel, cx| panel.history_for_selected_agent(window, cx))
 912                        {
 913                            menu = Self::populate_recently_updated_menu_section(
 914                                menu, panel, history, cx,
 915                            );
 916                            menu = menu.action("View All", Box::new(OpenHistory));
 917                        }
 918                    }
 919
 920                    menu = menu
 921                        .fixed_width(px(320.).into())
 922                        .keep_open_on_confirm(false)
 923                        .key_context("NavigationMenu");
 924
 925                    menu
 926                });
 927            weak_panel
 928                .update(cx, |panel, cx| {
 929                    cx.subscribe_in(
 930                        &agent_navigation_menu,
 931                        window,
 932                        |_, menu, _: &DismissEvent, window, cx| {
 933                            menu.update(cx, |menu, _| {
 934                                menu.clear_selected();
 935                            });
 936                            cx.focus_self(window);
 937                        },
 938                    )
 939                    .detach();
 940                    panel.agent_navigation_menu = Some(agent_navigation_menu);
 941                })
 942                .ok();
 943        });
 944
 945        let weak_panel = cx.entity().downgrade();
 946        let onboarding = cx.new(|cx| {
 947            AgentPanelOnboarding::new(
 948                user_store.clone(),
 949                client,
 950                move |_window, cx| {
 951                    weak_panel
 952                        .update(cx, |panel, _| {
 953                            panel
 954                                .on_boarding_upsell_dismissed
 955                                .store(true, Ordering::Release);
 956                        })
 957                        .ok();
 958                    OnboardingUpsell::set_dismissed(true, cx);
 959                },
 960                cx,
 961            )
 962        });
 963
 964        // Subscribe to extension events to sync agent servers when extensions change
 965        let extension_subscription = if let Some(extension_events) = ExtensionEvents::try_global(cx)
 966        {
 967            Some(
 968                cx.subscribe(&extension_events, |this, _source, event, cx| match event {
 969                    extension::Event::ExtensionInstalled(_)
 970                    | extension::Event::ExtensionUninstalled(_)
 971                    | extension::Event::ExtensionsInstalledChanged => {
 972                        this.sync_agent_servers_from_extensions(cx);
 973                    }
 974                    _ => {}
 975                }),
 976            )
 977        } else {
 978            None
 979        };
 980
 981        let connection_store = cx.new(|cx| {
 982            let mut store = AgentConnectionStore::new(project.clone(), cx);
 983            // Register the native agent right away, so that it is available for
 984            // the inline assistant etc.
 985            store.request_connection(
 986                Agent::NativeAgent,
 987                Agent::NativeAgent.server(fs.clone(), thread_store.clone()),
 988                cx,
 989            );
 990            store
 991        });
 992        let _project_subscription =
 993            cx.subscribe(&project, |this, _project, event, cx| match event {
 994                project::Event::WorktreeAdded(_)
 995                | project::Event::WorktreeRemoved(_)
 996                | project::Event::WorktreeOrderChanged => {
 997                    this.update_thread_work_dirs(cx);
 998                }
 999                _ => {}
1000            });
1001
1002        let mut panel = Self {
1003            workspace_id,
1004            active_view,
1005            workspace,
1006            user_store,
1007            project: project.clone(),
1008            fs: fs.clone(),
1009            language_registry,
1010            prompt_store,
1011            connection_store,
1012            configuration: None,
1013            configuration_subscription: None,
1014            focus_handle: cx.focus_handle(),
1015            context_server_registry,
1016            previous_view: None,
1017            background_threads: HashMap::default(),
1018            new_thread_menu_handle: PopoverMenuHandle::default(),
1019            start_thread_in_menu_handle: PopoverMenuHandle::default(),
1020            thread_branch_menu_handle: PopoverMenuHandle::default(),
1021            agent_panel_menu_handle: PopoverMenuHandle::default(),
1022            agent_navigation_menu_handle: PopoverMenuHandle::default(),
1023            agent_navigation_menu: None,
1024            _extension_subscription: extension_subscription,
1025            _project_subscription,
1026            zoomed: false,
1027            pending_serialization: None,
1028            onboarding,
1029            thread_store,
1030            selected_agent: Agent::default(),
1031            start_thread_in: StartThreadIn::default(),
1032            worktree_creation_status: None,
1033            _thread_view_subscription: None,
1034            _active_thread_focus_subscription: None,
1035            _worktree_creation_task: None,
1036            show_trust_workspace_message: false,
1037            on_boarding_upsell_dismissed: AtomicBool::new(OnboardingUpsell::dismissed(cx)),
1038            _active_view_observation: None,
1039        };
1040
1041        // Initial sync of agent servers from extensions
1042        panel.sync_agent_servers_from_extensions(cx);
1043        panel
1044    }
1045
1046    pub fn toggle_focus(
1047        workspace: &mut Workspace,
1048        _: &ToggleFocus,
1049        window: &mut Window,
1050        cx: &mut Context<Workspace>,
1051    ) {
1052        if workspace
1053            .panel::<Self>(cx)
1054            .is_some_and(|panel| panel.read(cx).enabled(cx))
1055        {
1056            workspace.toggle_panel_focus::<Self>(window, cx);
1057        }
1058    }
1059
1060    pub fn toggle(
1061        workspace: &mut Workspace,
1062        _: &Toggle,
1063        window: &mut Window,
1064        cx: &mut Context<Workspace>,
1065    ) {
1066        if workspace
1067            .panel::<Self>(cx)
1068            .is_some_and(|panel| panel.read(cx).enabled(cx))
1069        {
1070            if !workspace.toggle_panel_focus::<Self>(window, cx) {
1071                workspace.close_panel::<Self>(window, cx);
1072            }
1073        }
1074    }
1075
1076    pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
1077        &self.prompt_store
1078    }
1079
1080    pub fn thread_store(&self) -> &Entity<ThreadStore> {
1081        &self.thread_store
1082    }
1083
1084    pub fn connection_store(&self) -> &Entity<AgentConnectionStore> {
1085        &self.connection_store
1086    }
1087
1088    pub fn open_thread(
1089        &mut self,
1090        session_id: acp::SessionId,
1091        work_dirs: Option<PathList>,
1092        title: Option<SharedString>,
1093        window: &mut Window,
1094        cx: &mut Context<Self>,
1095    ) {
1096        self.external_thread(
1097            Some(crate::Agent::NativeAgent),
1098            Some(session_id),
1099            work_dirs,
1100            title,
1101            None,
1102            true,
1103            window,
1104            cx,
1105        );
1106    }
1107
1108    pub(crate) fn context_server_registry(&self) -> &Entity<ContextServerRegistry> {
1109        &self.context_server_registry
1110    }
1111
1112    pub fn is_visible(workspace: &Entity<Workspace>, cx: &App) -> bool {
1113        let workspace_read = workspace.read(cx);
1114
1115        workspace_read
1116            .panel::<AgentPanel>(cx)
1117            .map(|panel| {
1118                let panel_id = Entity::entity_id(&panel);
1119
1120                workspace_read.all_docks().iter().any(|dock| {
1121                    dock.read(cx)
1122                        .visible_panel()
1123                        .is_some_and(|visible_panel| visible_panel.panel_id() == panel_id)
1124                })
1125            })
1126            .unwrap_or(false)
1127    }
1128
1129    pub fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
1130        self.reset_start_thread_in_to_default(cx);
1131        self.external_thread(None, None, None, None, None, true, window, cx);
1132    }
1133
1134    fn new_native_agent_thread_from_summary(
1135        &mut self,
1136        action: &NewNativeAgentThreadFromSummary,
1137        window: &mut Window,
1138        cx: &mut Context<Self>,
1139    ) {
1140        let session_id = action.from_session_id.clone();
1141
1142        let Some(history) = self
1143            .connection_store
1144            .read(cx)
1145            .entry(&Agent::NativeAgent)
1146            .and_then(|e| e.read(cx).history().cloned())
1147        else {
1148            debug_panic!("Native agent is not registered");
1149            return;
1150        };
1151
1152        cx.spawn_in(window, async move |this, cx| {
1153            this.update_in(cx, |this, window, cx| {
1154                let thread = history
1155                    .read(cx)
1156                    .session_for_id(&session_id)
1157                    .context("Session not found")?;
1158
1159                this.external_thread(
1160                    Some(Agent::NativeAgent),
1161                    None,
1162                    None,
1163                    None,
1164                    Some(AgentInitialContent::ThreadSummary {
1165                        session_id: thread.session_id,
1166                        title: thread.title,
1167                    }),
1168                    true,
1169                    window,
1170                    cx,
1171                );
1172                anyhow::Ok(())
1173            })
1174        })
1175        .detach_and_log_err(cx);
1176    }
1177
1178    fn external_thread(
1179        &mut self,
1180        agent_choice: Option<crate::Agent>,
1181        resume_session_id: Option<acp::SessionId>,
1182        work_dirs: Option<PathList>,
1183        title: Option<SharedString>,
1184        initial_content: Option<AgentInitialContent>,
1185        focus: bool,
1186        window: &mut Window,
1187        cx: &mut Context<Self>,
1188    ) {
1189        let workspace = self.workspace.clone();
1190        let project = self.project.clone();
1191        let fs = self.fs.clone();
1192        let thread_store = self.thread_store.clone();
1193
1194        let agent = agent_choice.unwrap_or_else(|| {
1195            if self.project.read(cx).is_via_collab() {
1196                Agent::NativeAgent
1197            } else {
1198                self.selected_agent.clone()
1199            }
1200        });
1201
1202        let server = agent.server(fs, thread_store);
1203        self.create_agent_thread(
1204            server,
1205            resume_session_id,
1206            work_dirs,
1207            title,
1208            initial_content,
1209            workspace,
1210            project,
1211            agent,
1212            focus,
1213            window,
1214            cx,
1215        );
1216    }
1217
1218    fn deploy_rules_library(
1219        &mut self,
1220        action: &OpenRulesLibrary,
1221        _window: &mut Window,
1222        cx: &mut Context<Self>,
1223    ) {
1224        open_rules_library(
1225            self.language_registry.clone(),
1226            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
1227            action
1228                .prompt_to_select
1229                .map(|uuid| UserPromptId(uuid).into()),
1230            cx,
1231        )
1232        .detach_and_log_err(cx);
1233    }
1234
1235    fn expand_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1236        let Some(conversation_view) = self.active_conversation_view() else {
1237            return;
1238        };
1239
1240        let Some(active_thread) = conversation_view.read(cx).active_thread().cloned() else {
1241            return;
1242        };
1243
1244        active_thread.update(cx, |active_thread, cx| {
1245            active_thread.expand_message_editor(&ExpandMessageEditor, window, cx);
1246            active_thread.focus_handle(cx).focus(window, cx);
1247        })
1248    }
1249
1250    fn has_history_for_selected_agent(&self, cx: &App) -> bool {
1251        match &self.selected_agent {
1252            Agent::NativeAgent => true,
1253            Agent::Custom { .. } => self
1254                .connection_store
1255                .read(cx)
1256                .entry(&self.selected_agent)
1257                .map_or(false, |entry| entry.read(cx).history().is_some()),
1258        }
1259    }
1260
1261    fn history_for_selected_agent(
1262        &self,
1263        window: &mut Window,
1264        cx: &mut Context<Self>,
1265    ) -> Option<Entity<ThreadHistoryView>> {
1266        let agent = self.selected_agent.clone();
1267        let history = self
1268            .connection_store
1269            .read(cx)
1270            .entry(&agent)?
1271            .read(cx)
1272            .history()?
1273            .clone();
1274        Some(self.create_thread_history_view(agent, history, window, cx))
1275    }
1276
1277    fn create_thread_history_view(
1278        &self,
1279        agent: Agent,
1280        history: Entity<ThreadHistory>,
1281        window: &mut Window,
1282        cx: &mut Context<Self>,
1283    ) -> Entity<ThreadHistoryView> {
1284        let view = cx.new(|cx| ThreadHistoryView::new(history.clone(), window, cx));
1285        cx.subscribe_in(
1286            &view,
1287            window,
1288            move |this, _, event, window, cx| match event {
1289                ThreadHistoryViewEvent::Open(thread) => {
1290                    this.load_agent_thread(
1291                        agent.clone(),
1292                        thread.session_id.clone(),
1293                        thread.work_dirs.clone(),
1294                        thread.title.clone(),
1295                        true,
1296                        window,
1297                        cx,
1298                    );
1299                }
1300            },
1301        )
1302        .detach();
1303        view
1304    }
1305
1306    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1307        let Some(view) = self.history_for_selected_agent(window, cx) else {
1308            return;
1309        };
1310
1311        if let ActiveView::History { view: active_view } = &self.active_view {
1312            if active_view == &view {
1313                if let Some(previous_view) = self.previous_view.take() {
1314                    self.set_active_view(previous_view, true, window, cx);
1315                }
1316                return;
1317            }
1318        }
1319
1320        self.set_active_view(ActiveView::History { view }, true, window, cx);
1321        cx.notify();
1322    }
1323
1324    pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1325        match self.active_view {
1326            ActiveView::Configuration | ActiveView::History { .. } => {
1327                if let Some(previous_view) = self.previous_view.take() {
1328                    self.set_active_view(previous_view, true, window, cx);
1329                }
1330                cx.notify();
1331            }
1332            _ => {}
1333        }
1334    }
1335
1336    pub fn toggle_navigation_menu(
1337        &mut self,
1338        _: &ToggleNavigationMenu,
1339        window: &mut Window,
1340        cx: &mut Context<Self>,
1341    ) {
1342        if !self.has_history_for_selected_agent(cx) {
1343            return;
1344        }
1345        self.agent_navigation_menu_handle.toggle(window, cx);
1346    }
1347
1348    pub fn toggle_options_menu(
1349        &mut self,
1350        _: &ToggleOptionsMenu,
1351        window: &mut Window,
1352        cx: &mut Context<Self>,
1353    ) {
1354        self.agent_panel_menu_handle.toggle(window, cx);
1355    }
1356
1357    pub fn toggle_new_thread_menu(
1358        &mut self,
1359        _: &ToggleNewThreadMenu,
1360        window: &mut Window,
1361        cx: &mut Context<Self>,
1362    ) {
1363        self.new_thread_menu_handle.toggle(window, cx);
1364    }
1365
1366    pub fn increase_font_size(
1367        &mut self,
1368        action: &IncreaseBufferFontSize,
1369        _: &mut Window,
1370        cx: &mut Context<Self>,
1371    ) {
1372        self.handle_font_size_action(action.persist, px(1.0), cx);
1373    }
1374
1375    pub fn decrease_font_size(
1376        &mut self,
1377        action: &DecreaseBufferFontSize,
1378        _: &mut Window,
1379        cx: &mut Context<Self>,
1380    ) {
1381        self.handle_font_size_action(action.persist, px(-1.0), cx);
1382    }
1383
1384    fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1385        match self.active_view.which_font_size_used() {
1386            WhichFontSize::AgentFont => {
1387                if persist {
1388                    update_settings_file(self.fs.clone(), cx, move |settings, cx| {
1389                        let agent_ui_font_size =
1390                            ThemeSettings::get_global(cx).agent_ui_font_size(cx) + delta;
1391                        let agent_buffer_font_size =
1392                            ThemeSettings::get_global(cx).agent_buffer_font_size(cx) + delta;
1393
1394                        let _ = settings.theme.agent_ui_font_size.insert(
1395                            f32::from(theme_settings::clamp_font_size(agent_ui_font_size)).into(),
1396                        );
1397                        let _ = settings.theme.agent_buffer_font_size.insert(
1398                            f32::from(theme_settings::clamp_font_size(agent_buffer_font_size))
1399                                .into(),
1400                        );
1401                    });
1402                } else {
1403                    theme_settings::adjust_agent_ui_font_size(cx, |size| size + delta);
1404                    theme_settings::adjust_agent_buffer_font_size(cx, |size| size + delta);
1405                }
1406            }
1407            WhichFontSize::None => {}
1408        }
1409    }
1410
1411    pub fn reset_font_size(
1412        &mut self,
1413        action: &ResetBufferFontSize,
1414        _: &mut Window,
1415        cx: &mut Context<Self>,
1416    ) {
1417        if action.persist {
1418            update_settings_file(self.fs.clone(), cx, move |settings, _| {
1419                settings.theme.agent_ui_font_size = None;
1420                settings.theme.agent_buffer_font_size = None;
1421            });
1422        } else {
1423            theme_settings::reset_agent_ui_font_size(cx);
1424            theme_settings::reset_agent_buffer_font_size(cx);
1425        }
1426    }
1427
1428    pub fn reset_agent_zoom(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1429        theme_settings::reset_agent_ui_font_size(cx);
1430        theme_settings::reset_agent_buffer_font_size(cx);
1431    }
1432
1433    pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1434        if self.zoomed {
1435            cx.emit(PanelEvent::ZoomOut);
1436        } else {
1437            if !self.focus_handle(cx).contains_focused(window, cx) {
1438                cx.focus_self(window);
1439            }
1440            cx.emit(PanelEvent::ZoomIn);
1441        }
1442    }
1443
1444    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1445        let agent_server_store = self.project.read(cx).agent_server_store().clone();
1446        let context_server_store = self.project.read(cx).context_server_store();
1447        let fs = self.fs.clone();
1448
1449        self.set_active_view(ActiveView::Configuration, true, window, cx);
1450        self.configuration = Some(cx.new(|cx| {
1451            AgentConfiguration::new(
1452                fs,
1453                agent_server_store,
1454                self.connection_store.clone(),
1455                context_server_store,
1456                self.context_server_registry.clone(),
1457                self.language_registry.clone(),
1458                self.workspace.clone(),
1459                window,
1460                cx,
1461            )
1462        }));
1463
1464        if let Some(configuration) = self.configuration.as_ref() {
1465            self.configuration_subscription = Some(cx.subscribe_in(
1466                configuration,
1467                window,
1468                Self::handle_agent_configuration_event,
1469            ));
1470
1471            configuration.focus_handle(cx).focus(window, cx);
1472        }
1473    }
1474
1475    pub(crate) fn open_active_thread_as_markdown(
1476        &mut self,
1477        _: &OpenActiveThreadAsMarkdown,
1478        window: &mut Window,
1479        cx: &mut Context<Self>,
1480    ) {
1481        if let Some(workspace) = self.workspace.upgrade()
1482            && let Some(conversation_view) = self.active_conversation_view()
1483            && let Some(active_thread) = conversation_view.read(cx).active_thread().cloned()
1484        {
1485            active_thread.update(cx, |thread, cx| {
1486                thread
1487                    .open_thread_as_markdown(workspace, window, cx)
1488                    .detach_and_log_err(cx);
1489            });
1490        }
1491    }
1492
1493    fn copy_thread_to_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1494        let Some(thread) = self.active_native_agent_thread(cx) else {
1495            Self::show_deferred_toast(&self.workspace, "No active native thread to copy", cx);
1496            return;
1497        };
1498
1499        let workspace = self.workspace.clone();
1500        let load_task = thread.read(cx).to_db(cx);
1501
1502        cx.spawn_in(window, async move |_this, cx| {
1503            let db_thread = load_task.await;
1504            let shared_thread = SharedThread::from_db_thread(&db_thread);
1505            let thread_data = shared_thread.to_bytes()?;
1506            let encoded = base64::Engine::encode(&base64::prelude::BASE64_STANDARD, &thread_data);
1507
1508            cx.update(|_window, cx| {
1509                cx.write_to_clipboard(ClipboardItem::new_string(encoded));
1510                if let Some(workspace) = workspace.upgrade() {
1511                    workspace.update(cx, |workspace, cx| {
1512                        struct ThreadCopiedToast;
1513                        workspace.show_toast(
1514                            workspace::Toast::new(
1515                                workspace::notifications::NotificationId::unique::<ThreadCopiedToast>(),
1516                                "Thread copied to clipboard (base64 encoded)",
1517                            )
1518                            .autohide(),
1519                            cx,
1520                        );
1521                    });
1522                }
1523            })?;
1524
1525            anyhow::Ok(())
1526        })
1527        .detach_and_log_err(cx);
1528    }
1529
1530    fn show_deferred_toast(
1531        workspace: &WeakEntity<workspace::Workspace>,
1532        message: &'static str,
1533        cx: &mut App,
1534    ) {
1535        let workspace = workspace.clone();
1536        cx.defer(move |cx| {
1537            if let Some(workspace) = workspace.upgrade() {
1538                workspace.update(cx, |workspace, cx| {
1539                    struct ClipboardToast;
1540                    workspace.show_toast(
1541                        workspace::Toast::new(
1542                            workspace::notifications::NotificationId::unique::<ClipboardToast>(),
1543                            message,
1544                        )
1545                        .autohide(),
1546                        cx,
1547                    );
1548                });
1549            }
1550        });
1551    }
1552
1553    fn load_thread_from_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1554        let Some(clipboard) = cx.read_from_clipboard() else {
1555            Self::show_deferred_toast(&self.workspace, "No clipboard content available", cx);
1556            return;
1557        };
1558
1559        let Some(encoded) = clipboard.text() else {
1560            Self::show_deferred_toast(&self.workspace, "Clipboard does not contain text", cx);
1561            return;
1562        };
1563
1564        let thread_data = match base64::Engine::decode(&base64::prelude::BASE64_STANDARD, &encoded)
1565        {
1566            Ok(data) => data,
1567            Err(_) => {
1568                Self::show_deferred_toast(
1569                    &self.workspace,
1570                    "Failed to decode clipboard content (expected base64)",
1571                    cx,
1572                );
1573                return;
1574            }
1575        };
1576
1577        let shared_thread = match SharedThread::from_bytes(&thread_data) {
1578            Ok(thread) => thread,
1579            Err(_) => {
1580                Self::show_deferred_toast(
1581                    &self.workspace,
1582                    "Failed to parse thread data from clipboard",
1583                    cx,
1584                );
1585                return;
1586            }
1587        };
1588
1589        let db_thread = shared_thread.to_db_thread();
1590        let session_id = acp::SessionId::new(uuid::Uuid::new_v4().to_string());
1591        let thread_store = self.thread_store.clone();
1592        let title = db_thread.title.clone();
1593        let workspace = self.workspace.clone();
1594
1595        cx.spawn_in(window, async move |this, cx| {
1596            thread_store
1597                .update(&mut cx.clone(), |store, cx| {
1598                    store.save_thread(session_id.clone(), db_thread, Default::default(), cx)
1599                })
1600                .await?;
1601
1602            this.update_in(cx, |this, window, cx| {
1603                this.open_thread(session_id, None, Some(title), window, cx);
1604            })?;
1605
1606            this.update_in(cx, |_, _window, cx| {
1607                if let Some(workspace) = workspace.upgrade() {
1608                    workspace.update(cx, |workspace, cx| {
1609                        struct ThreadLoadedToast;
1610                        workspace.show_toast(
1611                            workspace::Toast::new(
1612                                workspace::notifications::NotificationId::unique::<ThreadLoadedToast>(),
1613                                "Thread loaded from clipboard",
1614                            )
1615                            .autohide(),
1616                            cx,
1617                        );
1618                    });
1619                }
1620            })?;
1621
1622            anyhow::Ok(())
1623        })
1624        .detach_and_log_err(cx);
1625    }
1626
1627    fn handle_agent_configuration_event(
1628        &mut self,
1629        _entity: &Entity<AgentConfiguration>,
1630        event: &AssistantConfigurationEvent,
1631        window: &mut Window,
1632        cx: &mut Context<Self>,
1633    ) {
1634        match event {
1635            AssistantConfigurationEvent::NewThread(provider) => {
1636                if LanguageModelRegistry::read_global(cx)
1637                    .default_model()
1638                    .is_none_or(|model| model.provider.id() != provider.id())
1639                    && let Some(model) = provider.default_model(cx)
1640                {
1641                    update_settings_file(self.fs.clone(), cx, move |settings, _| {
1642                        let provider = model.provider_id().0.to_string();
1643                        let enable_thinking = model.supports_thinking();
1644                        let effort = model
1645                            .default_effort_level()
1646                            .map(|effort| effort.value.to_string());
1647                        let model = model.id().0.to_string();
1648                        settings
1649                            .agent
1650                            .get_or_insert_default()
1651                            .set_model(LanguageModelSelection {
1652                                provider: LanguageModelProviderSetting(provider),
1653                                model,
1654                                enable_thinking,
1655                                effort,
1656                            })
1657                    });
1658                }
1659
1660                self.new_thread(&NewThread, window, cx);
1661                if let Some((thread, model)) = self
1662                    .active_native_agent_thread(cx)
1663                    .zip(provider.default_model(cx))
1664                {
1665                    thread.update(cx, |thread, cx| {
1666                        thread.set_model(model, cx);
1667                    });
1668                }
1669            }
1670        }
1671    }
1672
1673    pub fn workspace_id(&self) -> Option<WorkspaceId> {
1674        self.workspace_id
1675    }
1676
1677    pub fn background_threads(&self) -> &HashMap<acp::SessionId, Entity<ConversationView>> {
1678        &self.background_threads
1679    }
1680
1681    pub fn active_conversation_view(&self) -> Option<&Entity<ConversationView>> {
1682        match &self.active_view {
1683            ActiveView::AgentThread { conversation_view } => Some(conversation_view),
1684            _ => None,
1685        }
1686    }
1687
1688    pub fn active_thread_view(&self, cx: &App) -> Option<Entity<ThreadView>> {
1689        let server_view = self.active_conversation_view()?;
1690        server_view.read(cx).active_thread().cloned()
1691    }
1692
1693    pub fn active_agent_thread(&self, cx: &App) -> Option<Entity<AcpThread>> {
1694        match &self.active_view {
1695            ActiveView::AgentThread {
1696                conversation_view, ..
1697            } => conversation_view
1698                .read(cx)
1699                .active_thread()
1700                .map(|r| r.read(cx).thread.clone()),
1701            _ => None,
1702        }
1703    }
1704
1705    /// Returns the primary thread views for all retained connections: the
1706    pub fn is_background_thread(&self, session_id: &acp::SessionId) -> bool {
1707        self.background_threads.contains_key(session_id)
1708    }
1709
1710    pub fn cancel_thread(&self, session_id: &acp::SessionId, cx: &mut Context<Self>) -> bool {
1711        let conversation_views = self
1712            .active_conversation_view()
1713            .into_iter()
1714            .chain(self.background_threads.values());
1715
1716        for conversation_view in conversation_views {
1717            if let Some(thread_view) = conversation_view.read(cx).thread_view(session_id) {
1718                thread_view.update(cx, |view, cx| view.cancel_generation(cx));
1719                return true;
1720            }
1721        }
1722        false
1723    }
1724
1725    /// active thread plus any background threads that are still running or
1726    /// completed but unseen.
1727    pub fn parent_threads(&self, cx: &App) -> Vec<Entity<ThreadView>> {
1728        let mut views = Vec::new();
1729
1730        if let Some(server_view) = self.active_conversation_view() {
1731            if let Some(thread_view) = server_view.read(cx).root_thread(cx) {
1732                views.push(thread_view);
1733            }
1734        }
1735
1736        for server_view in self.background_threads.values() {
1737            if let Some(thread_view) = server_view.read(cx).root_thread(cx) {
1738                views.push(thread_view);
1739            }
1740        }
1741
1742        views
1743    }
1744
1745    fn update_thread_work_dirs(&self, cx: &mut Context<Self>) {
1746        let new_work_dirs = self.project.read(cx).default_path_list(cx);
1747
1748        if let Some(conversation_view) = self.active_conversation_view() {
1749            conversation_view.update(cx, |conversation_view, cx| {
1750                conversation_view.set_work_dirs(new_work_dirs.clone(), cx);
1751            });
1752        }
1753
1754        for conversation_view in self.background_threads.values() {
1755            conversation_view.update(cx, |conversation_view, cx| {
1756                conversation_view.set_work_dirs(new_work_dirs.clone(), cx);
1757            });
1758        }
1759    }
1760
1761    fn retain_running_thread(&mut self, old_view: ActiveView, cx: &mut Context<Self>) {
1762        let ActiveView::AgentThread { conversation_view } = old_view else {
1763            return;
1764        };
1765
1766        let Some(thread_view) = conversation_view.read(cx).root_thread(cx) else {
1767            return;
1768        };
1769
1770        if thread_view.read(cx).thread.read(cx).entries().is_empty() {
1771            return;
1772        }
1773
1774        self.background_threads
1775            .insert(thread_view.read(cx).id.clone(), conversation_view);
1776        self.cleanup_background_threads(cx);
1777    }
1778
1779    /// We keep threads that are:
1780    /// - Still running
1781    /// - Do not support reloading the full session
1782    /// - Have had the most recent events (up to 5 idle threads)
1783    fn cleanup_background_threads(&mut self, cx: &App) {
1784        let mut potential_removals = self
1785            .background_threads
1786            .iter()
1787            .filter(|(_id, view)| {
1788                let Some(thread_view) = view.read(cx).root_thread(cx) else {
1789                    return true;
1790                };
1791                let thread = thread_view.read(cx).thread.read(cx);
1792                thread.connection().supports_load_session() && thread.status() == ThreadStatus::Idle
1793            })
1794            .collect::<Vec<_>>();
1795
1796        const MAX_IDLE_BACKGROUND_THREADS: usize = 5;
1797
1798        potential_removals.sort_unstable_by_key(|(_, view)| view.read(cx).updated_at(cx));
1799        let n = potential_removals
1800            .len()
1801            .saturating_sub(MAX_IDLE_BACKGROUND_THREADS);
1802        let to_remove = potential_removals
1803            .into_iter()
1804            .map(|(id, _)| id.clone())
1805            .take(n)
1806            .collect::<Vec<_>>();
1807        for id in to_remove {
1808            self.background_threads.remove(&id);
1809        }
1810    }
1811
1812    pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
1813        match &self.active_view {
1814            ActiveView::AgentThread {
1815                conversation_view, ..
1816            } => conversation_view.read(cx).as_native_thread(cx),
1817            _ => None,
1818        }
1819    }
1820
1821    fn set_active_view(
1822        &mut self,
1823        new_view: ActiveView,
1824        focus: bool,
1825        window: &mut Window,
1826        cx: &mut Context<Self>,
1827    ) {
1828        let was_in_agent_history = matches!(self.active_view, ActiveView::History { .. });
1829        let current_is_uninitialized = matches!(self.active_view, ActiveView::Uninitialized);
1830        let current_is_history = matches!(self.active_view, ActiveView::History { .. });
1831        let new_is_history = matches!(new_view, ActiveView::History { .. });
1832
1833        let current_is_config = matches!(self.active_view, ActiveView::Configuration);
1834        let new_is_config = matches!(new_view, ActiveView::Configuration);
1835
1836        let current_is_overlay = current_is_history || current_is_config;
1837        let new_is_overlay = new_is_history || new_is_config;
1838
1839        if current_is_uninitialized || (current_is_overlay && !new_is_overlay) {
1840            self.active_view = new_view;
1841        } else if !current_is_overlay && new_is_overlay {
1842            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1843        } else {
1844            let old_view = std::mem::replace(&mut self.active_view, new_view);
1845            if !new_is_overlay {
1846                if let Some(previous) = self.previous_view.take() {
1847                    self.retain_running_thread(previous, cx);
1848                }
1849            }
1850            self.retain_running_thread(old_view, cx);
1851        }
1852
1853        // Subscribe to the active ThreadView's events (e.g. FirstSendRequested)
1854        // so the panel can intercept the first send for worktree creation.
1855        // Re-subscribe whenever the ConnectionView changes, since the inner
1856        // ThreadView may have been replaced (e.g. navigating between threads).
1857        self._active_view_observation = match &self.active_view {
1858            ActiveView::AgentThread { conversation_view } => {
1859                self._thread_view_subscription =
1860                    Self::subscribe_to_active_thread_view(conversation_view, window, cx);
1861                let focus_handle = conversation_view.focus_handle(cx);
1862                self._active_thread_focus_subscription =
1863                    Some(cx.on_focus_in(&focus_handle, window, |_this, _window, cx| {
1864                        cx.emit(AgentPanelEvent::ThreadFocused);
1865                        cx.notify();
1866                    }));
1867                Some(cx.observe_in(
1868                    conversation_view,
1869                    window,
1870                    |this, server_view, window, cx| {
1871                        this._thread_view_subscription =
1872                            Self::subscribe_to_active_thread_view(&server_view, window, cx);
1873                        cx.emit(AgentPanelEvent::ActiveViewChanged);
1874                        this.serialize(cx);
1875                        cx.notify();
1876                    },
1877                ))
1878            }
1879            _ => {
1880                self._thread_view_subscription = None;
1881                self._active_thread_focus_subscription = None;
1882                None
1883            }
1884        };
1885
1886        if let ActiveView::History { view } = &self.active_view {
1887            if !was_in_agent_history {
1888                view.update(cx, |view, cx| {
1889                    view.history()
1890                        .update(cx, |history, cx| history.refresh_full_history(cx))
1891                });
1892            }
1893        }
1894
1895        if focus {
1896            self.focus_handle(cx).focus(window, cx);
1897        }
1898        cx.emit(AgentPanelEvent::ActiveViewChanged);
1899    }
1900
1901    fn populate_recently_updated_menu_section(
1902        mut menu: ContextMenu,
1903        panel: Entity<Self>,
1904        view: Entity<ThreadHistoryView>,
1905        cx: &mut Context<ContextMenu>,
1906    ) -> ContextMenu {
1907        let entries = view
1908            .read(cx)
1909            .history()
1910            .read(cx)
1911            .sessions()
1912            .iter()
1913            .take(RECENTLY_UPDATED_MENU_LIMIT)
1914            .cloned()
1915            .collect::<Vec<_>>();
1916
1917        if entries.is_empty() {
1918            return menu;
1919        }
1920
1921        menu = menu.header("Recently Updated");
1922
1923        for entry in entries {
1924            let title = entry
1925                .title
1926                .as_ref()
1927                .filter(|title| !title.is_empty())
1928                .cloned()
1929                .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE));
1930
1931            menu = menu.entry(title, None, {
1932                let panel = panel.downgrade();
1933                let entry = entry.clone();
1934                move |window, cx| {
1935                    let entry = entry.clone();
1936                    panel
1937                        .update(cx, move |this, cx| {
1938                            if let Some(agent) = this.selected_agent() {
1939                                this.load_agent_thread(
1940                                    agent,
1941                                    entry.session_id.clone(),
1942                                    entry.work_dirs.clone(),
1943                                    entry.title.clone(),
1944                                    true,
1945                                    window,
1946                                    cx,
1947                                );
1948                            }
1949                        })
1950                        .ok();
1951                }
1952            });
1953        }
1954
1955        menu.separator()
1956    }
1957
1958    fn subscribe_to_active_thread_view(
1959        server_view: &Entity<ConversationView>,
1960        window: &mut Window,
1961        cx: &mut Context<Self>,
1962    ) -> Option<Subscription> {
1963        server_view.read(cx).active_thread().cloned().map(|tv| {
1964            cx.subscribe_in(
1965                &tv,
1966                window,
1967                |this, view, event: &AcpThreadViewEvent, window, cx| match event {
1968                    AcpThreadViewEvent::FirstSendRequested { content } => {
1969                        this.handle_first_send_requested(view.clone(), content.clone(), window, cx);
1970                    }
1971                    AcpThreadViewEvent::MessageSentOrQueued => {
1972                        let session_id = view.read(cx).thread.read(cx).session_id().clone();
1973                        cx.emit(AgentPanelEvent::MessageSentOrQueued { session_id });
1974                    }
1975                },
1976            )
1977        })
1978    }
1979
1980    pub fn start_thread_in(&self) -> &StartThreadIn {
1981        &self.start_thread_in
1982    }
1983
1984    fn set_start_thread_in(
1985        &mut self,
1986        action: &StartThreadIn,
1987        window: &mut Window,
1988        cx: &mut Context<Self>,
1989    ) {
1990        let new_target = match action {
1991            StartThreadIn::LocalProject => StartThreadIn::LocalProject,
1992            StartThreadIn::NewWorktree { .. } => {
1993                if !cx.has_flag::<AgentV2FeatureFlag>() {
1994                    return;
1995                }
1996                if !self.project_has_git_repository(cx) {
1997                    log::error!(
1998                        "set_start_thread_in: cannot use worktree mode without a git repository"
1999                    );
2000                    return;
2001                }
2002                if self.project.read(cx).is_via_collab() {
2003                    log::error!(
2004                        "set_start_thread_in: cannot use worktree mode in a collab project"
2005                    );
2006                    return;
2007                }
2008                action.clone()
2009            }
2010            StartThreadIn::LinkedWorktree { .. } => {
2011                if !cx.has_flag::<AgentV2FeatureFlag>() {
2012                    return;
2013                }
2014                if !self.project_has_git_repository(cx) {
2015                    log::error!(
2016                        "set_start_thread_in: cannot use LinkedWorktree without a git repository"
2017                    );
2018                    return;
2019                }
2020                if self.project.read(cx).is_via_collab() {
2021                    log::error!(
2022                        "set_start_thread_in: cannot use LinkedWorktree in a collab project"
2023                    );
2024                    return;
2025                }
2026                action.clone()
2027            }
2028        };
2029        self.start_thread_in = new_target;
2030        if let Some(thread) = self.active_thread_view(cx) {
2031            thread.update(cx, |thread, cx| thread.focus_handle(cx).focus(window, cx));
2032        }
2033        self.serialize(cx);
2034        cx.notify();
2035    }
2036
2037    fn cycle_start_thread_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2038        let next = match &self.start_thread_in {
2039            StartThreadIn::LocalProject => StartThreadIn::NewWorktree {
2040                worktree_name: None,
2041                branch_target: NewWorktreeBranchTarget::default(),
2042            },
2043            StartThreadIn::NewWorktree { .. } | StartThreadIn::LinkedWorktree { .. } => {
2044                StartThreadIn::LocalProject
2045            }
2046        };
2047        self.set_start_thread_in(&next, window, cx);
2048    }
2049
2050    fn reset_start_thread_in_to_default(&mut self, cx: &mut Context<Self>) {
2051        use settings::{NewThreadLocation, Settings};
2052        let default = AgentSettings::get_global(cx).new_thread_location;
2053        let start_thread_in = match default {
2054            NewThreadLocation::LocalProject => StartThreadIn::LocalProject,
2055            NewThreadLocation::NewWorktree => {
2056                if self.project_has_git_repository(cx) {
2057                    StartThreadIn::NewWorktree {
2058                        worktree_name: None,
2059                        branch_target: NewWorktreeBranchTarget::default(),
2060                    }
2061                } else {
2062                    StartThreadIn::LocalProject
2063                }
2064            }
2065        };
2066        if self.start_thread_in != start_thread_in {
2067            self.start_thread_in = start_thread_in;
2068            self.serialize(cx);
2069            cx.notify();
2070        }
2071    }
2072
2073    pub(crate) fn selected_agent(&self) -> Option<Agent> {
2074        Some(self.selected_agent.clone())
2075    }
2076
2077    fn sync_agent_servers_from_extensions(&mut self, cx: &mut Context<Self>) {
2078        if let Some(extension_store) = ExtensionStore::try_global(cx) {
2079            let (manifests, extensions_dir) = {
2080                let store = extension_store.read(cx);
2081                let installed = store.installed_extensions();
2082                let manifests: Vec<_> = installed
2083                    .iter()
2084                    .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
2085                    .collect();
2086                let extensions_dir = paths::extensions_dir().join("installed");
2087                (manifests, extensions_dir)
2088            };
2089
2090            self.project.update(cx, |project, cx| {
2091                project.agent_server_store().update(cx, |store, cx| {
2092                    let manifest_refs: Vec<_> = manifests
2093                        .iter()
2094                        .map(|(id, manifest)| (id.as_ref(), manifest.as_ref()))
2095                        .collect();
2096                    store.sync_extension_agents(manifest_refs, extensions_dir, cx);
2097                });
2098            });
2099        }
2100    }
2101
2102    pub fn new_agent_thread_with_external_source_prompt(
2103        &mut self,
2104        external_source_prompt: Option<ExternalSourcePrompt>,
2105        window: &mut Window,
2106        cx: &mut Context<Self>,
2107    ) {
2108        self.external_thread(
2109            None,
2110            None,
2111            None,
2112            None,
2113            external_source_prompt.map(AgentInitialContent::from),
2114            true,
2115            window,
2116            cx,
2117        );
2118    }
2119
2120    pub fn new_agent_thread(&mut self, agent: Agent, window: &mut Window, cx: &mut Context<Self>) {
2121        self.reset_start_thread_in_to_default(cx);
2122        self.new_agent_thread_inner(agent, true, window, cx);
2123    }
2124
2125    fn new_agent_thread_inner(
2126        &mut self,
2127        agent: Agent,
2128        focus: bool,
2129        window: &mut Window,
2130        cx: &mut Context<Self>,
2131    ) {
2132        self.external_thread(Some(agent), None, None, None, None, focus, window, cx);
2133    }
2134
2135    pub fn load_agent_thread(
2136        &mut self,
2137        agent: Agent,
2138        session_id: acp::SessionId,
2139        work_dirs: Option<PathList>,
2140        title: Option<SharedString>,
2141        focus: bool,
2142        window: &mut Window,
2143        cx: &mut Context<Self>,
2144    ) {
2145        if let Some(store) = ThreadMetadataStore::try_global(cx) {
2146            store.update(cx, |store, cx| store.unarchive(&session_id, cx));
2147        }
2148
2149        if let Some(conversation_view) = self.background_threads.remove(&session_id) {
2150            self.set_active_view(
2151                ActiveView::AgentThread { conversation_view },
2152                focus,
2153                window,
2154                cx,
2155            );
2156            return;
2157        }
2158
2159        if let ActiveView::AgentThread { conversation_view } = &self.active_view {
2160            if conversation_view
2161                .read(cx)
2162                .active_thread()
2163                .map(|t| t.read(cx).id.clone())
2164                == Some(session_id.clone())
2165            {
2166                cx.emit(AgentPanelEvent::ActiveViewChanged);
2167                return;
2168            }
2169        }
2170
2171        if let Some(ActiveView::AgentThread { conversation_view }) = &self.previous_view {
2172            if conversation_view
2173                .read(cx)
2174                .active_thread()
2175                .map(|t| t.read(cx).id.clone())
2176                == Some(session_id.clone())
2177            {
2178                let view = self.previous_view.take().unwrap();
2179                self.set_active_view(view, focus, window, cx);
2180                return;
2181            }
2182        }
2183
2184        self.external_thread(
2185            Some(agent),
2186            Some(session_id),
2187            work_dirs,
2188            title,
2189            None,
2190            focus,
2191            window,
2192            cx,
2193        );
2194    }
2195
2196    pub(crate) fn create_agent_thread(
2197        &mut self,
2198        server: Rc<dyn AgentServer>,
2199        resume_session_id: Option<acp::SessionId>,
2200        work_dirs: Option<PathList>,
2201        title: Option<SharedString>,
2202        initial_content: Option<AgentInitialContent>,
2203        workspace: WeakEntity<Workspace>,
2204        project: Entity<Project>,
2205        agent: Agent,
2206        focus: bool,
2207        window: &mut Window,
2208        cx: &mut Context<Self>,
2209    ) {
2210        if self.selected_agent != agent {
2211            self.selected_agent = agent.clone();
2212            self.serialize(cx);
2213        }
2214
2215        cx.background_spawn({
2216            let kvp = KeyValueStore::global(cx);
2217            let agent = agent.clone();
2218            async move {
2219                write_global_last_used_agent(kvp, agent).await;
2220            }
2221        })
2222        .detach();
2223
2224        let thread_store = server
2225            .clone()
2226            .downcast::<agent::NativeAgentServer>()
2227            .is_some()
2228            .then(|| self.thread_store.clone());
2229
2230        let connection_store = self.connection_store.clone();
2231
2232        let conversation_view = cx.new(|cx| {
2233            crate::ConversationView::new(
2234                server,
2235                connection_store,
2236                agent,
2237                resume_session_id,
2238                work_dirs,
2239                title,
2240                initial_content,
2241                workspace.clone(),
2242                project,
2243                thread_store,
2244                self.prompt_store.clone(),
2245                window,
2246                cx,
2247            )
2248        });
2249
2250        cx.observe(&conversation_view, |this, server_view, cx| {
2251            let is_active = this
2252                .active_conversation_view()
2253                .is_some_and(|active| active.entity_id() == server_view.entity_id());
2254            if is_active {
2255                cx.emit(AgentPanelEvent::ActiveViewChanged);
2256                this.serialize(cx);
2257            } else {
2258                cx.emit(AgentPanelEvent::BackgroundThreadChanged);
2259            }
2260            cx.notify();
2261        })
2262        .detach();
2263
2264        self.set_active_view(
2265            ActiveView::AgentThread { conversation_view },
2266            focus,
2267            window,
2268            cx,
2269        );
2270    }
2271
2272    fn active_thread_has_messages(&self, cx: &App) -> bool {
2273        self.active_agent_thread(cx)
2274            .is_some_and(|thread| !thread.read(cx).entries().is_empty())
2275    }
2276
2277    pub fn active_thread_is_draft(&self, cx: &App) -> bool {
2278        self.active_conversation_view().is_some() && !self.active_thread_has_messages(cx)
2279    }
2280
2281    fn handle_first_send_requested(
2282        &mut self,
2283        thread_view: Entity<ThreadView>,
2284        content: Vec<acp::ContentBlock>,
2285        window: &mut Window,
2286        cx: &mut Context<Self>,
2287    ) {
2288        match &self.start_thread_in {
2289            StartThreadIn::NewWorktree {
2290                worktree_name,
2291                branch_target,
2292            } => {
2293                self.handle_worktree_requested(
2294                    content,
2295                    WorktreeCreationArgs::New {
2296                        worktree_name: worktree_name.clone(),
2297                        branch_target: branch_target.clone(),
2298                    },
2299                    window,
2300                    cx,
2301                );
2302            }
2303            StartThreadIn::LinkedWorktree { path, .. } => {
2304                self.handle_worktree_requested(
2305                    content,
2306                    WorktreeCreationArgs::Linked {
2307                        worktree_path: path.clone(),
2308                    },
2309                    window,
2310                    cx,
2311                );
2312            }
2313            StartThreadIn::LocalProject => {
2314                cx.defer_in(window, move |_this, window, cx| {
2315                    thread_view.update(cx, |thread_view, cx| {
2316                        let editor = thread_view.message_editor.clone();
2317                        thread_view.send_impl(editor, window, cx);
2318                    });
2319                });
2320            }
2321        }
2322    }
2323
2324    // TODO: The mapping from workspace root paths to git repositories needs a
2325    // unified approach across the codebase: this method, `sidebar::is_root_repo`,
2326    // thread persistence (which PathList is saved to the database), and thread
2327    // querying (which PathList is used to read threads back). All of these need
2328    // to agree on how repos are resolved for a given workspace, especially in
2329    // multi-root and nested-repo configurations.
2330    /// Partitions the project's visible worktrees into git-backed repositories
2331    /// and plain (non-git) paths. Git repos will have worktrees created for
2332    /// them; non-git paths are carried over to the new workspace as-is.
2333    ///
2334    /// When multiple worktrees map to the same repository, the most specific
2335    /// match wins (deepest work directory path), with a deterministic
2336    /// tie-break on entity id. Each repository appears at most once.
2337    fn classify_worktrees(
2338        &self,
2339        cx: &App,
2340    ) -> (Vec<Entity<project::git_store::Repository>>, Vec<PathBuf>) {
2341        let project = &self.project;
2342        let repositories = project.read(cx).repositories(cx).clone();
2343        let mut git_repos: Vec<Entity<project::git_store::Repository>> = Vec::new();
2344        let mut non_git_paths: Vec<PathBuf> = Vec::new();
2345        let mut seen_repo_ids = std::collections::HashSet::new();
2346
2347        for worktree in project.read(cx).visible_worktrees(cx) {
2348            let wt_path = worktree.read(cx).abs_path();
2349
2350            let matching_repo = repositories
2351                .iter()
2352                .filter_map(|(id, repo)| {
2353                    let work_dir = repo.read(cx).work_directory_abs_path.clone();
2354                    if wt_path.starts_with(work_dir.as_ref())
2355                        || work_dir.starts_with(wt_path.as_ref())
2356                    {
2357                        Some((*id, repo.clone(), work_dir.as_ref().components().count()))
2358                    } else {
2359                        None
2360                    }
2361                })
2362                .max_by(
2363                    |(left_id, _left_repo, left_depth), (right_id, _right_repo, right_depth)| {
2364                        left_depth
2365                            .cmp(right_depth)
2366                            .then_with(|| left_id.cmp(right_id))
2367                    },
2368                );
2369
2370            if let Some((id, repo, _)) = matching_repo {
2371                if seen_repo_ids.insert(id) {
2372                    git_repos.push(repo);
2373                }
2374            } else {
2375                non_git_paths.push(wt_path.to_path_buf());
2376            }
2377        }
2378
2379        (git_repos, non_git_paths)
2380    }
2381
2382    fn resolve_worktree_branch_target(
2383        branch_target: &NewWorktreeBranchTarget,
2384        existing_branches: &HashSet<String>,
2385        occupied_branches: &HashSet<String>,
2386    ) -> Result<(String, bool, Option<String>)> {
2387        let generate_branch_name = || -> Result<String> {
2388            let refs: Vec<&str> = existing_branches.iter().map(|s| s.as_str()).collect();
2389            let mut rng = rand::rng();
2390            crate::branch_names::generate_branch_name(&refs, &mut rng)
2391                .ok_or_else(|| anyhow!("Failed to generate a unique branch name"))
2392        };
2393
2394        match branch_target {
2395            NewWorktreeBranchTarget::CreateBranch { name, from_ref } => {
2396                Ok((name.clone(), false, from_ref.clone()))
2397            }
2398            NewWorktreeBranchTarget::ExistingBranch { name } => {
2399                if occupied_branches.contains(name) {
2400                    Ok((generate_branch_name()?, false, Some(name.clone())))
2401                } else {
2402                    Ok((name.clone(), true, None))
2403                }
2404            }
2405            NewWorktreeBranchTarget::CurrentBranch => Ok((generate_branch_name()?, false, None)),
2406        }
2407    }
2408
2409    /// Kicks off an async git-worktree creation for each repository. Returns:
2410    ///
2411    /// - `creation_infos`: a vec of `(repo, new_path, receiver)` tuples—the
2412    ///   receiver resolves once the git worktree command finishes.
2413    /// - `path_remapping`: `(old_work_dir, new_worktree_path)` pairs used
2414    ///   later to remap open editor tabs into the new workspace.
2415    fn start_worktree_creations(
2416        git_repos: &[Entity<project::git_store::Repository>],
2417        worktree_name: Option<String>,
2418        branch_name: &str,
2419        use_existing_branch: bool,
2420        start_point: Option<String>,
2421        worktree_directory_setting: &str,
2422        cx: &mut Context<Self>,
2423    ) -> Result<(
2424        Vec<(
2425            Entity<project::git_store::Repository>,
2426            PathBuf,
2427            futures::channel::oneshot::Receiver<Result<()>>,
2428        )>,
2429        Vec<(PathBuf, PathBuf)>,
2430    )> {
2431        let mut creation_infos = Vec::new();
2432        let mut path_remapping = Vec::new();
2433
2434        let worktree_name = worktree_name.unwrap_or_else(|| branch_name.to_string());
2435
2436        for repo in git_repos {
2437            let (work_dir, new_path, receiver) = repo.update(cx, |repo, _cx| {
2438                let new_path =
2439                    repo.path_for_new_linked_worktree(&worktree_name, worktree_directory_setting)?;
2440                let target = if use_existing_branch {
2441                    debug_assert!(
2442                        git_repos.len() == 1,
2443                        "use_existing_branch should only be true for a single repo"
2444                    );
2445                    git::repository::CreateWorktreeTarget::ExistingBranch {
2446                        branch_name: branch_name.to_string(),
2447                    }
2448                } else {
2449                    git::repository::CreateWorktreeTarget::NewBranch {
2450                        branch_name: branch_name.to_string(),
2451                        base_sha: start_point.clone(),
2452                    }
2453                };
2454                let receiver = repo.create_worktree(target, new_path.clone());
2455                let work_dir = repo.work_directory_abs_path.clone();
2456                anyhow::Ok((work_dir, new_path, receiver))
2457            })?;
2458            path_remapping.push((work_dir.to_path_buf(), new_path.clone()));
2459            creation_infos.push((repo.clone(), new_path, receiver));
2460        }
2461
2462        Ok((creation_infos, path_remapping))
2463    }
2464
2465    /// Waits for every in-flight worktree creation to complete. If any
2466    /// creation fails, all successfully-created worktrees are rolled back
2467    /// (removed) so the project isn't left in a half-migrated state.
2468    async fn await_and_rollback_on_failure(
2469        creation_infos: Vec<(
2470            Entity<project::git_store::Repository>,
2471            PathBuf,
2472            futures::channel::oneshot::Receiver<Result<()>>,
2473        )>,
2474        cx: &mut AsyncWindowContext,
2475    ) -> Result<Vec<PathBuf>> {
2476        let mut created_paths: Vec<PathBuf> = Vec::new();
2477        let mut repos_and_paths: Vec<(Entity<project::git_store::Repository>, PathBuf)> =
2478            Vec::new();
2479        let mut first_error: Option<anyhow::Error> = None;
2480
2481        for (repo, new_path, receiver) in creation_infos {
2482            match receiver.await {
2483                Ok(Ok(())) => {
2484                    created_paths.push(new_path.clone());
2485                    repos_and_paths.push((repo, new_path));
2486                }
2487                Ok(Err(err)) => {
2488                    if first_error.is_none() {
2489                        first_error = Some(err);
2490                    }
2491                }
2492                Err(_canceled) => {
2493                    if first_error.is_none() {
2494                        first_error = Some(anyhow!("Worktree creation was canceled"));
2495                    }
2496                }
2497            }
2498        }
2499
2500        let Some(err) = first_error else {
2501            return Ok(created_paths);
2502        };
2503
2504        // Rollback all successfully created worktrees
2505        let mut rollback_receivers = Vec::new();
2506        for (rollback_repo, rollback_path) in &repos_and_paths {
2507            if let Ok(receiver) = cx.update(|_, cx| {
2508                rollback_repo.update(cx, |repo, _cx| {
2509                    repo.remove_worktree(rollback_path.clone(), true)
2510                })
2511            }) {
2512                rollback_receivers.push((rollback_path.clone(), receiver));
2513            }
2514        }
2515        let mut rollback_failures: Vec<String> = Vec::new();
2516        for (path, receiver) in rollback_receivers {
2517            match receiver.await {
2518                Ok(Ok(())) => {}
2519                Ok(Err(rollback_err)) => {
2520                    log::error!(
2521                        "failed to rollback worktree at {}: {rollback_err}",
2522                        path.display()
2523                    );
2524                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2525                }
2526                Err(rollback_err) => {
2527                    log::error!(
2528                        "failed to rollback worktree at {}: {rollback_err}",
2529                        path.display()
2530                    );
2531                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2532                }
2533            }
2534        }
2535        let mut error_message = format!("Failed to create worktree: {err}");
2536        if !rollback_failures.is_empty() {
2537            error_message.push_str("\n\nFailed to clean up: ");
2538            error_message.push_str(&rollback_failures.join(", "));
2539        }
2540        Err(anyhow!(error_message))
2541    }
2542
2543    fn set_worktree_creation_error(
2544        &mut self,
2545        message: SharedString,
2546        window: &mut Window,
2547        cx: &mut Context<Self>,
2548    ) {
2549        self.worktree_creation_status = Some(WorktreeCreationStatus::Error(message));
2550        if matches!(self.active_view, ActiveView::Uninitialized) {
2551            let selected_agent = self.selected_agent.clone();
2552            self.new_agent_thread(selected_agent, window, cx);
2553        }
2554        cx.notify();
2555    }
2556
2557    fn handle_worktree_requested(
2558        &mut self,
2559        content: Vec<acp::ContentBlock>,
2560        args: WorktreeCreationArgs,
2561        window: &mut Window,
2562        cx: &mut Context<Self>,
2563    ) {
2564        if matches!(
2565            self.worktree_creation_status,
2566            Some(WorktreeCreationStatus::Creating)
2567        ) {
2568            return;
2569        }
2570
2571        self.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
2572        cx.notify();
2573
2574        let (git_repos, non_git_paths) = self.classify_worktrees(cx);
2575
2576        if matches!(args, WorktreeCreationArgs::New { .. }) && git_repos.is_empty() {
2577            self.set_worktree_creation_error(
2578                "No git repositories found in the project".into(),
2579                window,
2580                cx,
2581            );
2582            return;
2583        }
2584
2585        let (branch_receivers, worktree_receivers, worktree_directory_setting) =
2586            if matches!(args, WorktreeCreationArgs::New { .. }) {
2587                (
2588                    Some(
2589                        git_repos
2590                            .iter()
2591                            .map(|repo| repo.update(cx, |repo, _cx| repo.branches()))
2592                            .collect::<Vec<_>>(),
2593                    ),
2594                    Some(
2595                        git_repos
2596                            .iter()
2597                            .map(|repo| repo.update(cx, |repo, _cx| repo.worktrees()))
2598                            .collect::<Vec<_>>(),
2599                    ),
2600                    Some(
2601                        ProjectSettings::get_global(cx)
2602                            .git
2603                            .worktree_directory
2604                            .clone(),
2605                    ),
2606                )
2607            } else {
2608                (None, None, None)
2609            };
2610
2611        let active_file_path = self.workspace.upgrade().and_then(|workspace| {
2612            let workspace = workspace.read(cx);
2613            let active_item = workspace.active_item(cx)?;
2614            let project_path = active_item.project_path(cx)?;
2615            workspace
2616                .project()
2617                .read(cx)
2618                .absolute_path(&project_path, cx)
2619        });
2620
2621        let workspace = self.workspace.clone();
2622        let window_handle = window
2623            .window_handle()
2624            .downcast::<workspace::MultiWorkspace>();
2625
2626        let selected_agent = self.selected_agent();
2627
2628        let task = cx.spawn_in(window, async move |this, cx| {
2629            let (all_paths, path_remapping, has_non_git) = match args {
2630                WorktreeCreationArgs::New {
2631                    worktree_name,
2632                    branch_target,
2633                } => {
2634                    let branch_receivers = branch_receivers
2635                        .expect("branch receivers must be prepared for new worktree creation");
2636                    let worktree_receivers = worktree_receivers
2637                        .expect("worktree receivers must be prepared for new worktree creation");
2638                    let worktree_directory_setting = worktree_directory_setting
2639                        .expect("worktree directory must be prepared for new worktree creation");
2640
2641                    let mut existing_branches = HashSet::default();
2642                    for result in futures::future::join_all(branch_receivers).await {
2643                        match result {
2644                            Ok(Ok(branches)) => {
2645                                for branch in branches {
2646                                    existing_branches.insert(branch.name().to_string());
2647                                }
2648                            }
2649                            Ok(Err(err)) => {
2650                                Err::<(), _>(err).log_err();
2651                            }
2652                            Err(_) => {}
2653                        }
2654                    }
2655
2656                    let mut occupied_branches = HashSet::default();
2657                    for result in futures::future::join_all(worktree_receivers).await {
2658                        match result {
2659                            Ok(Ok(worktrees)) => {
2660                                for worktree in worktrees {
2661                                    if let Some(branch_name) = worktree.branch_name() {
2662                                        occupied_branches.insert(branch_name.to_string());
2663                                    }
2664                                }
2665                            }
2666                            Ok(Err(err)) => {
2667                                Err::<(), _>(err).log_err();
2668                            }
2669                            Err(_) => {}
2670                        }
2671                    }
2672
2673                    let (branch_name, use_existing_branch, start_point) =
2674                        match Self::resolve_worktree_branch_target(
2675                            &branch_target,
2676                            &existing_branches,
2677                            &occupied_branches,
2678                        ) {
2679                            Ok(target) => target,
2680                            Err(err) => {
2681                                this.update_in(cx, |this, window, cx| {
2682                                    this.set_worktree_creation_error(
2683                                        err.to_string().into(),
2684                                        window,
2685                                        cx,
2686                                    );
2687                                })?;
2688                                return anyhow::Ok(());
2689                            }
2690                        };
2691
2692                    let (creation_infos, path_remapping) =
2693                        match this.update_in(cx, |_this, _window, cx| {
2694                            Self::start_worktree_creations(
2695                                &git_repos,
2696                                worktree_name,
2697                                &branch_name,
2698                                use_existing_branch,
2699                                start_point,
2700                                &worktree_directory_setting,
2701                                cx,
2702                            )
2703                        }) {
2704                            Ok(Ok(result)) => result,
2705                            Ok(Err(err)) | Err(err) => {
2706                                this.update_in(cx, |this, window, cx| {
2707                                    this.set_worktree_creation_error(
2708                                        format!("Failed to validate worktree directory: {err}")
2709                                            .into(),
2710                                        window,
2711                                        cx,
2712                                    );
2713                                })
2714                                .log_err();
2715                                return anyhow::Ok(());
2716                            }
2717                        };
2718
2719                    let created_paths =
2720                        match Self::await_and_rollback_on_failure(creation_infos, cx).await {
2721                            Ok(paths) => paths,
2722                            Err(err) => {
2723                                this.update_in(cx, |this, window, cx| {
2724                                    this.set_worktree_creation_error(
2725                                        format!("{err}").into(),
2726                                        window,
2727                                        cx,
2728                                    );
2729                                })?;
2730                                return anyhow::Ok(());
2731                            }
2732                        };
2733
2734                    let mut all_paths = created_paths;
2735                    let has_non_git = !non_git_paths.is_empty();
2736                    all_paths.extend(non_git_paths.iter().cloned());
2737                    (all_paths, path_remapping, has_non_git)
2738                }
2739                WorktreeCreationArgs::Linked { worktree_path } => {
2740                    let mut all_paths = vec![worktree_path];
2741                    let has_non_git = !non_git_paths.is_empty();
2742                    all_paths.extend(non_git_paths.iter().cloned());
2743                    (all_paths, Vec::new(), has_non_git)
2744                }
2745            };
2746
2747            let app_state = match workspace.upgrade() {
2748                Some(workspace) => cx.update(|_, cx| workspace.read(cx).app_state().clone())?,
2749                None => {
2750                    this.update_in(cx, |this, window, cx| {
2751                        this.set_worktree_creation_error(
2752                            "Workspace no longer available".into(),
2753                            window,
2754                            cx,
2755                        );
2756                    })?;
2757                    return anyhow::Ok(());
2758                }
2759            };
2760
2761            let this_for_error = this.clone();
2762            if let Err(err) = Self::open_worktree_workspace_and_start_thread(
2763                this,
2764                all_paths,
2765                app_state,
2766                window_handle,
2767                active_file_path,
2768                path_remapping,
2769                non_git_paths,
2770                has_non_git,
2771                content,
2772                selected_agent,
2773                cx,
2774            )
2775            .await
2776            {
2777                this_for_error
2778                    .update_in(cx, |this, window, cx| {
2779                        this.set_worktree_creation_error(
2780                            format!("Failed to set up workspace: {err}").into(),
2781                            window,
2782                            cx,
2783                        );
2784                    })
2785                    .log_err();
2786            }
2787            anyhow::Ok(())
2788        });
2789
2790        self._worktree_creation_task = Some(cx.background_spawn(async move {
2791            task.await.log_err();
2792        }));
2793    }
2794
2795    async fn open_worktree_workspace_and_start_thread(
2796        this: WeakEntity<Self>,
2797        all_paths: Vec<PathBuf>,
2798        app_state: Arc<workspace::AppState>,
2799        window_handle: Option<gpui::WindowHandle<workspace::MultiWorkspace>>,
2800        active_file_path: Option<PathBuf>,
2801        path_remapping: Vec<(PathBuf, PathBuf)>,
2802        non_git_paths: Vec<PathBuf>,
2803        has_non_git: bool,
2804        content: Vec<acp::ContentBlock>,
2805        selected_agent: Option<Agent>,
2806        cx: &mut AsyncWindowContext,
2807    ) -> Result<()> {
2808        let OpenResult {
2809            window: new_window_handle,
2810            workspace: new_workspace,
2811            ..
2812        } = cx
2813            .update(|_window, cx| {
2814                Workspace::new_local(
2815                    all_paths,
2816                    app_state,
2817                    window_handle,
2818                    None,
2819                    None,
2820                    OpenMode::Add,
2821                    cx,
2822                )
2823            })?
2824            .await?;
2825
2826        let panels_task = new_workspace.update(cx, |workspace, _cx| workspace.take_panels_task());
2827
2828        if let Some(task) = panels_task {
2829            task.await.log_err();
2830        }
2831
2832        new_workspace
2833            .update(cx, |workspace, cx| {
2834                workspace.project().read(cx).wait_for_initial_scan(cx)
2835            })
2836            .await;
2837
2838        new_workspace
2839            .update(cx, |workspace, cx| {
2840                let repos = workspace
2841                    .project()
2842                    .read(cx)
2843                    .repositories(cx)
2844                    .values()
2845                    .cloned()
2846                    .collect::<Vec<_>>();
2847
2848                let tasks = repos
2849                    .into_iter()
2850                    .map(|repo| repo.update(cx, |repo, _| repo.barrier()));
2851                futures::future::join_all(tasks)
2852            })
2853            .await;
2854
2855        let initial_content = AgentInitialContent::ContentBlock {
2856            blocks: content,
2857            auto_submit: true,
2858        };
2859
2860        new_window_handle.update(cx, |_multi_workspace, window, cx| {
2861            new_workspace.update(cx, |workspace, cx| {
2862                if has_non_git {
2863                    let toast_id = workspace::notifications::NotificationId::unique::<AgentPanel>();
2864                    workspace.show_toast(
2865                        workspace::Toast::new(
2866                            toast_id,
2867                            "Some project folders are not git repositories. \
2868                             They were included as-is without creating a worktree.",
2869                        ),
2870                        cx,
2871                    );
2872                }
2873
2874                // If we had an active buffer, remap its path and reopen it.
2875                let had_active_file = active_file_path.is_some();
2876                let remapped_active_path = active_file_path.and_then(|original_path| {
2877                    let best_match = path_remapping
2878                        .iter()
2879                        .filter_map(|(old_root, new_root)| {
2880                            original_path.strip_prefix(old_root).ok().map(|relative| {
2881                                (old_root.components().count(), new_root.join(relative))
2882                            })
2883                        })
2884                        .max_by_key(|(depth, _)| *depth);
2885
2886                    if let Some((_, remapped_path)) = best_match {
2887                        return Some(remapped_path);
2888                    }
2889
2890                    for non_git in &non_git_paths {
2891                        if original_path.starts_with(non_git) {
2892                            return Some(original_path);
2893                        }
2894                    }
2895                    None
2896                });
2897
2898                if had_active_file && remapped_active_path.is_none() {
2899                    log::warn!(
2900                        "Active file could not be remapped to the new worktree; it will not be reopened"
2901                    );
2902                }
2903
2904                if let Some(path) = remapped_active_path {
2905                    let open_task = workspace.open_paths(
2906                        vec![path],
2907                        workspace::OpenOptions::default(),
2908                        None,
2909                        window,
2910                        cx,
2911                    );
2912                    cx.spawn(async move |_, _| -> anyhow::Result<()> {
2913                        for item in open_task.await.into_iter().flatten() {
2914                            item?;
2915                        }
2916                        Ok(())
2917                    })
2918                    .detach_and_log_err(cx);
2919                }
2920
2921                workspace.focus_panel::<AgentPanel>(window, cx);
2922
2923                // If no active buffer was open, zoom the agent panel
2924                // (equivalent to cmd-esc fullscreen behavior).
2925                // This must happen after focus_panel, which activates
2926                // and opens the panel in the dock.
2927
2928                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2929                    panel.update(cx, |panel, cx| {
2930                        panel.external_thread(
2931                            selected_agent,
2932                            None,
2933                            None,
2934                            None,
2935                            Some(initial_content),
2936                            true,
2937                            window,
2938                            cx,
2939                        );
2940                    });
2941                }
2942            });
2943        })?;
2944
2945        new_window_handle.update(cx, |multi_workspace, window, cx| {
2946            multi_workspace.activate(new_workspace.clone(), window, cx);
2947
2948            new_workspace.update(cx, |workspace, cx| {
2949                workspace.run_create_worktree_tasks(window, cx);
2950            })
2951        })?;
2952
2953        this.update_in(cx, |this, window, cx| {
2954            this.worktree_creation_status = None;
2955
2956            if let Some(thread_view) = this.active_thread_view(cx) {
2957                thread_view.update(cx, |thread_view, cx| {
2958                    thread_view
2959                        .message_editor
2960                        .update(cx, |editor, cx| editor.clear(window, cx));
2961                });
2962            }
2963
2964            cx.notify();
2965        })?;
2966
2967        anyhow::Ok(())
2968    }
2969}
2970
2971impl Focusable for AgentPanel {
2972    fn focus_handle(&self, cx: &App) -> FocusHandle {
2973        match &self.active_view {
2974            ActiveView::Uninitialized => self.focus_handle.clone(),
2975            ActiveView::AgentThread {
2976                conversation_view, ..
2977            } => conversation_view.focus_handle(cx),
2978            ActiveView::History { view } => view.read(cx).focus_handle(cx),
2979            ActiveView::Configuration => {
2980                if let Some(configuration) = self.configuration.as_ref() {
2981                    configuration.focus_handle(cx)
2982                } else {
2983                    self.focus_handle.clone()
2984                }
2985            }
2986        }
2987    }
2988}
2989
2990fn agent_panel_dock_position(cx: &App) -> DockPosition {
2991    AgentSettings::get_global(cx).dock.into()
2992}
2993
2994pub enum AgentPanelEvent {
2995    ActiveViewChanged,
2996    ThreadFocused,
2997    BackgroundThreadChanged,
2998    MessageSentOrQueued { session_id: acp::SessionId },
2999}
3000
3001impl EventEmitter<PanelEvent> for AgentPanel {}
3002impl EventEmitter<AgentPanelEvent> for AgentPanel {}
3003
3004impl Panel for AgentPanel {
3005    fn persistent_name() -> &'static str {
3006        "AgentPanel"
3007    }
3008
3009    fn panel_key() -> &'static str {
3010        AGENT_PANEL_KEY
3011    }
3012
3013    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3014        agent_panel_dock_position(cx)
3015    }
3016
3017    fn position_is_valid(&self, position: DockPosition) -> bool {
3018        position != DockPosition::Bottom
3019    }
3020
3021    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3022        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3023            settings
3024                .agent
3025                .get_or_insert_default()
3026                .set_dock(position.into());
3027        });
3028    }
3029
3030    fn default_size(&self, window: &Window, cx: &App) -> Pixels {
3031        let settings = AgentSettings::get_global(cx);
3032        match self.position(window, cx) {
3033            DockPosition::Left | DockPosition::Right => settings.default_width,
3034            DockPosition::Bottom => settings.default_height,
3035        }
3036    }
3037
3038    fn supports_flexible_size(&self) -> bool {
3039        true
3040    }
3041
3042    fn has_flexible_size(&self, _window: &Window, cx: &App) -> bool {
3043        AgentSettings::get_global(cx).flexible
3044    }
3045
3046    fn set_flexible_size(&mut self, flexible: bool, _window: &mut Window, cx: &mut Context<Self>) {
3047        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3048            settings
3049                .agent
3050                .get_or_insert_default()
3051                .set_flexible_size(flexible);
3052        });
3053    }
3054
3055    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
3056        if active
3057            && matches!(self.active_view, ActiveView::Uninitialized)
3058            && !matches!(
3059                self.worktree_creation_status,
3060                Some(WorktreeCreationStatus::Creating)
3061            )
3062        {
3063            let selected_agent = self.selected_agent.clone();
3064            self.new_agent_thread_inner(selected_agent, false, window, cx);
3065        }
3066    }
3067
3068    fn remote_id() -> Option<proto::PanelId> {
3069        Some(proto::PanelId::AssistantPanel)
3070    }
3071
3072    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
3073        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
3074    }
3075
3076    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3077        Some("Agent Panel")
3078    }
3079
3080    fn toggle_action(&self) -> Box<dyn Action> {
3081        Box::new(ToggleFocus)
3082    }
3083
3084    fn activation_priority(&self) -> u32 {
3085        0
3086    }
3087
3088    fn enabled(&self, cx: &App) -> bool {
3089        AgentSettings::get_global(cx).enabled(cx)
3090    }
3091
3092    fn is_agent_panel(&self) -> bool {
3093        true
3094    }
3095
3096    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
3097        self.zoomed
3098    }
3099
3100    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
3101        self.zoomed = zoomed;
3102        cx.notify();
3103    }
3104}
3105
3106impl AgentPanel {
3107    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
3108        let content = match &self.active_view {
3109            ActiveView::AgentThread { conversation_view } => {
3110                let server_view_ref = conversation_view.read(cx);
3111                let is_generating_title = server_view_ref.as_native_thread(cx).is_some()
3112                    && server_view_ref.root_thread(cx).map_or(false, |tv| {
3113                        tv.read(cx).thread.read(cx).has_provisional_title()
3114                    });
3115
3116                if let Some(title_editor) = server_view_ref
3117                    .root_thread(cx)
3118                    .map(|r| r.read(cx).title_editor.clone())
3119                {
3120                    if is_generating_title {
3121                        Label::new(DEFAULT_THREAD_TITLE)
3122                            .color(Color::Muted)
3123                            .truncate()
3124                            .with_animation(
3125                                "generating_title",
3126                                Animation::new(Duration::from_secs(2))
3127                                    .repeat()
3128                                    .with_easing(pulsating_between(0.4, 0.8)),
3129                                |label, delta| label.alpha(delta),
3130                            )
3131                            .into_any_element()
3132                    } else {
3133                        div()
3134                            .w_full()
3135                            .on_action({
3136                                let conversation_view = conversation_view.downgrade();
3137                                move |_: &menu::Confirm, window, cx| {
3138                                    if let Some(conversation_view) = conversation_view.upgrade() {
3139                                        conversation_view.focus_handle(cx).focus(window, cx);
3140                                    }
3141                                }
3142                            })
3143                            .on_action({
3144                                let conversation_view = conversation_view.downgrade();
3145                                move |_: &editor::actions::Cancel, window, cx| {
3146                                    if let Some(conversation_view) = conversation_view.upgrade() {
3147                                        conversation_view.focus_handle(cx).focus(window, cx);
3148                                    }
3149                                }
3150                            })
3151                            .child(title_editor)
3152                            .into_any_element()
3153                    }
3154                } else {
3155                    Label::new(conversation_view.read(cx).title(cx))
3156                        .color(Color::Muted)
3157                        .truncate()
3158                        .into_any_element()
3159                }
3160            }
3161            ActiveView::History { .. } => Label::new("History").truncate().into_any_element(),
3162            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
3163            ActiveView::Uninitialized => Label::new("Agent").truncate().into_any_element(),
3164        };
3165
3166        h_flex()
3167            .key_context("TitleEditor")
3168            .id("TitleEditor")
3169            .flex_grow()
3170            .w_full()
3171            .max_w_full()
3172            .overflow_x_scroll()
3173            .child(content)
3174            .into_any()
3175    }
3176
3177    fn handle_regenerate_thread_title(conversation_view: Entity<ConversationView>, cx: &mut App) {
3178        conversation_view.update(cx, |conversation_view, cx| {
3179            if let Some(thread) = conversation_view.as_native_thread(cx) {
3180                thread.update(cx, |thread, cx| {
3181                    thread.generate_title(cx);
3182                });
3183            }
3184        });
3185    }
3186
3187    fn render_panel_options_menu(
3188        &self,
3189        _window: &mut Window,
3190        cx: &mut Context<Self>,
3191    ) -> impl IntoElement {
3192        let focus_handle = self.focus_handle(cx);
3193
3194        let conversation_view = match &self.active_view {
3195            ActiveView::AgentThread { conversation_view } => Some(conversation_view.clone()),
3196            _ => None,
3197        };
3198        let thread_with_messages = match &self.active_view {
3199            ActiveView::AgentThread { conversation_view } => {
3200                conversation_view.read(cx).has_user_submitted_prompt(cx)
3201            }
3202            _ => false,
3203        };
3204        let has_auth_methods = match &self.active_view {
3205            ActiveView::AgentThread { conversation_view } => {
3206                conversation_view.read(cx).has_auth_methods()
3207            }
3208            _ => false,
3209        };
3210
3211        PopoverMenu::new("agent-options-menu")
3212            .trigger_with_tooltip(
3213                IconButton::new("agent-options-menu", IconName::Ellipsis)
3214                    .icon_size(IconSize::Small),
3215                {
3216                    let focus_handle = focus_handle.clone();
3217                    move |_window, cx| {
3218                        Tooltip::for_action_in(
3219                            "Toggle Agent Menu",
3220                            &ToggleOptionsMenu,
3221                            &focus_handle,
3222                            cx,
3223                        )
3224                    }
3225                },
3226            )
3227            .anchor(Corner::TopRight)
3228            .with_handle(self.agent_panel_menu_handle.clone())
3229            .menu({
3230                move |window, cx| {
3231                    Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
3232                        menu = menu.context(focus_handle.clone());
3233
3234                        if thread_with_messages {
3235                            menu = menu.header("Current Thread");
3236
3237                            if let Some(conversation_view) = conversation_view.as_ref() {
3238                                menu = menu
3239                                    .entry("Regenerate Thread Title", None, {
3240                                        let conversation_view = conversation_view.clone();
3241                                        move |_, cx| {
3242                                            Self::handle_regenerate_thread_title(
3243                                                conversation_view.clone(),
3244                                                cx,
3245                                            );
3246                                        }
3247                                    })
3248                                    .separator();
3249                            }
3250                        }
3251
3252                        menu = menu
3253                            .header("MCP Servers")
3254                            .action(
3255                                "View Server Extensions",
3256                                Box::new(zed_actions::Extensions {
3257                                    category_filter: Some(
3258                                        zed_actions::ExtensionCategoryFilter::ContextServers,
3259                                    ),
3260                                    id: None,
3261                                }),
3262                            )
3263                            .action("Add Custom Server…", Box::new(AddContextServer))
3264                            .separator()
3265                            .action("Rules", Box::new(OpenRulesLibrary::default()))
3266                            .action("Profiles", Box::new(ManageProfiles::default()))
3267                            .action("Settings", Box::new(OpenSettings))
3268                            .separator()
3269                            .action("Toggle Threads Sidebar", Box::new(ToggleWorkspaceSidebar));
3270
3271                        if has_auth_methods {
3272                            menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
3273                        }
3274
3275                        menu
3276                    }))
3277                }
3278            })
3279    }
3280
3281    fn render_recent_entries_menu(
3282        &self,
3283        icon: IconName,
3284        corner: Corner,
3285        cx: &mut Context<Self>,
3286    ) -> impl IntoElement {
3287        let focus_handle = self.focus_handle(cx);
3288
3289        PopoverMenu::new("agent-nav-menu")
3290            .trigger_with_tooltip(
3291                IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
3292                {
3293                    move |_window, cx| {
3294                        Tooltip::for_action_in(
3295                            "Toggle Recently Updated Threads",
3296                            &ToggleNavigationMenu,
3297                            &focus_handle,
3298                            cx,
3299                        )
3300                    }
3301                },
3302            )
3303            .anchor(corner)
3304            .with_handle(self.agent_navigation_menu_handle.clone())
3305            .menu({
3306                let menu = self.agent_navigation_menu.clone();
3307                move |window, cx| {
3308                    telemetry::event!("View Thread History Clicked");
3309
3310                    if let Some(menu) = menu.as_ref() {
3311                        menu.update(cx, |_, cx| {
3312                            cx.defer_in(window, |menu, window, cx| {
3313                                menu.rebuild(window, cx);
3314                            });
3315                        })
3316                    }
3317                    menu.clone()
3318                }
3319            })
3320    }
3321
3322    fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3323        let focus_handle = self.focus_handle(cx);
3324
3325        IconButton::new("go-back", IconName::ArrowLeft)
3326            .icon_size(IconSize::Small)
3327            .on_click(cx.listener(|this, _, window, cx| {
3328                this.go_back(&workspace::GoBack, window, cx);
3329            }))
3330            .tooltip({
3331                move |_window, cx| {
3332                    Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
3333                }
3334            })
3335    }
3336
3337    fn project_has_git_repository(&self, cx: &App) -> bool {
3338        !self.project.read(cx).repositories(cx).is_empty()
3339    }
3340
3341    fn render_start_thread_in_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3342        let focus_handle = self.focus_handle(cx);
3343
3344        let is_creating = matches!(
3345            self.worktree_creation_status,
3346            Some(WorktreeCreationStatus::Creating)
3347        );
3348
3349        let trigger_label = self.start_thread_in.label();
3350
3351        let icon = if self.start_thread_in_menu_handle.is_deployed() {
3352            IconName::ChevronUp
3353        } else {
3354            IconName::ChevronDown
3355        };
3356
3357        let trigger_button = Button::new("thread-target-trigger", trigger_label)
3358            .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3359            .disabled(is_creating);
3360
3361        let project = self.project.clone();
3362        let current_target = self.start_thread_in.clone();
3363        let fs = self.fs.clone();
3364
3365        PopoverMenu::new("thread-target-selector")
3366            .trigger_with_tooltip(trigger_button, {
3367                move |_window, cx| {
3368                    Tooltip::for_action_in(
3369                        "Start Thread In…",
3370                        &CycleStartThreadIn,
3371                        &focus_handle,
3372                        cx,
3373                    )
3374                }
3375            })
3376            .menu(move |window, cx| {
3377                let fs = fs.clone();
3378                Some(cx.new(|cx| {
3379                    ThreadWorktreePicker::new(project.clone(), &current_target, fs, window, cx)
3380                }))
3381            })
3382            .with_handle(self.start_thread_in_menu_handle.clone())
3383            .anchor(Corner::TopLeft)
3384            .offset(gpui::Point {
3385                x: px(1.0),
3386                y: px(1.0),
3387            })
3388    }
3389
3390    fn render_new_worktree_branch_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3391        let is_creating = matches!(
3392            self.worktree_creation_status,
3393            Some(WorktreeCreationStatus::Creating)
3394        );
3395        let default_branch_label = if self.project.read(cx).repositories(cx).len() > 1 {
3396            SharedString::from("From: current branches")
3397        } else {
3398            self.project
3399                .read(cx)
3400                .active_repository(cx)
3401                .and_then(|repo| {
3402                    repo.read(cx)
3403                        .branch
3404                        .as_ref()
3405                        .map(|branch| SharedString::from(format!("From: {}", branch.name())))
3406                })
3407                .unwrap_or_else(|| SharedString::from("From: HEAD"))
3408        };
3409        let trigger_label = self
3410            .start_thread_in
3411            .worktree_branch_label(default_branch_label)
3412            .unwrap_or_else(|| SharedString::from("From: HEAD"));
3413        let icon = if self.thread_branch_menu_handle.is_deployed() {
3414            IconName::ChevronUp
3415        } else {
3416            IconName::ChevronDown
3417        };
3418        let trigger_button = Button::new("thread-branch-trigger", trigger_label)
3419            .start_icon(
3420                Icon::new(IconName::GitBranch)
3421                    .size(IconSize::Small)
3422                    .color(Color::Muted),
3423            )
3424            .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3425            .disabled(is_creating);
3426        let project = self.project.clone();
3427        let current_target = self.start_thread_in.clone();
3428
3429        PopoverMenu::new("thread-branch-selector")
3430            .trigger_with_tooltip(trigger_button, Tooltip::text("Choose Worktree Branch…"))
3431            .menu(move |window, cx| {
3432                Some(cx.new(|cx| {
3433                    ThreadBranchPicker::new(project.clone(), &current_target, window, cx)
3434                }))
3435            })
3436            .with_handle(self.thread_branch_menu_handle.clone())
3437            .anchor(Corner::TopLeft)
3438            .offset(gpui::Point {
3439                x: px(1.0),
3440                y: px(1.0),
3441            })
3442    }
3443
3444    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3445        let agent_server_store = self.project.read(cx).agent_server_store().clone();
3446        let has_visible_worktrees = self.project.read(cx).visible_worktrees(cx).next().is_some();
3447        let focus_handle = self.focus_handle(cx);
3448
3449        let (selected_agent_custom_icon, selected_agent_label) =
3450            if let Agent::Custom { id, .. } = &self.selected_agent {
3451                let store = agent_server_store.read(cx);
3452                let icon = store.agent_icon(&id);
3453
3454                let label = store
3455                    .agent_display_name(&id)
3456                    .unwrap_or_else(|| self.selected_agent.label());
3457                (icon, label)
3458            } else {
3459                (None, self.selected_agent.label())
3460            };
3461
3462        let active_thread = match &self.active_view {
3463            ActiveView::AgentThread { conversation_view } => {
3464                conversation_view.read(cx).as_native_thread(cx)
3465            }
3466            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
3467                None
3468            }
3469        };
3470
3471        let new_thread_menu_builder: Rc<
3472            dyn Fn(&mut Window, &mut App) -> Option<Entity<ContextMenu>>,
3473        > = {
3474            let selected_agent = self.selected_agent.clone();
3475            let is_agent_selected = move |agent: Agent| selected_agent == agent;
3476
3477            let workspace = self.workspace.clone();
3478            let is_via_collab = workspace
3479                .update(cx, |workspace, cx| {
3480                    workspace.project().read(cx).is_via_collab()
3481                })
3482                .unwrap_or_default();
3483
3484            let focus_handle = focus_handle.clone();
3485            let agent_server_store = agent_server_store;
3486
3487            Rc::new(move |window, cx| {
3488                telemetry::event!("New Thread Clicked");
3489
3490                let active_thread = active_thread.clone();
3491                Some(ContextMenu::build(window, cx, |menu, _window, cx| {
3492                    menu.context(focus_handle.clone())
3493                        .when_some(active_thread, |this, active_thread| {
3494                            let thread = active_thread.read(cx);
3495
3496                            if !thread.is_empty() {
3497                                let session_id = thread.id().clone();
3498                                this.item(
3499                                    ContextMenuEntry::new("New From Summary")
3500                                        .icon(IconName::ThreadFromSummary)
3501                                        .icon_color(Color::Muted)
3502                                        .handler(move |window, cx| {
3503                                            window.dispatch_action(
3504                                                Box::new(NewNativeAgentThreadFromSummary {
3505                                                    from_session_id: session_id.clone(),
3506                                                }),
3507                                                cx,
3508                                            );
3509                                        }),
3510                                )
3511                            } else {
3512                                this
3513                            }
3514                        })
3515                        .item(
3516                            ContextMenuEntry::new("Zed Agent")
3517                                .when(is_agent_selected(Agent::NativeAgent), |this| {
3518                                    this.action(Box::new(NewExternalAgentThread { agent: None }))
3519                                })
3520                                .icon(IconName::ZedAgent)
3521                                .icon_color(Color::Muted)
3522                                .handler({
3523                                    let workspace = workspace.clone();
3524                                    move |window, cx| {
3525                                        if let Some(workspace) = workspace.upgrade() {
3526                                            workspace.update(cx, |workspace, cx| {
3527                                                if let Some(panel) =
3528                                                    workspace.panel::<AgentPanel>(cx)
3529                                                {
3530                                                    panel.update(cx, |panel, cx| {
3531                                                        panel.new_agent_thread(
3532                                                            Agent::NativeAgent,
3533                                                            window,
3534                                                            cx,
3535                                                        );
3536                                                    });
3537                                                }
3538                                            });
3539                                        }
3540                                    }
3541                                }),
3542                        )
3543                        .map(|mut menu| {
3544                            let agent_server_store = agent_server_store.read(cx);
3545                            let registry_store = project::AgentRegistryStore::try_global(cx);
3546                            let registry_store_ref = registry_store.as_ref().map(|s| s.read(cx));
3547
3548                            struct AgentMenuItem {
3549                                id: AgentId,
3550                                display_name: SharedString,
3551                            }
3552
3553                            let agent_items = agent_server_store
3554                                .external_agents()
3555                                .map(|agent_id| {
3556                                    let display_name = agent_server_store
3557                                        .agent_display_name(agent_id)
3558                                        .or_else(|| {
3559                                            registry_store_ref
3560                                                .as_ref()
3561                                                .and_then(|store| store.agent(agent_id))
3562                                                .map(|a| a.name().clone())
3563                                        })
3564                                        .unwrap_or_else(|| agent_id.0.clone());
3565                                    AgentMenuItem {
3566                                        id: agent_id.clone(),
3567                                        display_name,
3568                                    }
3569                                })
3570                                .sorted_unstable_by_key(|e| e.display_name.to_lowercase())
3571                                .collect::<Vec<_>>();
3572
3573                            if !agent_items.is_empty() {
3574                                menu = menu.separator().header("External Agents");
3575                            }
3576                            for item in &agent_items {
3577                                let mut entry = ContextMenuEntry::new(item.display_name.clone());
3578
3579                                let icon_path =
3580                                    agent_server_store.agent_icon(&item.id).or_else(|| {
3581                                        registry_store_ref
3582                                            .as_ref()
3583                                            .and_then(|store| store.agent(&item.id))
3584                                            .and_then(|a| a.icon_path().cloned())
3585                                    });
3586
3587                                if let Some(icon_path) = icon_path {
3588                                    entry = entry.custom_icon_svg(icon_path);
3589                                } else {
3590                                    entry = entry.icon(IconName::Sparkle);
3591                                }
3592
3593                                entry = entry
3594                                    .when(
3595                                        is_agent_selected(Agent::Custom {
3596                                            id: item.id.clone(),
3597                                        }),
3598                                        |this| {
3599                                            this.action(Box::new(NewExternalAgentThread {
3600                                                agent: None,
3601                                            }))
3602                                        },
3603                                    )
3604                                    .icon_color(Color::Muted)
3605                                    .disabled(is_via_collab)
3606                                    .handler({
3607                                        let workspace = workspace.clone();
3608                                        let agent_id = item.id.clone();
3609                                        move |window, cx| {
3610                                            if let Some(workspace) = workspace.upgrade() {
3611                                                workspace.update(cx, |workspace, cx| {
3612                                                    if let Some(panel) =
3613                                                        workspace.panel::<AgentPanel>(cx)
3614                                                    {
3615                                                        panel.update(cx, |panel, cx| {
3616                                                            panel.new_agent_thread(
3617                                                                Agent::Custom {
3618                                                                    id: agent_id.clone(),
3619                                                                },
3620                                                                window,
3621                                                                cx,
3622                                                            );
3623                                                        });
3624                                                    }
3625                                                });
3626                                            }
3627                                        }
3628                                    });
3629
3630                                menu = menu.item(entry);
3631                            }
3632
3633                            menu
3634                        })
3635                        .separator()
3636                        .item(
3637                            ContextMenuEntry::new("Add More Agents")
3638                                .icon(IconName::Plus)
3639                                .icon_color(Color::Muted)
3640                                .handler({
3641                                    move |window, cx| {
3642                                        window
3643                                            .dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
3644                                    }
3645                                }),
3646                        )
3647                }))
3648            })
3649        };
3650
3651        let is_thread_loading = self
3652            .active_conversation_view()
3653            .map(|thread| thread.read(cx).is_loading())
3654            .unwrap_or(false);
3655
3656        let has_custom_icon = selected_agent_custom_icon.is_some();
3657        let selected_agent_custom_icon_for_button = selected_agent_custom_icon.clone();
3658        let selected_agent_builtin_icon = self.selected_agent.icon();
3659        let selected_agent_label_for_tooltip = selected_agent_label.clone();
3660
3661        let selected_agent = div()
3662            .id("selected_agent_icon")
3663            .when_some(selected_agent_custom_icon, |this, icon_path| {
3664                this.px_1()
3665                    .child(Icon::from_external_svg(icon_path).color(Color::Muted))
3666            })
3667            .when(!has_custom_icon, |this| {
3668                this.when_some(selected_agent_builtin_icon, |this, icon| {
3669                    this.px_1().child(Icon::new(icon).color(Color::Muted))
3670                })
3671            })
3672            .tooltip(move |_, cx| {
3673                Tooltip::with_meta(
3674                    selected_agent_label_for_tooltip.clone(),
3675                    None,
3676                    "Selected Agent",
3677                    cx,
3678                )
3679            });
3680
3681        let selected_agent = if is_thread_loading {
3682            selected_agent
3683                .with_animation(
3684                    "pulsating-icon",
3685                    Animation::new(Duration::from_secs(1))
3686                        .repeat()
3687                        .with_easing(pulsating_between(0.2, 0.6)),
3688                    |icon, delta| icon.opacity(delta),
3689                )
3690                .into_any_element()
3691        } else {
3692            selected_agent.into_any_element()
3693        };
3694
3695        let show_history_menu = self.has_history_for_selected_agent(cx);
3696        let has_v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
3697        let is_empty_state = !self.active_thread_has_messages(cx);
3698
3699        let is_in_history_or_config = matches!(
3700            &self.active_view,
3701            ActiveView::History { .. } | ActiveView::Configuration
3702        );
3703
3704        let is_full_screen = self.is_zoomed(window, cx);
3705        let full_screen_button = if is_full_screen {
3706            IconButton::new("disable-full-screen", IconName::Minimize)
3707                .icon_size(IconSize::Small)
3708                .tooltip(move |_, cx| Tooltip::for_action("Disable Full Screen", &ToggleZoom, cx))
3709                .on_click(cx.listener(move |this, _, window, cx| {
3710                    this.toggle_zoom(&ToggleZoom, window, cx);
3711                }))
3712        } else {
3713            IconButton::new("enable-full-screen", IconName::Maximize)
3714                .icon_size(IconSize::Small)
3715                .tooltip(move |_, cx| Tooltip::for_action("Enable Full Screen", &ToggleZoom, cx))
3716                .on_click(cx.listener(move |this, _, window, cx| {
3717                    this.toggle_zoom(&ToggleZoom, window, cx);
3718                }))
3719        };
3720
3721        let use_v2_empty_toolbar = has_v2_flag && is_empty_state && !is_in_history_or_config;
3722
3723        let max_content_width = AgentSettings::get_global(cx).max_content_width;
3724
3725        let base_container = h_flex()
3726            .size_full()
3727            // TODO: This is only until we remove Agent settings from the panel.
3728            .when(!is_in_history_or_config, |this| {
3729                this.max_w(max_content_width).mx_auto()
3730            })
3731            .flex_none()
3732            .justify_between()
3733            .gap_2();
3734
3735        let toolbar_content = if use_v2_empty_toolbar {
3736            let (chevron_icon, icon_color, label_color) =
3737                if self.new_thread_menu_handle.is_deployed() {
3738                    (IconName::ChevronUp, Color::Accent, Color::Accent)
3739                } else {
3740                    (IconName::ChevronDown, Color::Muted, Color::Default)
3741                };
3742
3743            let agent_icon = if let Some(icon_path) = selected_agent_custom_icon_for_button {
3744                Icon::from_external_svg(icon_path)
3745                    .size(IconSize::Small)
3746                    .color(icon_color)
3747            } else {
3748                let icon_name = selected_agent_builtin_icon.unwrap_or(IconName::ZedAgent);
3749                Icon::new(icon_name).size(IconSize::Small).color(icon_color)
3750            };
3751
3752            let agent_selector_button = Button::new("agent-selector-trigger", selected_agent_label)
3753                .start_icon(agent_icon)
3754                .color(label_color)
3755                .end_icon(
3756                    Icon::new(chevron_icon)
3757                        .color(icon_color)
3758                        .size(IconSize::XSmall),
3759                );
3760
3761            let agent_selector_menu = PopoverMenu::new("new_thread_menu")
3762                .trigger_with_tooltip(agent_selector_button, {
3763                    move |_window, cx| {
3764                        Tooltip::for_action_in(
3765                            "New Thread…",
3766                            &ToggleNewThreadMenu,
3767                            &focus_handle,
3768                            cx,
3769                        )
3770                    }
3771                })
3772                .menu({
3773                    let builder = new_thread_menu_builder.clone();
3774                    move |window, cx| builder(window, cx)
3775                })
3776                .with_handle(self.new_thread_menu_handle.clone())
3777                .anchor(Corner::TopLeft)
3778                .offset(gpui::Point {
3779                    x: px(1.0),
3780                    y: px(1.0),
3781                });
3782
3783            base_container
3784                .child(
3785                    h_flex()
3786                        .size_full()
3787                        .gap(DynamicSpacing::Base04.rems(cx))
3788                        .pl(DynamicSpacing::Base04.rems(cx))
3789                        .child(agent_selector_menu)
3790                        .when(
3791                            has_visible_worktrees && self.project_has_git_repository(cx),
3792                            |this| this.child(self.render_start_thread_in_selector(cx)),
3793                        )
3794                        .when(
3795                            has_v2_flag
3796                                && matches!(
3797                                    self.start_thread_in,
3798                                    StartThreadIn::NewWorktree { .. }
3799                                ),
3800                            |this| this.child(self.render_new_worktree_branch_selector(cx)),
3801                        ),
3802                )
3803                .child(
3804                    h_flex()
3805                        .h_full()
3806                        .flex_none()
3807                        .gap_1()
3808                        .pl_1()
3809                        .pr_1()
3810                        .when(show_history_menu && !has_v2_flag, |this| {
3811                            this.child(self.render_recent_entries_menu(
3812                                IconName::MenuAltTemp,
3813                                Corner::TopRight,
3814                                cx,
3815                            ))
3816                        })
3817                        .child(full_screen_button)
3818                        .child(self.render_panel_options_menu(window, cx)),
3819                )
3820                .into_any_element()
3821        } else {
3822            let new_thread_menu = PopoverMenu::new("new_thread_menu")
3823                .trigger_with_tooltip(
3824                    IconButton::new("new_thread_menu_btn", IconName::Plus)
3825                        .icon_size(IconSize::Small),
3826                    {
3827                        move |_window, cx| {
3828                            Tooltip::for_action_in(
3829                                "New Thread\u{2026}",
3830                                &ToggleNewThreadMenu,
3831                                &focus_handle,
3832                                cx,
3833                            )
3834                        }
3835                    },
3836                )
3837                .anchor(Corner::TopRight)
3838                .with_handle(self.new_thread_menu_handle.clone())
3839                .menu(move |window, cx| new_thread_menu_builder(window, cx));
3840
3841            base_container
3842                .child(
3843                    h_flex()
3844                        .size_full()
3845                        .gap(DynamicSpacing::Base04.rems(cx))
3846                        .pl(DynamicSpacing::Base04.rems(cx))
3847                        .child(match &self.active_view {
3848                            ActiveView::History { .. } | ActiveView::Configuration => {
3849                                self.render_toolbar_back_button(cx).into_any_element()
3850                            }
3851                            _ => selected_agent.into_any_element(),
3852                        })
3853                        .child(self.render_title_view(window, cx)),
3854                )
3855                .child(
3856                    h_flex()
3857                        .h_full()
3858                        .flex_none()
3859                        .gap_1()
3860                        .pl_1()
3861                        .pr_1()
3862                        .child(new_thread_menu)
3863                        .when(show_history_menu && !has_v2_flag, |this| {
3864                            this.child(self.render_recent_entries_menu(
3865                                IconName::MenuAltTemp,
3866                                Corner::TopRight,
3867                                cx,
3868                            ))
3869                        })
3870                        .child(full_screen_button)
3871                        .child(self.render_panel_options_menu(window, cx)),
3872                )
3873                .into_any_element()
3874        };
3875
3876        h_flex()
3877            .id("agent-panel-toolbar")
3878            .h(Tab::container_height(cx))
3879            .flex_shrink_0()
3880            .max_w_full()
3881            .bg(cx.theme().colors().tab_bar_background)
3882            .border_b_1()
3883            .border_color(cx.theme().colors().border)
3884            .child(toolbar_content)
3885    }
3886
3887    fn render_worktree_creation_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3888        let status = self.worktree_creation_status.as_ref()?;
3889        match status {
3890            WorktreeCreationStatus::Creating => Some(
3891                h_flex()
3892                    .absolute()
3893                    .bottom_12()
3894                    .w_full()
3895                    .p_2()
3896                    .gap_1()
3897                    .justify_center()
3898                    .bg(cx.theme().colors().editor_background)
3899                    .child(
3900                        Icon::new(IconName::LoadCircle)
3901                            .size(IconSize::Small)
3902                            .color(Color::Muted)
3903                            .with_rotate_animation(3),
3904                    )
3905                    .child(
3906                        Label::new("Creating Worktree…")
3907                            .color(Color::Muted)
3908                            .size(LabelSize::Small),
3909                    )
3910                    .into_any_element(),
3911            ),
3912            WorktreeCreationStatus::Error(message) => Some(
3913                Callout::new()
3914                    .icon(IconName::Warning)
3915                    .severity(Severity::Warning)
3916                    .title(message.clone())
3917                    .into_any_element(),
3918            ),
3919        }
3920    }
3921
3922    fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
3923        if TrialEndUpsell::dismissed(cx) {
3924            return false;
3925        }
3926
3927        match &self.active_view {
3928            ActiveView::AgentThread { .. } => {
3929                if LanguageModelRegistry::global(cx)
3930                    .read(cx)
3931                    .default_model()
3932                    .is_some_and(|model| {
3933                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
3934                    })
3935                {
3936                    return false;
3937                }
3938            }
3939            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
3940                return false;
3941            }
3942        }
3943
3944        let plan = self.user_store.read(cx).plan();
3945        let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
3946
3947        plan.is_some_and(|plan| plan == Plan::ZedFree) && has_previous_trial
3948    }
3949
3950    fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
3951        if self.on_boarding_upsell_dismissed.load(Ordering::Acquire) {
3952            return false;
3953        }
3954
3955        let user_store = self.user_store.read(cx);
3956
3957        if user_store.plan().is_some_and(|plan| plan == Plan::ZedPro)
3958            && user_store
3959                .subscription_period()
3960                .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
3961                .is_some_and(|date| date < chrono::Utc::now())
3962        {
3963            OnboardingUpsell::set_dismissed(true, cx);
3964            self.on_boarding_upsell_dismissed
3965                .store(true, Ordering::Release);
3966            return false;
3967        }
3968
3969        let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
3970            .visible_providers()
3971            .iter()
3972            .any(|provider| {
3973                provider.is_authenticated(cx)
3974                    && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
3975            });
3976
3977        match &self.active_view {
3978            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
3979                false
3980            }
3981            ActiveView::AgentThread {
3982                conversation_view, ..
3983            } if conversation_view.read(cx).as_native_thread(cx).is_none() => false,
3984            ActiveView::AgentThread { conversation_view } => {
3985                let history_is_empty = conversation_view
3986                    .read(cx)
3987                    .history()
3988                    .is_none_or(|h| h.read(cx).is_empty());
3989                history_is_empty || !has_configured_non_zed_providers
3990            }
3991        }
3992    }
3993
3994    fn render_onboarding(
3995        &self,
3996        _window: &mut Window,
3997        cx: &mut Context<Self>,
3998    ) -> Option<impl IntoElement> {
3999        if !self.should_render_onboarding(cx) {
4000            return None;
4001        }
4002
4003        Some(div().child(self.onboarding.clone()))
4004    }
4005
4006    fn render_trial_end_upsell(
4007        &self,
4008        _window: &mut Window,
4009        cx: &mut Context<Self>,
4010    ) -> Option<impl IntoElement> {
4011        if !self.should_render_trial_end_upsell(cx) {
4012            return None;
4013        }
4014
4015        Some(
4016            v_flex()
4017                .absolute()
4018                .inset_0()
4019                .size_full()
4020                .bg(cx.theme().colors().panel_background)
4021                .opacity(0.85)
4022                .block_mouse_except_scroll()
4023                .child(EndTrialUpsell::new(Arc::new({
4024                    let this = cx.entity();
4025                    move |_, cx| {
4026                        this.update(cx, |_this, cx| {
4027                            TrialEndUpsell::set_dismissed(true, cx);
4028                            cx.notify();
4029                        });
4030                    }
4031                }))),
4032        )
4033    }
4034
4035    fn render_drag_target(&self, cx: &Context<Self>) -> Div {
4036        let is_local = self.project.read(cx).is_local();
4037        div()
4038            .invisible()
4039            .absolute()
4040            .top_0()
4041            .right_0()
4042            .bottom_0()
4043            .left_0()
4044            .bg(cx.theme().colors().drop_target_background)
4045            .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
4046            .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
4047            .when(is_local, |this| {
4048                this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
4049            })
4050            .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
4051                let item = tab.pane.read(cx).item_for_index(tab.ix);
4052                let project_paths = item
4053                    .and_then(|item| item.project_path(cx))
4054                    .into_iter()
4055                    .collect::<Vec<_>>();
4056                this.handle_drop(project_paths, vec![], window, cx);
4057            }))
4058            .on_drop(
4059                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
4060                    let project_paths = selection
4061                        .items()
4062                        .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
4063                        .collect::<Vec<_>>();
4064                    this.handle_drop(project_paths, vec![], window, cx);
4065                }),
4066            )
4067            .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
4068                let tasks = paths
4069                    .paths()
4070                    .iter()
4071                    .map(|path| {
4072                        Workspace::project_path_for_path(this.project.clone(), path, false, cx)
4073                    })
4074                    .collect::<Vec<_>>();
4075                cx.spawn_in(window, async move |this, cx| {
4076                    let mut paths = vec![];
4077                    let mut added_worktrees = vec![];
4078                    let opened_paths = futures::future::join_all(tasks).await;
4079                    for entry in opened_paths {
4080                        if let Some((worktree, project_path)) = entry.log_err() {
4081                            added_worktrees.push(worktree);
4082                            paths.push(project_path);
4083                        }
4084                    }
4085                    this.update_in(cx, |this, window, cx| {
4086                        this.handle_drop(paths, added_worktrees, window, cx);
4087                    })
4088                    .ok();
4089                })
4090                .detach();
4091            }))
4092    }
4093
4094    fn handle_drop(
4095        &mut self,
4096        paths: Vec<ProjectPath>,
4097        added_worktrees: Vec<Entity<Worktree>>,
4098        window: &mut Window,
4099        cx: &mut Context<Self>,
4100    ) {
4101        match &self.active_view {
4102            ActiveView::AgentThread { conversation_view } => {
4103                conversation_view.update(cx, |conversation_view, cx| {
4104                    conversation_view.insert_dragged_files(paths, added_worktrees, window, cx);
4105                });
4106            }
4107            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4108        }
4109    }
4110
4111    fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
4112        if !self.show_trust_workspace_message {
4113            return None;
4114        }
4115
4116        let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
4117
4118        Some(
4119            Callout::new()
4120                .icon(IconName::Warning)
4121                .severity(Severity::Warning)
4122                .border_position(ui::BorderPosition::Bottom)
4123                .title("You're in Restricted Mode")
4124                .description(description)
4125                .actions_slot(
4126                    Button::new("open-trust-modal", "Configure Project Trust")
4127                        .label_size(LabelSize::Small)
4128                        .style(ButtonStyle::Outlined)
4129                        .on_click({
4130                            cx.listener(move |this, _, window, cx| {
4131                                this.workspace
4132                                    .update(cx, |workspace, cx| {
4133                                        workspace
4134                                            .show_worktree_trust_security_modal(true, window, cx)
4135                                    })
4136                                    .log_err();
4137                            })
4138                        }),
4139                ),
4140        )
4141    }
4142
4143    fn key_context(&self) -> KeyContext {
4144        let mut key_context = KeyContext::new_with_defaults();
4145        key_context.add("AgentPanel");
4146        match &self.active_view {
4147            ActiveView::AgentThread { .. } => key_context.add("acp_thread"),
4148            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4149        }
4150        key_context
4151    }
4152}
4153
4154impl Render for AgentPanel {
4155    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4156        // WARNING: Changes to this element hierarchy can have
4157        // non-obvious implications to the layout of children.
4158        //
4159        // If you need to change it, please confirm:
4160        // - The message editor expands (cmd-option-esc) correctly
4161        // - When expanded, the buttons at the bottom of the panel are displayed correctly
4162        // - Font size works as expected and can be changed with cmd-+/cmd-
4163        // - Scrolling in all views works as expected
4164        // - Files can be dropped into the panel
4165        let content = v_flex()
4166            .relative()
4167            .size_full()
4168            .justify_between()
4169            .key_context(self.key_context())
4170            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
4171                this.new_thread(action, window, cx);
4172            }))
4173            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
4174                this.open_history(window, cx);
4175            }))
4176            .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
4177                this.open_configuration(window, cx);
4178            }))
4179            .on_action(cx.listener(Self::open_active_thread_as_markdown))
4180            .on_action(cx.listener(Self::deploy_rules_library))
4181            .on_action(cx.listener(Self::go_back))
4182            .on_action(cx.listener(Self::toggle_navigation_menu))
4183            .on_action(cx.listener(Self::toggle_options_menu))
4184            .on_action(cx.listener(Self::increase_font_size))
4185            .on_action(cx.listener(Self::decrease_font_size))
4186            .on_action(cx.listener(Self::reset_font_size))
4187            .on_action(cx.listener(Self::toggle_zoom))
4188            .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
4189                if let Some(conversation_view) = this.active_conversation_view() {
4190                    conversation_view.update(cx, |conversation_view, cx| {
4191                        conversation_view.reauthenticate(window, cx)
4192                    })
4193                }
4194            }))
4195            .child(self.render_toolbar(window, cx))
4196            .children(self.render_workspace_trust_message(cx))
4197            .children(self.render_onboarding(window, cx))
4198            .map(|parent| match &self.active_view {
4199                ActiveView::Uninitialized => parent,
4200                ActiveView::AgentThread {
4201                    conversation_view, ..
4202                } => parent
4203                    .child(conversation_view.clone())
4204                    .child(self.render_drag_target(cx)),
4205                ActiveView::History { view } => parent.child(view.clone()),
4206                ActiveView::Configuration => parent.children(self.configuration.clone()),
4207            })
4208            .children(self.render_worktree_creation_status(cx))
4209            .children(self.render_trial_end_upsell(window, cx));
4210
4211        match self.active_view.which_font_size_used() {
4212            WhichFontSize::AgentFont => {
4213                WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
4214                    .size_full()
4215                    .child(content)
4216                    .into_any()
4217            }
4218            _ => content.into_any(),
4219        }
4220    }
4221}
4222
4223struct PromptLibraryInlineAssist {
4224    workspace: WeakEntity<Workspace>,
4225}
4226
4227impl PromptLibraryInlineAssist {
4228    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
4229        Self { workspace }
4230    }
4231}
4232
4233impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
4234    fn assist(
4235        &self,
4236        prompt_editor: &Entity<Editor>,
4237        initial_prompt: Option<String>,
4238        window: &mut Window,
4239        cx: &mut Context<RulesLibrary>,
4240    ) {
4241        InlineAssistant::update_global(cx, |assistant, cx| {
4242            let Some(workspace) = self.workspace.upgrade() else {
4243                return;
4244            };
4245            let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4246                return;
4247            };
4248            let history = panel
4249                .read(cx)
4250                .connection_store()
4251                .read(cx)
4252                .entry(&crate::Agent::NativeAgent)
4253                .and_then(|s| s.read(cx).history())
4254                .map(|h| h.downgrade());
4255            let project = workspace.read(cx).project().downgrade();
4256            let panel = panel.read(cx);
4257            let thread_store = panel.thread_store().clone();
4258            assistant.assist(
4259                prompt_editor,
4260                self.workspace.clone(),
4261                project,
4262                thread_store,
4263                None,
4264                history,
4265                initial_prompt,
4266                window,
4267                cx,
4268            );
4269        })
4270    }
4271
4272    fn focus_agent_panel(
4273        &self,
4274        workspace: &mut Workspace,
4275        window: &mut Window,
4276        cx: &mut Context<Workspace>,
4277    ) -> bool {
4278        workspace.focus_panel::<AgentPanel>(window, cx).is_some()
4279    }
4280}
4281
4282struct OnboardingUpsell;
4283
4284impl Dismissable for OnboardingUpsell {
4285    const KEY: &'static str = "dismissed-trial-upsell";
4286}
4287
4288struct TrialEndUpsell;
4289
4290impl Dismissable for TrialEndUpsell {
4291    const KEY: &'static str = "dismissed-trial-end-upsell";
4292}
4293
4294/// Test-only helper methods
4295#[cfg(any(test, feature = "test-support"))]
4296impl AgentPanel {
4297    pub fn test_new(workspace: &Workspace, window: &mut Window, cx: &mut Context<Self>) -> Self {
4298        Self::new(workspace, None, window, cx)
4299    }
4300
4301    /// Opens an external thread using an arbitrary AgentServer.
4302    ///
4303    /// This is a test-only helper that allows visual tests and integration tests
4304    /// to inject a stub server without modifying production code paths.
4305    /// Not compiled into production builds.
4306    pub fn open_external_thread_with_server(
4307        &mut self,
4308        server: Rc<dyn AgentServer>,
4309        window: &mut Window,
4310        cx: &mut Context<Self>,
4311    ) {
4312        let workspace = self.workspace.clone();
4313        let project = self.project.clone();
4314
4315        let ext_agent = Agent::Custom {
4316            id: server.agent_id(),
4317        };
4318
4319        self.create_agent_thread(
4320            server, None, None, None, None, workspace, project, ext_agent, true, window, cx,
4321        );
4322    }
4323
4324    /// Returns the currently active thread view, if any.
4325    ///
4326    /// This is a test-only accessor that exposes the private `active_thread_view()`
4327    /// method for test assertions. Not compiled into production builds.
4328    pub fn active_thread_view_for_tests(&self) -> Option<&Entity<ConversationView>> {
4329        self.active_conversation_view()
4330    }
4331
4332    /// Sets the start_thread_in value directly, bypassing validation.
4333    ///
4334    /// This is a test-only helper for visual tests that need to show specific
4335    /// start_thread_in states without requiring a real git repository.
4336    pub fn set_start_thread_in_for_tests(&mut self, target: StartThreadIn, cx: &mut Context<Self>) {
4337        self.start_thread_in = target;
4338        cx.notify();
4339    }
4340
4341    /// Returns the current worktree creation status.
4342    ///
4343    /// This is a test-only helper for visual tests.
4344    pub fn worktree_creation_status_for_tests(&self) -> Option<&WorktreeCreationStatus> {
4345        self.worktree_creation_status.as_ref()
4346    }
4347
4348    /// Sets the worktree creation status directly.
4349    ///
4350    /// This is a test-only helper for visual tests that need to show the
4351    /// "Creating worktree…" spinner or error banners.
4352    pub fn set_worktree_creation_status_for_tests(
4353        &mut self,
4354        status: Option<WorktreeCreationStatus>,
4355        cx: &mut Context<Self>,
4356    ) {
4357        self.worktree_creation_status = status;
4358        cx.notify();
4359    }
4360
4361    /// Opens the history view.
4362    ///
4363    /// This is a test-only helper that exposes the private `open_history()`
4364    /// method for visual tests.
4365    pub fn open_history_for_tests(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4366        self.open_history(window, cx);
4367    }
4368
4369    /// Opens the start_thread_in selector popover menu.
4370    ///
4371    /// This is a test-only helper for visual tests.
4372    pub fn open_start_thread_in_menu_for_tests(
4373        &mut self,
4374        window: &mut Window,
4375        cx: &mut Context<Self>,
4376    ) {
4377        self.start_thread_in_menu_handle.show(window, cx);
4378    }
4379
4380    /// Dismisses the start_thread_in dropdown menu.
4381    ///
4382    /// This is a test-only helper for visual tests.
4383    pub fn close_start_thread_in_menu_for_tests(&mut self, cx: &mut Context<Self>) {
4384        self.start_thread_in_menu_handle.hide(cx);
4385    }
4386}
4387
4388#[cfg(test)]
4389mod tests {
4390    use super::*;
4391    use crate::conversation_view::tests::{StubAgentServer, init_test};
4392    use crate::test_support::{
4393        active_session_id, open_thread_with_connection, open_thread_with_custom_connection,
4394        send_message,
4395    };
4396    use acp_thread::{StubAgentConnection, ThreadStatus};
4397    use agent_servers::CODEX_ID;
4398    use feature_flags::FeatureFlagAppExt;
4399    use fs::FakeFs;
4400    use gpui::{TestAppContext, VisualTestContext};
4401    use project::Project;
4402    use serde_json::json;
4403    use std::path::Path;
4404    use std::time::Instant;
4405    use workspace::MultiWorkspace;
4406
4407    #[gpui::test]
4408    async fn test_active_thread_serialize_and_load_round_trip(cx: &mut TestAppContext) {
4409        init_test(cx);
4410        cx.update(|cx| {
4411            cx.update_flags(true, vec!["agent-v2".to_string()]);
4412            agent::ThreadStore::init_global(cx);
4413            language_model::LanguageModelRegistry::test(cx);
4414        });
4415
4416        // --- Create a MultiWorkspace window with two workspaces ---
4417        let fs = FakeFs::new(cx.executor());
4418        let project_a = Project::test(fs.clone(), [], cx).await;
4419        let project_b = Project::test(fs, [], cx).await;
4420
4421        let multi_workspace =
4422            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
4423
4424        let workspace_a = multi_workspace
4425            .read_with(cx, |multi_workspace, _cx| {
4426                multi_workspace.workspace().clone()
4427            })
4428            .unwrap();
4429
4430        let workspace_b = multi_workspace
4431            .update(cx, |multi_workspace, window, cx| {
4432                multi_workspace.test_add_workspace(project_b.clone(), window, cx)
4433            })
4434            .unwrap();
4435
4436        workspace_a.update(cx, |workspace, _cx| {
4437            workspace.set_random_database_id();
4438        });
4439        workspace_b.update(cx, |workspace, _cx| {
4440            workspace.set_random_database_id();
4441        });
4442
4443        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
4444
4445        // --- Set up workspace A: with an active thread ---
4446        let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
4447            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
4448        });
4449
4450        panel_a.update_in(cx, |panel, window, cx| {
4451            panel.open_external_thread_with_server(
4452                Rc::new(StubAgentServer::default_response()),
4453                window,
4454                cx,
4455            );
4456        });
4457
4458        cx.run_until_parked();
4459
4460        panel_a.read_with(cx, |panel, cx| {
4461            assert!(
4462                panel.active_agent_thread(cx).is_some(),
4463                "workspace A should have an active thread after connection"
4464            );
4465        });
4466
4467        send_message(&panel_a, cx);
4468
4469        let agent_type_a = panel_a.read_with(cx, |panel, _cx| panel.selected_agent.clone());
4470
4471        // --- Set up workspace B: ClaudeCode, no active thread ---
4472        let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
4473            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
4474        });
4475
4476        panel_b.update(cx, |panel, _cx| {
4477            panel.selected_agent = Agent::Custom {
4478                id: "claude-acp".into(),
4479            };
4480        });
4481
4482        // --- Serialize both panels ---
4483        panel_a.update(cx, |panel, cx| panel.serialize(cx));
4484        panel_b.update(cx, |panel, cx| panel.serialize(cx));
4485        cx.run_until_parked();
4486
4487        // --- Load fresh panels for each workspace and verify independent state ---
4488        let async_cx = cx.update(|window, cx| window.to_async(cx));
4489        let loaded_a = AgentPanel::load(workspace_a.downgrade(), async_cx)
4490            .await
4491            .expect("panel A load should succeed");
4492        cx.run_until_parked();
4493
4494        let async_cx = cx.update(|window, cx| window.to_async(cx));
4495        let loaded_b = AgentPanel::load(workspace_b.downgrade(), async_cx)
4496            .await
4497            .expect("panel B load should succeed");
4498        cx.run_until_parked();
4499
4500        // Workspace A should restore its thread and agent type
4501        loaded_a.read_with(cx, |panel, _cx| {
4502            assert_eq!(
4503                panel.selected_agent, agent_type_a,
4504                "workspace A agent type should be restored"
4505            );
4506            assert!(
4507                panel.active_conversation_view().is_some(),
4508                "workspace A should have its active thread restored"
4509            );
4510        });
4511
4512        // Workspace B should restore its own agent type, with no thread
4513        loaded_b.read_with(cx, |panel, _cx| {
4514            assert_eq!(
4515                panel.selected_agent,
4516                Agent::Custom {
4517                    id: "claude-acp".into()
4518                },
4519                "workspace B agent type should be restored"
4520            );
4521            assert!(
4522                panel.active_conversation_view().is_none(),
4523                "workspace B should have no active thread"
4524            );
4525        });
4526    }
4527
4528    #[gpui::test]
4529    async fn test_non_native_thread_without_metadata_is_not_restored(cx: &mut TestAppContext) {
4530        init_test(cx);
4531        cx.update(|cx| {
4532            cx.update_flags(true, vec!["agent-v2".to_string()]);
4533            agent::ThreadStore::init_global(cx);
4534            language_model::LanguageModelRegistry::test(cx);
4535        });
4536
4537        let fs = FakeFs::new(cx.executor());
4538        let project = Project::test(fs, [], cx).await;
4539
4540        let multi_workspace =
4541            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4542
4543        let workspace = multi_workspace
4544            .read_with(cx, |multi_workspace, _cx| {
4545                multi_workspace.workspace().clone()
4546            })
4547            .unwrap();
4548
4549        workspace.update(cx, |workspace, _cx| {
4550            workspace.set_random_database_id();
4551        });
4552
4553        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
4554
4555        let panel = workspace.update_in(cx, |workspace, window, cx| {
4556            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
4557        });
4558
4559        panel.update_in(cx, |panel, window, cx| {
4560            panel.open_external_thread_with_server(
4561                Rc::new(StubAgentServer::default_response()),
4562                window,
4563                cx,
4564            );
4565        });
4566
4567        cx.run_until_parked();
4568
4569        panel.read_with(cx, |panel, cx| {
4570            assert!(
4571                panel.active_agent_thread(cx).is_some(),
4572                "should have an active thread after connection"
4573            );
4574        });
4575
4576        // Serialize without ever sending a message, so no thread metadata exists.
4577        panel.update(cx, |panel, cx| panel.serialize(cx));
4578        cx.run_until_parked();
4579
4580        let async_cx = cx.update(|window, cx| window.to_async(cx));
4581        let loaded = AgentPanel::load(workspace.downgrade(), async_cx)
4582            .await
4583            .expect("panel load should succeed");
4584        cx.run_until_parked();
4585
4586        loaded.read_with(cx, |panel, _cx| {
4587            assert!(
4588                panel.active_conversation_view().is_none(),
4589                "thread without metadata should not be restored"
4590            );
4591        });
4592    }
4593
4594    /// Extracts the text from a Text content block, panicking if it's not Text.
4595    fn expect_text_block(block: &acp::ContentBlock) -> &str {
4596        match block {
4597            acp::ContentBlock::Text(t) => t.text.as_str(),
4598            other => panic!("expected Text block, got {:?}", other),
4599        }
4600    }
4601
4602    /// Extracts the (text_content, uri) from a Resource content block, panicking
4603    /// if it's not a TextResourceContents resource.
4604    fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
4605        match block {
4606            acp::ContentBlock::Resource(r) => match &r.resource {
4607                acp::EmbeddedResourceResource::TextResourceContents(t) => {
4608                    (t.text.as_str(), t.uri.as_str())
4609                }
4610                other => panic!("expected TextResourceContents, got {:?}", other),
4611            },
4612            other => panic!("expected Resource block, got {:?}", other),
4613        }
4614    }
4615
4616    #[test]
4617    fn test_build_conflict_resolution_prompt_single_conflict() {
4618        let conflicts = vec![ConflictContent {
4619            file_path: "src/main.rs".to_string(),
4620            conflict_text: "<<<<<<< HEAD\nlet x = 1;\n=======\nlet x = 2;\n>>>>>>> feature"
4621                .to_string(),
4622            ours_branch_name: "HEAD".to_string(),
4623            theirs_branch_name: "feature".to_string(),
4624        }];
4625
4626        let blocks = build_conflict_resolution_prompt(&conflicts);
4627        // 2 Text blocks + 1 ResourceLink + 1 Resource for the conflict
4628        assert_eq!(
4629            blocks.len(),
4630            4,
4631            "expected 2 text + 1 resource link + 1 resource block"
4632        );
4633
4634        let intro_text = expect_text_block(&blocks[0]);
4635        assert!(
4636            intro_text.contains("Please resolve the following merge conflict in"),
4637            "prompt should include single-conflict intro text"
4638        );
4639
4640        match &blocks[1] {
4641            acp::ContentBlock::ResourceLink(link) => {
4642                assert!(
4643                    link.uri.contains("file://"),
4644                    "resource link URI should use file scheme"
4645                );
4646                assert!(
4647                    link.uri.contains("main.rs"),
4648                    "resource link URI should reference file path"
4649                );
4650            }
4651            other => panic!("expected ResourceLink block, got {:?}", other),
4652        }
4653
4654        let body_text = expect_text_block(&blocks[2]);
4655        assert!(
4656            body_text.contains("`HEAD` (ours)"),
4657            "prompt should mention ours branch"
4658        );
4659        assert!(
4660            body_text.contains("`feature` (theirs)"),
4661            "prompt should mention theirs branch"
4662        );
4663        assert!(
4664            body_text.contains("editing the file directly"),
4665            "prompt should instruct the agent to edit the file"
4666        );
4667
4668        let (resource_text, resource_uri) = expect_resource_block(&blocks[3]);
4669        assert!(
4670            resource_text.contains("<<<<<<< HEAD"),
4671            "resource should contain the conflict text"
4672        );
4673        assert!(
4674            resource_uri.contains("merge-conflict"),
4675            "resource URI should use the merge-conflict scheme"
4676        );
4677        assert!(
4678            resource_uri.contains("main.rs"),
4679            "resource URI should reference the file path"
4680        );
4681    }
4682
4683    #[test]
4684    fn test_build_conflict_resolution_prompt_multiple_conflicts_same_file() {
4685        let conflicts = vec![
4686            ConflictContent {
4687                file_path: "src/lib.rs".to_string(),
4688                conflict_text: "<<<<<<< main\nfn a() {}\n=======\nfn a_v2() {}\n>>>>>>> dev"
4689                    .to_string(),
4690                ours_branch_name: "main".to_string(),
4691                theirs_branch_name: "dev".to_string(),
4692            },
4693            ConflictContent {
4694                file_path: "src/lib.rs".to_string(),
4695                conflict_text: "<<<<<<< main\nfn b() {}\n=======\nfn b_v2() {}\n>>>>>>> dev"
4696                    .to_string(),
4697                ours_branch_name: "main".to_string(),
4698                theirs_branch_name: "dev".to_string(),
4699            },
4700        ];
4701
4702        let blocks = build_conflict_resolution_prompt(&conflicts);
4703        // 1 Text instruction + 2 Resource blocks
4704        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
4705
4706        let text = expect_text_block(&blocks[0]);
4707        assert!(
4708            text.contains("all 2 merge conflicts"),
4709            "prompt should mention the total count"
4710        );
4711        assert!(
4712            text.contains("`main` (ours)"),
4713            "prompt should mention ours branch"
4714        );
4715        assert!(
4716            text.contains("`dev` (theirs)"),
4717            "prompt should mention theirs branch"
4718        );
4719        // Single file, so "file" not "files"
4720        assert!(
4721            text.contains("file directly"),
4722            "single file should use singular 'file'"
4723        );
4724
4725        let (resource_a, _) = expect_resource_block(&blocks[1]);
4726        let (resource_b, _) = expect_resource_block(&blocks[2]);
4727        assert!(
4728            resource_a.contains("fn a()"),
4729            "first resource should contain first conflict"
4730        );
4731        assert!(
4732            resource_b.contains("fn b()"),
4733            "second resource should contain second conflict"
4734        );
4735    }
4736
4737    #[test]
4738    fn test_build_conflict_resolution_prompt_multiple_conflicts_different_files() {
4739        let conflicts = vec![
4740            ConflictContent {
4741                file_path: "src/a.rs".to_string(),
4742                conflict_text: "<<<<<<< main\nA\n=======\nB\n>>>>>>> dev".to_string(),
4743                ours_branch_name: "main".to_string(),
4744                theirs_branch_name: "dev".to_string(),
4745            },
4746            ConflictContent {
4747                file_path: "src/b.rs".to_string(),
4748                conflict_text: "<<<<<<< main\nC\n=======\nD\n>>>>>>> dev".to_string(),
4749                ours_branch_name: "main".to_string(),
4750                theirs_branch_name: "dev".to_string(),
4751            },
4752        ];
4753
4754        let blocks = build_conflict_resolution_prompt(&conflicts);
4755        // 1 Text instruction + 2 Resource blocks
4756        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
4757
4758        let text = expect_text_block(&blocks[0]);
4759        assert!(
4760            text.contains("files directly"),
4761            "multiple files should use plural 'files'"
4762        );
4763
4764        let (_, uri_a) = expect_resource_block(&blocks[1]);
4765        let (_, uri_b) = expect_resource_block(&blocks[2]);
4766        assert!(
4767            uri_a.contains("a.rs"),
4768            "first resource URI should reference a.rs"
4769        );
4770        assert!(
4771            uri_b.contains("b.rs"),
4772            "second resource URI should reference b.rs"
4773        );
4774    }
4775
4776    #[test]
4777    fn test_build_conflicted_files_resolution_prompt_file_paths_only() {
4778        let file_paths = vec![
4779            "src/main.rs".to_string(),
4780            "src/lib.rs".to_string(),
4781            "tests/integration.rs".to_string(),
4782        ];
4783
4784        let blocks = build_conflicted_files_resolution_prompt(&file_paths);
4785        // 1 instruction Text block + (ResourceLink + newline Text) per file
4786        assert_eq!(
4787            blocks.len(),
4788            1 + (file_paths.len() * 2),
4789            "expected instruction text plus resource links and separators"
4790        );
4791
4792        let text = expect_text_block(&blocks[0]);
4793        assert!(
4794            text.contains("unresolved merge conflicts"),
4795            "prompt should describe the task"
4796        );
4797        assert!(
4798            text.contains("conflict markers"),
4799            "prompt should mention conflict markers"
4800        );
4801
4802        for (index, path) in file_paths.iter().enumerate() {
4803            let link_index = 1 + (index * 2);
4804            let newline_index = link_index + 1;
4805
4806            match &blocks[link_index] {
4807                acp::ContentBlock::ResourceLink(link) => {
4808                    assert!(
4809                        link.uri.contains("file://"),
4810                        "resource link URI should use file scheme"
4811                    );
4812                    assert!(
4813                        link.uri.contains(path),
4814                        "resource link URI should reference file path: {path}"
4815                    );
4816                }
4817                other => panic!(
4818                    "expected ResourceLink block at index {}, got {:?}",
4819                    link_index, other
4820                ),
4821            }
4822
4823            let separator = expect_text_block(&blocks[newline_index]);
4824            assert_eq!(
4825                separator, "\n",
4826                "expected newline separator after each file"
4827            );
4828        }
4829    }
4830
4831    #[test]
4832    fn test_build_conflict_resolution_prompt_empty_conflicts() {
4833        let blocks = build_conflict_resolution_prompt(&[]);
4834        assert!(
4835            blocks.is_empty(),
4836            "empty conflicts should produce no blocks, got {} blocks",
4837            blocks.len()
4838        );
4839    }
4840
4841    #[test]
4842    fn test_build_conflicted_files_resolution_prompt_empty_paths() {
4843        let blocks = build_conflicted_files_resolution_prompt(&[]);
4844        assert!(
4845            blocks.is_empty(),
4846            "empty paths should produce no blocks, got {} blocks",
4847            blocks.len()
4848        );
4849    }
4850
4851    #[test]
4852    fn test_conflict_resource_block_structure() {
4853        let conflict = ConflictContent {
4854            file_path: "src/utils.rs".to_string(),
4855            conflict_text: "<<<<<<< HEAD\nold code\n=======\nnew code\n>>>>>>> branch".to_string(),
4856            ours_branch_name: "HEAD".to_string(),
4857            theirs_branch_name: "branch".to_string(),
4858        };
4859
4860        let block = conflict_resource_block(&conflict);
4861        let (text, uri) = expect_resource_block(&block);
4862
4863        assert_eq!(
4864            text, conflict.conflict_text,
4865            "resource text should be the raw conflict"
4866        );
4867        assert!(
4868            uri.starts_with("zed:///agent/merge-conflict"),
4869            "URI should use the zed merge-conflict scheme, got: {uri}"
4870        );
4871        assert!(uri.contains("utils.rs"), "URI should encode the file path");
4872    }
4873
4874    fn open_generating_thread_with_loadable_connection(
4875        panel: &Entity<AgentPanel>,
4876        connection: &StubAgentConnection,
4877        cx: &mut VisualTestContext,
4878    ) -> acp::SessionId {
4879        open_thread_with_custom_connection(panel, connection.clone(), cx);
4880        let session_id = active_session_id(panel, cx);
4881        send_message(panel, cx);
4882        cx.update(|_, cx| {
4883            connection.send_update(
4884                session_id.clone(),
4885                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("done".into())),
4886                cx,
4887            );
4888        });
4889        cx.run_until_parked();
4890        session_id
4891    }
4892
4893    fn open_idle_thread_with_non_loadable_connection(
4894        panel: &Entity<AgentPanel>,
4895        connection: &StubAgentConnection,
4896        cx: &mut VisualTestContext,
4897    ) -> acp::SessionId {
4898        open_thread_with_custom_connection(panel, connection.clone(), cx);
4899        let session_id = active_session_id(panel, cx);
4900
4901        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4902            acp::ContentChunk::new("done".into()),
4903        )]);
4904        send_message(panel, cx);
4905
4906        session_id
4907    }
4908
4909    async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {
4910        init_test(cx);
4911        cx.update(|cx| {
4912            cx.update_flags(true, vec!["agent-v2".to_string()]);
4913            agent::ThreadStore::init_global(cx);
4914            language_model::LanguageModelRegistry::test(cx);
4915        });
4916
4917        let fs = FakeFs::new(cx.executor());
4918        let project = Project::test(fs.clone(), [], cx).await;
4919
4920        let multi_workspace =
4921            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4922
4923        let workspace = multi_workspace
4924            .read_with(cx, |mw, _cx| mw.workspace().clone())
4925            .unwrap();
4926
4927        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
4928
4929        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
4930            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
4931        });
4932
4933        (panel, cx)
4934    }
4935
4936    #[gpui::test]
4937    async fn test_empty_draft_thread_not_retained_when_navigating_away(cx: &mut TestAppContext) {
4938        let (panel, mut cx) = setup_panel(cx).await;
4939
4940        let connection_a = StubAgentConnection::new();
4941        open_thread_with_connection(&panel, connection_a, &mut cx);
4942        let session_id_a = active_session_id(&panel, &cx);
4943
4944        panel.read_with(&cx, |panel, cx| {
4945            let thread = panel.active_agent_thread(cx).unwrap();
4946            assert!(
4947                thread.read(cx).entries().is_empty(),
4948                "newly opened draft thread should have no entries"
4949            );
4950            assert!(panel.background_threads.is_empty());
4951        });
4952
4953        let connection_b = StubAgentConnection::new();
4954        open_thread_with_connection(&panel, connection_b, &mut cx);
4955
4956        panel.read_with(&cx, |panel, _cx| {
4957            assert!(
4958                panel.background_threads.is_empty(),
4959                "empty draft thread should not be retained in background_threads"
4960            );
4961            assert!(
4962                !panel.background_threads.contains_key(&session_id_a),
4963                "empty draft thread should not be keyed in background_threads"
4964            );
4965        });
4966    }
4967
4968    #[gpui::test]
4969    async fn test_running_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
4970        let (panel, mut cx) = setup_panel(cx).await;
4971
4972        let connection_a = StubAgentConnection::new();
4973        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
4974        send_message(&panel, &mut cx);
4975
4976        let session_id_a = active_session_id(&panel, &cx);
4977
4978        // Send a chunk to keep thread A generating (don't end the turn).
4979        cx.update(|_, cx| {
4980            connection_a.send_update(
4981                session_id_a.clone(),
4982                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
4983                cx,
4984            );
4985        });
4986        cx.run_until_parked();
4987
4988        // Verify thread A is generating.
4989        panel.read_with(&cx, |panel, cx| {
4990            let thread = panel.active_agent_thread(cx).unwrap();
4991            assert_eq!(thread.read(cx).status(), ThreadStatus::Generating);
4992            assert!(panel.background_threads.is_empty());
4993        });
4994
4995        // Open a new thread B — thread A should be retained in background.
4996        let connection_b = StubAgentConnection::new();
4997        open_thread_with_connection(&panel, connection_b, &mut cx);
4998
4999        panel.read_with(&cx, |panel, _cx| {
5000            assert_eq!(
5001                panel.background_threads.len(),
5002                1,
5003                "Running thread A should be retained in background_views"
5004            );
5005            assert!(
5006                panel.background_threads.contains_key(&session_id_a),
5007                "Background view should be keyed by thread A's session ID"
5008            );
5009        });
5010    }
5011
5012    #[gpui::test]
5013    async fn test_idle_non_loadable_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5014        let (panel, mut cx) = setup_panel(cx).await;
5015
5016        let connection_a = StubAgentConnection::new();
5017        connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5018            acp::ContentChunk::new("Response".into()),
5019        )]);
5020        open_thread_with_connection(&panel, connection_a, &mut cx);
5021        send_message(&panel, &mut cx);
5022
5023        let weak_view_a = panel.read_with(&cx, |panel, _cx| {
5024            panel.active_conversation_view().unwrap().downgrade()
5025        });
5026        let session_id_a = active_session_id(&panel, &cx);
5027
5028        // Thread A should be idle (auto-completed via set_next_prompt_updates).
5029        panel.read_with(&cx, |panel, cx| {
5030            let thread = panel.active_agent_thread(cx).unwrap();
5031            assert_eq!(thread.read(cx).status(), ThreadStatus::Idle);
5032        });
5033
5034        // Open a new thread B — thread A should be retained because it is not loadable.
5035        let connection_b = StubAgentConnection::new();
5036        open_thread_with_connection(&panel, connection_b, &mut cx);
5037
5038        panel.read_with(&cx, |panel, _cx| {
5039            assert_eq!(
5040                panel.background_threads.len(),
5041                1,
5042                "Idle non-loadable thread A should be retained in background_views"
5043            );
5044            assert!(
5045                panel.background_threads.contains_key(&session_id_a),
5046                "Background view should be keyed by thread A's session ID"
5047            );
5048        });
5049
5050        assert!(
5051            weak_view_a.upgrade().is_some(),
5052            "Idle non-loadable ConnectionView should still be retained"
5053        );
5054    }
5055
5056    #[gpui::test]
5057    async fn test_background_thread_promoted_via_load(cx: &mut TestAppContext) {
5058        let (panel, mut cx) = setup_panel(cx).await;
5059
5060        let connection_a = StubAgentConnection::new();
5061        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5062        send_message(&panel, &mut cx);
5063
5064        let session_id_a = active_session_id(&panel, &cx);
5065
5066        // Keep thread A generating.
5067        cx.update(|_, cx| {
5068            connection_a.send_update(
5069                session_id_a.clone(),
5070                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5071                cx,
5072            );
5073        });
5074        cx.run_until_parked();
5075
5076        // Open thread B — thread A goes to background.
5077        let connection_b = StubAgentConnection::new();
5078        open_thread_with_connection(&panel, connection_b, &mut cx);
5079        send_message(&panel, &mut cx);
5080
5081        let session_id_b = active_session_id(&panel, &cx);
5082
5083        panel.read_with(&cx, |panel, _cx| {
5084            assert_eq!(panel.background_threads.len(), 1);
5085            assert!(panel.background_threads.contains_key(&session_id_a));
5086        });
5087
5088        // Load thread A back via load_agent_thread — should promote from background.
5089        panel.update_in(&mut cx, |panel, window, cx| {
5090            panel.load_agent_thread(
5091                panel.selected_agent().expect("selected agent must be set"),
5092                session_id_a.clone(),
5093                None,
5094                None,
5095                true,
5096                window,
5097                cx,
5098            );
5099        });
5100
5101        // Thread A should now be the active view, promoted from background.
5102        let active_session = active_session_id(&panel, &cx);
5103        assert_eq!(
5104            active_session, session_id_a,
5105            "Thread A should be the active thread after promotion"
5106        );
5107
5108        panel.read_with(&cx, |panel, _cx| {
5109            assert!(
5110                !panel.background_threads.contains_key(&session_id_a),
5111                "Promoted thread A should no longer be in background_views"
5112            );
5113            assert!(
5114                panel.background_threads.contains_key(&session_id_b),
5115                "Thread B (idle, non-loadable) should remain retained in background_views"
5116            );
5117        });
5118    }
5119
5120    #[gpui::test]
5121    async fn test_cleanup_background_threads_keeps_five_most_recent_idle_loadable_threads(
5122        cx: &mut TestAppContext,
5123    ) {
5124        let (panel, mut cx) = setup_panel(cx).await;
5125        let connection = StubAgentConnection::new()
5126            .with_supports_load_session(true)
5127            .with_agent_id("loadable-stub".into())
5128            .with_telemetry_id("loadable-stub".into());
5129        let mut session_ids = Vec::new();
5130
5131        for _ in 0..7 {
5132            session_ids.push(open_generating_thread_with_loadable_connection(
5133                &panel,
5134                &connection,
5135                &mut cx,
5136            ));
5137        }
5138
5139        let base_time = Instant::now();
5140
5141        for session_id in session_ids.iter().take(6) {
5142            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5143        }
5144        cx.run_until_parked();
5145
5146        panel.update(&mut cx, |panel, cx| {
5147            for (index, session_id) in session_ids.iter().take(6).enumerate() {
5148                let conversation_view = panel
5149                    .background_threads
5150                    .get(session_id)
5151                    .expect("background thread should exist")
5152                    .clone();
5153                conversation_view.update(cx, |view, cx| {
5154                    view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5155                });
5156            }
5157            panel.cleanup_background_threads(cx);
5158        });
5159
5160        panel.read_with(&cx, |panel, _cx| {
5161            assert_eq!(
5162                panel.background_threads.len(),
5163                5,
5164                "cleanup should keep at most five idle loadable background threads"
5165            );
5166            assert!(
5167                !panel.background_threads.contains_key(&session_ids[0]),
5168                "oldest idle loadable background thread should be removed"
5169            );
5170            for session_id in &session_ids[1..6] {
5171                assert!(
5172                    panel.background_threads.contains_key(session_id),
5173                    "more recent idle loadable background threads should be retained"
5174                );
5175            }
5176            assert!(
5177                !panel.background_threads.contains_key(&session_ids[6]),
5178                "the active thread should not also be stored as a background thread"
5179            );
5180        });
5181    }
5182
5183    #[gpui::test]
5184    async fn test_cleanup_background_threads_preserves_idle_non_loadable_threads(
5185        cx: &mut TestAppContext,
5186    ) {
5187        let (panel, mut cx) = setup_panel(cx).await;
5188
5189        let non_loadable_connection = StubAgentConnection::new();
5190        let non_loadable_session_id = open_idle_thread_with_non_loadable_connection(
5191            &panel,
5192            &non_loadable_connection,
5193            &mut cx,
5194        );
5195
5196        let loadable_connection = StubAgentConnection::new()
5197            .with_supports_load_session(true)
5198            .with_agent_id("loadable-stub".into())
5199            .with_telemetry_id("loadable-stub".into());
5200        let mut loadable_session_ids = Vec::new();
5201
5202        for _ in 0..7 {
5203            loadable_session_ids.push(open_generating_thread_with_loadable_connection(
5204                &panel,
5205                &loadable_connection,
5206                &mut cx,
5207            ));
5208        }
5209
5210        let base_time = Instant::now();
5211
5212        for session_id in loadable_session_ids.iter().take(6) {
5213            loadable_connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5214        }
5215        cx.run_until_parked();
5216
5217        panel.update(&mut cx, |panel, cx| {
5218            for (index, session_id) in loadable_session_ids.iter().take(6).enumerate() {
5219                let conversation_view = panel
5220                    .background_threads
5221                    .get(session_id)
5222                    .expect("background thread should exist")
5223                    .clone();
5224                conversation_view.update(cx, |view, cx| {
5225                    view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5226                });
5227            }
5228            panel.cleanup_background_threads(cx);
5229        });
5230
5231        panel.read_with(&cx, |panel, _cx| {
5232            assert_eq!(
5233                panel.background_threads.len(),
5234                6,
5235                "cleanup should keep the non-loadable idle thread in addition to five loadable ones"
5236            );
5237            assert!(
5238                panel
5239                    .background_threads
5240                    .contains_key(&non_loadable_session_id),
5241                "idle non-loadable background threads should not be cleanup candidates"
5242            );
5243            assert!(
5244                !panel
5245                    .background_threads
5246                    .contains_key(&loadable_session_ids[0]),
5247                "oldest idle loadable background thread should still be removed"
5248            );
5249            for session_id in &loadable_session_ids[1..6] {
5250                assert!(
5251                    panel.background_threads.contains_key(session_id),
5252                    "more recent idle loadable background threads should be retained"
5253                );
5254            }
5255            assert!(
5256                !panel
5257                    .background_threads
5258                    .contains_key(&loadable_session_ids[6]),
5259                "the active loadable thread should not also be stored as a background thread"
5260            );
5261        });
5262    }
5263
5264    #[gpui::test]
5265    async fn test_thread_target_local_project(cx: &mut TestAppContext) {
5266        init_test(cx);
5267        cx.update(|cx| {
5268            cx.update_flags(true, vec!["agent-v2".to_string()]);
5269            agent::ThreadStore::init_global(cx);
5270            language_model::LanguageModelRegistry::test(cx);
5271        });
5272
5273        let fs = FakeFs::new(cx.executor());
5274        fs.insert_tree(
5275            "/project",
5276            json!({
5277                ".git": {},
5278                "src": {
5279                    "main.rs": "fn main() {}"
5280                }
5281            }),
5282        )
5283        .await;
5284        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5285
5286        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5287
5288        let multi_workspace =
5289            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5290
5291        let workspace = multi_workspace
5292            .read_with(cx, |multi_workspace, _cx| {
5293                multi_workspace.workspace().clone()
5294            })
5295            .unwrap();
5296
5297        workspace.update(cx, |workspace, _cx| {
5298            workspace.set_random_database_id();
5299        });
5300
5301        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5302
5303        // Wait for the project to discover the git repository.
5304        cx.run_until_parked();
5305
5306        let panel = workspace.update_in(cx, |workspace, window, cx| {
5307            let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));
5308            workspace.add_panel(panel.clone(), window, cx);
5309            panel
5310        });
5311
5312        cx.run_until_parked();
5313
5314        // Default thread target should be LocalProject.
5315        panel.read_with(cx, |panel, _cx| {
5316            assert_eq!(
5317                *panel.start_thread_in(),
5318                StartThreadIn::LocalProject,
5319                "default thread target should be LocalProject"
5320            );
5321        });
5322
5323        // Start a new thread with the default LocalProject target.
5324        // Use StubAgentServer so the thread connects immediately in tests.
5325        panel.update_in(cx, |panel, window, cx| {
5326            panel.open_external_thread_with_server(
5327                Rc::new(StubAgentServer::default_response()),
5328                window,
5329                cx,
5330            );
5331        });
5332
5333        cx.run_until_parked();
5334
5335        // MultiWorkspace should still have exactly one workspace (no worktree created).
5336        multi_workspace
5337            .read_with(cx, |multi_workspace, _cx| {
5338                assert_eq!(
5339                    multi_workspace.workspaces().count(),
5340                    1,
5341                    "LocalProject should not create a new workspace"
5342                );
5343            })
5344            .unwrap();
5345
5346        // The thread should be active in the panel.
5347        panel.read_with(cx, |panel, cx| {
5348            assert!(
5349                panel.active_agent_thread(cx).is_some(),
5350                "a thread should be running in the current workspace"
5351            );
5352        });
5353
5354        // The thread target should still be LocalProject (unchanged).
5355        panel.read_with(cx, |panel, _cx| {
5356            assert_eq!(
5357                *panel.start_thread_in(),
5358                StartThreadIn::LocalProject,
5359                "thread target should remain LocalProject"
5360            );
5361        });
5362
5363        // No worktree creation status should be set.
5364        panel.read_with(cx, |panel, _cx| {
5365            assert!(
5366                panel.worktree_creation_status.is_none(),
5367                "no worktree creation should have occurred"
5368            );
5369        });
5370    }
5371
5372    #[gpui::test]
5373    async fn test_thread_target_serialization_round_trip(cx: &mut TestAppContext) {
5374        init_test(cx);
5375        cx.update(|cx| {
5376            cx.update_flags(true, vec!["agent-v2".to_string()]);
5377            agent::ThreadStore::init_global(cx);
5378            language_model::LanguageModelRegistry::test(cx);
5379        });
5380
5381        let fs = FakeFs::new(cx.executor());
5382        fs.insert_tree(
5383            "/project",
5384            json!({
5385                ".git": {},
5386                "src": {
5387                    "main.rs": "fn main() {}"
5388                }
5389            }),
5390        )
5391        .await;
5392        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5393
5394        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5395
5396        let multi_workspace =
5397            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5398
5399        let workspace = multi_workspace
5400            .read_with(cx, |multi_workspace, _cx| {
5401                multi_workspace.workspace().clone()
5402            })
5403            .unwrap();
5404
5405        workspace.update(cx, |workspace, _cx| {
5406            workspace.set_random_database_id();
5407        });
5408
5409        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5410
5411        // Wait for the project to discover the git repository.
5412        cx.run_until_parked();
5413
5414        let panel = workspace.update_in(cx, |workspace, window, cx| {
5415            let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));
5416            workspace.add_panel(panel.clone(), window, cx);
5417            panel
5418        });
5419
5420        cx.run_until_parked();
5421
5422        // Default should be LocalProject.
5423        panel.read_with(cx, |panel, _cx| {
5424            assert_eq!(*panel.start_thread_in(), StartThreadIn::LocalProject);
5425        });
5426
5427        // Change thread target to NewWorktree.
5428        panel.update_in(cx, |panel, window, cx| {
5429            panel.set_start_thread_in(
5430                &StartThreadIn::NewWorktree {
5431                    worktree_name: None,
5432                    branch_target: NewWorktreeBranchTarget::default(),
5433                },
5434                window,
5435                cx,
5436            );
5437        });
5438
5439        panel.read_with(cx, |panel, _cx| {
5440            assert_eq!(
5441                *panel.start_thread_in(),
5442                StartThreadIn::NewWorktree {
5443                    worktree_name: None,
5444                    branch_target: NewWorktreeBranchTarget::default(),
5445                },
5446                "thread target should be NewWorktree after set_thread_target"
5447            );
5448        });
5449
5450        // Let serialization complete.
5451        cx.run_until_parked();
5452
5453        // Load a fresh panel from the serialized data.
5454        let async_cx = cx.update(|window, cx| window.to_async(cx));
5455        let loaded_panel = AgentPanel::load(workspace.downgrade(), async_cx)
5456            .await
5457            .expect("panel load should succeed");
5458        cx.run_until_parked();
5459
5460        loaded_panel.read_with(cx, |panel, _cx| {
5461            assert_eq!(
5462                *panel.start_thread_in(),
5463                StartThreadIn::NewWorktree {
5464                    worktree_name: None,
5465                    branch_target: NewWorktreeBranchTarget::default(),
5466                },
5467                "thread target should survive serialization round-trip"
5468            );
5469        });
5470    }
5471
5472    #[gpui::test]
5473    async fn test_set_active_blocked_during_worktree_creation(cx: &mut TestAppContext) {
5474        init_test(cx);
5475
5476        let fs = FakeFs::new(cx.executor());
5477        cx.update(|cx| {
5478            cx.update_flags(true, vec!["agent-v2".to_string()]);
5479            agent::ThreadStore::init_global(cx);
5480            language_model::LanguageModelRegistry::test(cx);
5481            <dyn fs::Fs>::set_global(fs.clone(), cx);
5482        });
5483
5484        fs.insert_tree(
5485            "/project",
5486            json!({
5487                ".git": {},
5488                "src": {
5489                    "main.rs": "fn main() {}"
5490                }
5491            }),
5492        )
5493        .await;
5494
5495        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5496
5497        let multi_workspace =
5498            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5499
5500        let workspace = multi_workspace
5501            .read_with(cx, |multi_workspace, _cx| {
5502                multi_workspace.workspace().clone()
5503            })
5504            .unwrap();
5505
5506        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5507
5508        let panel = workspace.update_in(cx, |workspace, window, cx| {
5509            let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));
5510            workspace.add_panel(panel.clone(), window, cx);
5511            panel
5512        });
5513
5514        cx.run_until_parked();
5515
5516        // Simulate worktree creation in progress and reset to Uninitialized
5517        panel.update_in(cx, |panel, window, cx| {
5518            panel.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
5519            panel.active_view = ActiveView::Uninitialized;
5520            Panel::set_active(panel, true, window, cx);
5521            assert!(
5522                matches!(panel.active_view, ActiveView::Uninitialized),
5523                "set_active should not create a thread while worktree is being created"
5524            );
5525        });
5526
5527        // Clear the creation status and use open_external_thread_with_server
5528        // (which bypasses new_agent_thread) to verify the panel can transition
5529        // out of Uninitialized. We can't call set_active directly because
5530        // new_agent_thread requires full agent server infrastructure.
5531        panel.update_in(cx, |panel, window, cx| {
5532            panel.worktree_creation_status = None;
5533            panel.active_view = ActiveView::Uninitialized;
5534            panel.open_external_thread_with_server(
5535                Rc::new(StubAgentServer::default_response()),
5536                window,
5537                cx,
5538            );
5539        });
5540
5541        cx.run_until_parked();
5542
5543        panel.read_with(cx, |panel, _cx| {
5544            assert!(
5545                !matches!(panel.active_view, ActiveView::Uninitialized),
5546                "panel should transition out of Uninitialized once worktree creation is cleared"
5547            );
5548        });
5549    }
5550
5551    #[test]
5552    fn test_deserialize_agent_variants() {
5553        // PascalCase (legacy AgentType format, persisted in panel state)
5554        assert_eq!(
5555            serde_json::from_str::<Agent>(r#""NativeAgent""#).unwrap(),
5556            Agent::NativeAgent,
5557        );
5558        assert_eq!(
5559            serde_json::from_str::<Agent>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
5560            Agent::Custom {
5561                id: "my-agent".into(),
5562            },
5563        );
5564
5565        // Legacy TextThread variant deserializes to NativeAgent
5566        assert_eq!(
5567            serde_json::from_str::<Agent>(r#""TextThread""#).unwrap(),
5568            Agent::NativeAgent,
5569        );
5570
5571        // snake_case (canonical format)
5572        assert_eq!(
5573            serde_json::from_str::<Agent>(r#""native_agent""#).unwrap(),
5574            Agent::NativeAgent,
5575        );
5576        assert_eq!(
5577            serde_json::from_str::<Agent>(r#"{"custom":{"name":"my-agent"}}"#).unwrap(),
5578            Agent::Custom {
5579                id: "my-agent".into(),
5580            },
5581        );
5582
5583        // Serialization uses snake_case
5584        assert_eq!(
5585            serde_json::to_string(&Agent::NativeAgent).unwrap(),
5586            r#""native_agent""#,
5587        );
5588        assert_eq!(
5589            serde_json::to_string(&Agent::Custom {
5590                id: "my-agent".into()
5591            })
5592            .unwrap(),
5593            r#"{"custom":{"name":"my-agent"}}"#,
5594        );
5595    }
5596
5597    #[test]
5598    fn test_resolve_worktree_branch_target() {
5599        let existing_branches = HashSet::from_iter([
5600            "main".to_string(),
5601            "feature".to_string(),
5602            "origin/main".to_string(),
5603        ]);
5604
5605        let resolved = AgentPanel::resolve_worktree_branch_target(
5606            &NewWorktreeBranchTarget::CreateBranch {
5607                name: "new-branch".to_string(),
5608                from_ref: Some("main".to_string()),
5609            },
5610            &existing_branches,
5611            &HashSet::from_iter(["main".to_string()]),
5612        )
5613        .unwrap();
5614        assert_eq!(
5615            resolved,
5616            ("new-branch".to_string(), false, Some("main".to_string()))
5617        );
5618
5619        let resolved = AgentPanel::resolve_worktree_branch_target(
5620            &NewWorktreeBranchTarget::ExistingBranch {
5621                name: "feature".to_string(),
5622            },
5623            &existing_branches,
5624            &HashSet::default(),
5625        )
5626        .unwrap();
5627        assert_eq!(resolved, ("feature".to_string(), true, None));
5628
5629        let resolved = AgentPanel::resolve_worktree_branch_target(
5630            &NewWorktreeBranchTarget::ExistingBranch {
5631                name: "main".to_string(),
5632            },
5633            &existing_branches,
5634            &HashSet::from_iter(["main".to_string()]),
5635        )
5636        .unwrap();
5637        assert_eq!(resolved.1, false);
5638        assert_eq!(resolved.2, Some("main".to_string()));
5639        assert_ne!(resolved.0, "main");
5640        assert!(existing_branches.contains("main"));
5641        assert!(!existing_branches.contains(&resolved.0));
5642    }
5643
5644    #[gpui::test]
5645    async fn test_worktree_creation_preserves_selected_agent(cx: &mut TestAppContext) {
5646        init_test(cx);
5647
5648        let app_state = cx.update(|cx| {
5649            cx.update_flags(true, vec!["agent-v2".to_string()]);
5650            agent::ThreadStore::init_global(cx);
5651            language_model::LanguageModelRegistry::test(cx);
5652
5653            let app_state = workspace::AppState::test(cx);
5654            workspace::init(app_state.clone(), cx);
5655            app_state
5656        });
5657
5658        let fs = app_state.fs.as_fake();
5659        fs.insert_tree(
5660            "/project",
5661            json!({
5662                ".git": {},
5663                "src": {
5664                    "main.rs": "fn main() {}"
5665                }
5666            }),
5667        )
5668        .await;
5669        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5670
5671        let project = Project::test(app_state.fs.clone(), [Path::new("/project")], cx).await;
5672
5673        let multi_workspace =
5674            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5675        multi_workspace
5676            .update(cx, |multi_workspace, _, cx| {
5677                multi_workspace.open_sidebar(cx);
5678            })
5679            .unwrap();
5680
5681        let workspace = multi_workspace
5682            .read_with(cx, |multi_workspace, _cx| {
5683                multi_workspace.workspace().clone()
5684            })
5685            .unwrap();
5686
5687        workspace.update(cx, |workspace, _cx| {
5688            workspace.set_random_database_id();
5689        });
5690
5691        // Register a callback so new workspaces also get an AgentPanel.
5692        cx.update(|cx| {
5693            cx.observe_new(
5694                |workspace: &mut Workspace,
5695                 window: Option<&mut Window>,
5696                 cx: &mut Context<Workspace>| {
5697                    if let Some(window) = window {
5698                        let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));
5699                        workspace.add_panel(panel, window, cx);
5700                    }
5701                },
5702            )
5703            .detach();
5704        });
5705
5706        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5707
5708        // Wait for the project to discover the git repository.
5709        cx.run_until_parked();
5710
5711        let panel = workspace.update_in(cx, |workspace, window, cx| {
5712            let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));
5713            workspace.add_panel(panel.clone(), window, cx);
5714            panel
5715        });
5716
5717        cx.run_until_parked();
5718
5719        // Open a thread (needed so there's an active thread view).
5720        panel.update_in(cx, |panel, window, cx| {
5721            panel.open_external_thread_with_server(
5722                Rc::new(StubAgentServer::default_response()),
5723                window,
5724                cx,
5725            );
5726        });
5727
5728        cx.run_until_parked();
5729
5730        // Set the selected agent to Codex (a custom agent) and start_thread_in
5731        // to NewWorktree. We do this AFTER opening the thread because
5732        // open_external_thread_with_server overrides selected_agent.
5733        panel.update_in(cx, |panel, window, cx| {
5734            panel.selected_agent = Agent::Custom {
5735                id: CODEX_ID.into(),
5736            };
5737            panel.set_start_thread_in(
5738                &StartThreadIn::NewWorktree {
5739                    worktree_name: None,
5740                    branch_target: NewWorktreeBranchTarget::default(),
5741                },
5742                window,
5743                cx,
5744            );
5745        });
5746
5747        // Verify the panel has the Codex agent selected.
5748        panel.read_with(cx, |panel, _cx| {
5749            assert_eq!(
5750                panel.selected_agent,
5751                Agent::Custom {
5752                    id: CODEX_ID.into()
5753                },
5754            );
5755        });
5756
5757        // Directly call handle_worktree_creation_requested, which is what
5758        // handle_first_send_requested does when start_thread_in == NewWorktree.
5759        let content = vec![acp::ContentBlock::Text(acp::TextContent::new(
5760            "Hello from test",
5761        ))];
5762        panel.update_in(cx, |panel, window, cx| {
5763            panel.handle_worktree_requested(
5764                content,
5765                WorktreeCreationArgs::New {
5766                    worktree_name: None,
5767                    branch_target: NewWorktreeBranchTarget::default(),
5768                },
5769                window,
5770                cx,
5771            );
5772        });
5773
5774        // Let the async worktree creation + workspace setup complete.
5775        cx.run_until_parked();
5776
5777        // Find the new workspace's AgentPanel and verify it used the Codex agent.
5778        let found_codex = multi_workspace
5779            .read_with(cx, |multi_workspace, cx| {
5780                // There should be more than one workspace now (the original + the new worktree).
5781                assert!(
5782                    multi_workspace.workspaces().count() > 1,
5783                    "expected a new workspace to have been created, found {}",
5784                    multi_workspace.workspaces().count(),
5785                );
5786
5787                // Check the newest workspace's panel for the correct agent.
5788                let new_workspace = multi_workspace
5789                    .workspaces()
5790                    .find(|ws| ws.entity_id() != workspace.entity_id())
5791                    .expect("should find the new workspace");
5792                let new_panel = new_workspace
5793                    .read(cx)
5794                    .panel::<AgentPanel>(cx)
5795                    .expect("new workspace should have an AgentPanel");
5796
5797                new_panel.read(cx).selected_agent.clone()
5798            })
5799            .unwrap();
5800
5801        assert_eq!(
5802            found_codex,
5803            Agent::Custom {
5804                id: CODEX_ID.into()
5805            },
5806            "the new worktree workspace should use the same agent (Codex) that was selected in the original panel",
5807        );
5808    }
5809
5810    #[gpui::test]
5811    async fn test_work_dirs_update_when_worktrees_change(cx: &mut TestAppContext) {
5812        use crate::thread_metadata_store::ThreadMetadataStore;
5813
5814        init_test(cx);
5815        cx.update(|cx| {
5816            cx.update_flags(true, vec!["agent-v2".to_string()]);
5817            agent::ThreadStore::init_global(cx);
5818            language_model::LanguageModelRegistry::test(cx);
5819        });
5820
5821        // Set up a project with one worktree.
5822        let fs = FakeFs::new(cx.executor());
5823        fs.insert_tree("/project_a", json!({ "file.txt": "" }))
5824            .await;
5825        let project = Project::test(fs.clone(), [Path::new("/project_a")], cx).await;
5826
5827        let multi_workspace =
5828            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5829        let workspace = multi_workspace
5830            .read_with(cx, |mw, _cx| mw.workspace().clone())
5831            .unwrap();
5832        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
5833
5834        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
5835            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
5836        });
5837
5838        // Open thread A and send a message. With empty next_prompt_updates it
5839        // stays generating, so opening B will move A to background_threads.
5840        let connection_a = StubAgentConnection::new().with_agent_id("agent-a".into());
5841        open_thread_with_custom_connection(&panel, connection_a.clone(), &mut cx);
5842        send_message(&panel, &mut cx);
5843        let session_id_a = active_session_id(&panel, &cx);
5844
5845        // Open thread C — thread A (generating) moves to background.
5846        // Thread C completes immediately (idle), then opening B moves C to background too.
5847        let connection_c = StubAgentConnection::new().with_agent_id("agent-c".into());
5848        connection_c.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5849            acp::ContentChunk::new("done".into()),
5850        )]);
5851        open_thread_with_custom_connection(&panel, connection_c.clone(), &mut cx);
5852        send_message(&panel, &mut cx);
5853        let session_id_c = active_session_id(&panel, &cx);
5854
5855        // Open thread B — thread C (idle, non-loadable) is retained in background.
5856        let connection_b = StubAgentConnection::new().with_agent_id("agent-b".into());
5857        open_thread_with_custom_connection(&panel, connection_b.clone(), &mut cx);
5858        send_message(&panel, &mut cx);
5859        let session_id_b = active_session_id(&panel, &cx);
5860
5861        let metadata_store = cx.update(|_, cx| ThreadMetadataStore::global(cx));
5862
5863        panel.read_with(&cx, |panel, _cx| {
5864            assert!(
5865                panel.background_threads.contains_key(&session_id_a),
5866                "Thread A should be in background_threads"
5867            );
5868            assert!(
5869                panel.background_threads.contains_key(&session_id_c),
5870                "Thread C should be in background_threads"
5871            );
5872        });
5873
5874        // Verify initial work_dirs for thread B contain only /project_a.
5875        let initial_b_paths = panel.read_with(&cx, |panel, cx| {
5876            let thread = panel.active_agent_thread(cx).unwrap();
5877            thread.read(cx).work_dirs().cloned().unwrap()
5878        });
5879        assert_eq!(
5880            initial_b_paths.ordered_paths().collect::<Vec<_>>(),
5881            vec![&PathBuf::from("/project_a")],
5882            "Thread B should initially have only /project_a"
5883        );
5884
5885        // Now add a second worktree to the project.
5886        fs.insert_tree("/project_b", json!({ "other.txt": "" }))
5887            .await;
5888        let (new_tree, _) = project
5889            .update(&mut cx, |project, cx| {
5890                project.find_or_create_worktree("/project_b", true, cx)
5891            })
5892            .await
5893            .unwrap();
5894        cx.read(|cx| new_tree.read(cx).as_local().unwrap().scan_complete())
5895            .await;
5896        cx.run_until_parked();
5897
5898        // Verify thread B's (active) work_dirs now include both worktrees.
5899        let updated_b_paths = panel.read_with(&cx, |panel, cx| {
5900            let thread = panel.active_agent_thread(cx).unwrap();
5901            thread.read(cx).work_dirs().cloned().unwrap()
5902        });
5903        let mut b_paths_sorted = updated_b_paths.ordered_paths().cloned().collect::<Vec<_>>();
5904        b_paths_sorted.sort();
5905        assert_eq!(
5906            b_paths_sorted,
5907            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
5908            "Thread B work_dirs should include both worktrees after adding /project_b"
5909        );
5910
5911        // Verify thread A's (background) work_dirs are also updated.
5912        let updated_a_paths = panel.read_with(&cx, |panel, cx| {
5913            let bg_view = panel.background_threads.get(&session_id_a).unwrap();
5914            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
5915            root_thread
5916                .read(cx)
5917                .thread
5918                .read(cx)
5919                .work_dirs()
5920                .cloned()
5921                .unwrap()
5922        });
5923        let mut a_paths_sorted = updated_a_paths.ordered_paths().cloned().collect::<Vec<_>>();
5924        a_paths_sorted.sort();
5925        assert_eq!(
5926            a_paths_sorted,
5927            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
5928            "Thread A work_dirs should include both worktrees after adding /project_b"
5929        );
5930
5931        // Verify thread idle C was also updated.
5932        let updated_c_paths = panel.read_with(&cx, |panel, cx| {
5933            let bg_view = panel.background_threads.get(&session_id_c).unwrap();
5934            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
5935            root_thread
5936                .read(cx)
5937                .thread
5938                .read(cx)
5939                .work_dirs()
5940                .cloned()
5941                .unwrap()
5942        });
5943        let mut c_paths_sorted = updated_c_paths.ordered_paths().cloned().collect::<Vec<_>>();
5944        c_paths_sorted.sort();
5945        assert_eq!(
5946            c_paths_sorted,
5947            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
5948            "Thread C (idle background) work_dirs should include both worktrees after adding /project_b"
5949        );
5950
5951        // Verify the metadata store reflects the new paths for running threads only.
5952        cx.run_until_parked();
5953        for (label, session_id) in [("thread B", &session_id_b), ("thread A", &session_id_a)] {
5954            let metadata_paths = metadata_store.read_with(&cx, |store, _cx| {
5955                let metadata = store
5956                    .entry(session_id)
5957                    .unwrap_or_else(|| panic!("{label} thread metadata should exist"));
5958                metadata.folder_paths.clone()
5959            });
5960            let mut sorted = metadata_paths.ordered_paths().cloned().collect::<Vec<_>>();
5961            sorted.sort();
5962            assert_eq!(
5963                sorted,
5964                vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
5965                "{label} thread metadata folder_paths should include both worktrees"
5966            );
5967        }
5968
5969        // Now remove a worktree and verify work_dirs shrink.
5970        let worktree_b_id = new_tree.read_with(&cx, |tree, _| tree.id());
5971        project.update(&mut cx, |project, cx| {
5972            project.remove_worktree(worktree_b_id, cx);
5973        });
5974        cx.run_until_parked();
5975
5976        let after_remove_b = panel.read_with(&cx, |panel, cx| {
5977            let thread = panel.active_agent_thread(cx).unwrap();
5978            thread.read(cx).work_dirs().cloned().unwrap()
5979        });
5980        assert_eq!(
5981            after_remove_b.ordered_paths().collect::<Vec<_>>(),
5982            vec![&PathBuf::from("/project_a")],
5983            "Thread B work_dirs should revert to only /project_a after removing /project_b"
5984        );
5985
5986        let after_remove_a = panel.read_with(&cx, |panel, cx| {
5987            let bg_view = panel.background_threads.get(&session_id_a).unwrap();
5988            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
5989            root_thread
5990                .read(cx)
5991                .thread
5992                .read(cx)
5993                .work_dirs()
5994                .cloned()
5995                .unwrap()
5996        });
5997        assert_eq!(
5998            after_remove_a.ordered_paths().collect::<Vec<_>>(),
5999            vec![&PathBuf::from("/project_a")],
6000            "Thread A work_dirs should revert to only /project_a after removing /project_b"
6001        );
6002    }
6003
6004    #[gpui::test]
6005    async fn test_new_workspace_inherits_global_last_used_agent(cx: &mut TestAppContext) {
6006        init_test(cx);
6007        cx.update(|cx| {
6008            cx.update_flags(true, vec!["agent-v2".to_string()]);
6009            agent::ThreadStore::init_global(cx);
6010            language_model::LanguageModelRegistry::test(cx);
6011            // Use an isolated DB so parallel tests can't overwrite our global key.
6012            cx.set_global(db::AppDatabase::test_new());
6013        });
6014
6015        let custom_agent = Agent::Custom {
6016            id: "my-preferred-agent".into(),
6017        };
6018
6019        // Write a known agent to the global KVP to simulate a user who has
6020        // previously used this agent in another workspace.
6021        let kvp = cx.update(|cx| KeyValueStore::global(cx));
6022        write_global_last_used_agent(kvp, custom_agent.clone()).await;
6023
6024        let fs = FakeFs::new(cx.executor());
6025        let project = Project::test(fs.clone(), [], cx).await;
6026
6027        let multi_workspace =
6028            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6029
6030        let workspace = multi_workspace
6031            .read_with(cx, |multi_workspace, _cx| {
6032                multi_workspace.workspace().clone()
6033            })
6034            .unwrap();
6035
6036        workspace.update(cx, |workspace, _cx| {
6037            workspace.set_random_database_id();
6038        });
6039
6040        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6041
6042        // Load the panel via `load()`, which reads the global fallback
6043        // asynchronously when no per-workspace state exists.
6044        let async_cx = cx.update(|window, cx| window.to_async(cx));
6045        let panel = AgentPanel::load(workspace.downgrade(), async_cx)
6046            .await
6047            .expect("panel load should succeed");
6048        cx.run_until_parked();
6049
6050        panel.read_with(cx, |panel, _cx| {
6051            assert_eq!(
6052                panel.selected_agent, custom_agent,
6053                "new workspace should inherit the global last-used agent"
6054            );
6055        });
6056    }
6057
6058    #[gpui::test]
6059    async fn test_workspaces_maintain_independent_agent_selection(cx: &mut TestAppContext) {
6060        init_test(cx);
6061        cx.update(|cx| {
6062            cx.update_flags(true, vec!["agent-v2".to_string()]);
6063            agent::ThreadStore::init_global(cx);
6064            language_model::LanguageModelRegistry::test(cx);
6065        });
6066
6067        let fs = FakeFs::new(cx.executor());
6068        let project_a = Project::test(fs.clone(), [], cx).await;
6069        let project_b = Project::test(fs, [], cx).await;
6070
6071        let multi_workspace =
6072            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
6073
6074        let workspace_a = multi_workspace
6075            .read_with(cx, |multi_workspace, _cx| {
6076                multi_workspace.workspace().clone()
6077            })
6078            .unwrap();
6079
6080        let workspace_b = multi_workspace
6081            .update(cx, |multi_workspace, window, cx| {
6082                multi_workspace.test_add_workspace(project_b.clone(), window, cx)
6083            })
6084            .unwrap();
6085
6086        workspace_a.update(cx, |workspace, _cx| {
6087            workspace.set_random_database_id();
6088        });
6089        workspace_b.update(cx, |workspace, _cx| {
6090            workspace.set_random_database_id();
6091        });
6092
6093        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6094
6095        let agent_a = Agent::Custom {
6096            id: "agent-alpha".into(),
6097        };
6098        let agent_b = Agent::Custom {
6099            id: "agent-beta".into(),
6100        };
6101
6102        // Set up workspace A with agent_a
6103        let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
6104            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
6105        });
6106        panel_a.update(cx, |panel, _cx| {
6107            panel.selected_agent = agent_a.clone();
6108        });
6109
6110        // Set up workspace B with agent_b
6111        let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
6112            cx.new(|cx| AgentPanel::new(workspace, None, window, cx))
6113        });
6114        panel_b.update(cx, |panel, _cx| {
6115            panel.selected_agent = agent_b.clone();
6116        });
6117
6118        // Serialize both panels
6119        panel_a.update(cx, |panel, cx| panel.serialize(cx));
6120        panel_b.update(cx, |panel, cx| panel.serialize(cx));
6121        cx.run_until_parked();
6122
6123        // Load fresh panels from serialized state and verify independence
6124        let async_cx = cx.update(|window, cx| window.to_async(cx));
6125        let loaded_a = AgentPanel::load(workspace_a.downgrade(), async_cx)
6126            .await
6127            .expect("panel A load should succeed");
6128        cx.run_until_parked();
6129
6130        let async_cx = cx.update(|window, cx| window.to_async(cx));
6131        let loaded_b = AgentPanel::load(workspace_b.downgrade(), async_cx)
6132            .await
6133            .expect("panel B load should succeed");
6134        cx.run_until_parked();
6135
6136        loaded_a.read_with(cx, |panel, _cx| {
6137            assert_eq!(
6138                panel.selected_agent, agent_a,
6139                "workspace A should restore agent-alpha, not agent-beta"
6140            );
6141        });
6142
6143        loaded_b.read_with(cx, |panel, _cx| {
6144            assert_eq!(
6145                panel.selected_agent, agent_b,
6146                "workspace B should restore agent-beta, not agent-alpha"
6147            );
6148        });
6149    }
6150
6151    #[gpui::test]
6152    async fn test_new_thread_uses_workspace_selected_agent(cx: &mut TestAppContext) {
6153        init_test(cx);
6154        cx.update(|cx| {
6155            cx.update_flags(true, vec!["agent-v2".to_string()]);
6156            agent::ThreadStore::init_global(cx);
6157            language_model::LanguageModelRegistry::test(cx);
6158        });
6159
6160        let fs = FakeFs::new(cx.executor());
6161        let project = Project::test(fs.clone(), [], cx).await;
6162
6163        let multi_workspace =
6164            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6165
6166        let workspace = multi_workspace
6167            .read_with(cx, |multi_workspace, _cx| {
6168                multi_workspace.workspace().clone()
6169            })
6170            .unwrap();
6171
6172        workspace.update(cx, |workspace, _cx| {
6173            workspace.set_random_database_id();
6174        });
6175
6176        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6177
6178        let custom_agent = Agent::Custom {
6179            id: "my-custom-agent".into(),
6180        };
6181
6182        let panel = workspace.update_in(cx, |workspace, window, cx| {
6183            let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));
6184            workspace.add_panel(panel.clone(), window, cx);
6185            panel
6186        });
6187
6188        // Set selected_agent to a custom agent
6189        panel.update(cx, |panel, _cx| {
6190            panel.selected_agent = custom_agent.clone();
6191        });
6192
6193        // Call new_thread, which internally calls external_thread(None, ...)
6194        // This resolves the agent from self.selected_agent
6195        panel.update_in(cx, |panel, window, cx| {
6196            panel.new_thread(&NewThread, window, cx);
6197        });
6198
6199        panel.read_with(cx, |panel, _cx| {
6200            assert_eq!(
6201                panel.selected_agent, custom_agent,
6202                "selected_agent should remain the custom agent after new_thread"
6203            );
6204            assert!(
6205                panel.active_conversation_view().is_some(),
6206                "a thread should have been created"
6207            );
6208        });
6209    }
6210}