agent_panel.rs

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