agent_panel.rs

   1use std::{ops::Range, path::Path, rc::Rc, sync::Arc, time::Duration};
   2
   3use acp_thread::{AcpThread, AgentSessionInfo};
   4use agent::{ContextServerRegistry, ThreadStore};
   5use agent_servers::AgentServer;
   6use db::kvp::{Dismissable, KEY_VALUE_STORE};
   7use project::{
   8    ExternalAgentServerName,
   9    agent_server_store::{CLAUDE_CODE_NAME, CODEX_NAME, GEMINI_NAME},
  10};
  11use serde::{Deserialize, Serialize};
  12use settings::{
  13    DefaultAgentView as DefaultView, LanguageModelProviderSetting, LanguageModelSelection,
  14};
  15
  16use zed_actions::agent::{OpenClaudeCodeOnboardingModal, ReauthenticateAgent};
  17
  18use crate::ManageProfiles;
  19use crate::ui::{AcpOnboardingModal, ClaudeCodeOnboardingModal};
  20use crate::{
  21    AddContextServer, AgentDiffPane, Follow, InlineAssistant, NewTextThread, NewThread,
  22    OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,
  23    ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,
  24    acp::AcpThreadView,
  25    agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
  26    slash_command::SlashCommandCompletionProvider,
  27    text_thread_editor::{AgentPanelDelegate, TextThreadEditor, make_lsp_adapter_delegate},
  28    ui::{AgentOnboardingModal, EndTrialUpsell},
  29};
  30use crate::{
  31    ExpandMessageEditor,
  32    acp::{AcpThreadHistory, ThreadHistoryEvent},
  33    text_thread_history::{TextThreadHistory, TextThreadHistoryEvent},
  34};
  35use crate::{ExternalAgent, NewExternalAgentThread, NewNativeAgentThreadFromSummary};
  36use agent_settings::AgentSettings;
  37use ai_onboarding::AgentPanelOnboarding;
  38use anyhow::{Result, anyhow};
  39use assistant_slash_command::SlashCommandWorkingSet;
  40use assistant_text_thread::{TextThread, TextThreadEvent, TextThreadSummary};
  41use client::UserStore;
  42use cloud_llm_client::{Plan, PlanV2};
  43use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
  44use extension::ExtensionEvents;
  45use extension_host::ExtensionStore;
  46use fs::Fs;
  47use gpui::{
  48    Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext, Corner, DismissEvent,
  49    Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, KeyContext, Pixels, Subscription,
  50    Task, UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
  51};
  52use language::LanguageRegistry;
  53use language_model::{ConfigurationError, LanguageModelRegistry};
  54use project::{Project, ProjectPath, Worktree};
  55use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
  56use rules_library::{RulesLibrary, open_rules_library};
  57use search::{BufferSearchBar, buffer_search};
  58use settings::{Settings, update_settings_file};
  59use theme::ThemeSettings;
  60use ui::{
  61    Callout, ContextMenu, ContextMenuEntry, KeyBinding, PopoverMenu, PopoverMenuHandle, Tab,
  62    Tooltip, prelude::*, utils::WithRemSize,
  63};
  64use util::ResultExt as _;
  65use workspace::{
  66    CollaboratorId, DraggedSelection, DraggedTab, ToggleZoom, ToolbarItemView, Workspace,
  67    dock::{DockPosition, Panel, PanelEvent},
  68};
  69use zed_actions::{
  70    DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
  71    agent::{
  72        OpenAcpOnboardingModal, OpenOnboardingModal, OpenSettings, ResetAgentZoom, ResetOnboarding,
  73    },
  74    assistant::{OpenRulesLibrary, ToggleFocus},
  75};
  76
  77const AGENT_PANEL_KEY: &str = "agent_panel";
  78const RECENTLY_UPDATED_MENU_LIMIT: usize = 6;
  79const DEFAULT_THREAD_TITLE: &str = "New Thread";
  80
  81#[derive(Serialize, Deserialize, Debug)]
  82struct SerializedAgentPanel {
  83    width: Option<Pixels>,
  84    selected_agent: Option<AgentType>,
  85}
  86
  87pub fn init(cx: &mut App) {
  88    cx.observe_new(
  89        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
  90            workspace
  91                .register_action(|workspace, action: &NewThread, window, cx| {
  92                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
  93                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
  94                        workspace.focus_panel::<AgentPanel>(window, cx);
  95                    }
  96                })
  97                .register_action(
  98                    |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {
  99                        if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 100                            panel.update(cx, |panel, cx| {
 101                                panel.new_native_agent_thread_from_summary(action, window, cx)
 102                            });
 103                            workspace.focus_panel::<AgentPanel>(window, cx);
 104                        }
 105                    },
 106                )
 107                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
 108                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 109                        workspace.focus_panel::<AgentPanel>(window, cx);
 110                        panel.update(cx, |panel, cx| panel.expand_message_editor(window, cx));
 111                    }
 112                })
 113                .register_action(|workspace, _: &OpenHistory, window, cx| {
 114                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 115                        workspace.focus_panel::<AgentPanel>(window, cx);
 116                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
 117                    }
 118                })
 119                .register_action(|workspace, _: &OpenSettings, window, cx| {
 120                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 121                        workspace.focus_panel::<AgentPanel>(window, cx);
 122                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
 123                    }
 124                })
 125                .register_action(|workspace, _: &NewTextThread, window, cx| {
 126                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 127                        workspace.focus_panel::<AgentPanel>(window, cx);
 128                        panel.update(cx, |panel, cx| panel.new_text_thread(window, cx));
 129                    }
 130                })
 131                .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
 132                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 133                        workspace.focus_panel::<AgentPanel>(window, cx);
 134                        panel.update(cx, |panel, cx| {
 135                            panel.external_thread(action.agent.clone(), None, None, window, cx)
 136                        });
 137                    }
 138                })
 139                .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
 140                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 141                        workspace.focus_panel::<AgentPanel>(window, cx);
 142                        panel.update(cx, |panel, cx| {
 143                            panel.deploy_rules_library(action, window, cx)
 144                        });
 145                    }
 146                })
 147                .register_action(|workspace, _: &Follow, window, cx| {
 148                    workspace.follow(CollaboratorId::Agent, window, cx);
 149                })
 150                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
 151                    let thread = workspace
 152                        .panel::<AgentPanel>(cx)
 153                        .and_then(|panel| panel.read(cx).active_thread_view().cloned())
 154                        .and_then(|thread_view| thread_view.read(cx).thread().cloned());
 155
 156                    if let Some(thread) = thread {
 157                        AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
 158                    }
 159                })
 160                .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
 161                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 162                        workspace.focus_panel::<AgentPanel>(window, cx);
 163                        panel.update(cx, |panel, cx| {
 164                            panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
 165                        });
 166                    }
 167                })
 168                .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
 169                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 170                        workspace.focus_panel::<AgentPanel>(window, cx);
 171                        panel.update(cx, |panel, cx| {
 172                            panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
 173                        });
 174                    }
 175                })
 176                .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
 177                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 178                        workspace.focus_panel::<AgentPanel>(window, cx);
 179                        panel.update(cx, |panel, cx| {
 180                            panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
 181                        });
 182                    }
 183                })
 184                .register_action(|workspace, _: &OpenOnboardingModal, window, cx| {
 185                    AgentOnboardingModal::toggle(workspace, window, cx)
 186                })
 187                .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {
 188                    AcpOnboardingModal::toggle(workspace, window, cx)
 189                })
 190                .register_action(|workspace, _: &OpenClaudeCodeOnboardingModal, window, cx| {
 191                    ClaudeCodeOnboardingModal::toggle(workspace, window, cx)
 192                })
 193                .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
 194                    window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
 195                    window.refresh();
 196                })
 197                .register_action(|_workspace, _: &ResetTrialUpsell, _window, cx| {
 198                    OnboardingUpsell::set_dismissed(false, cx);
 199                })
 200                .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
 201                    TrialEndUpsell::set_dismissed(false, cx);
 202                })
 203                .register_action(|workspace, _: &ResetAgentZoom, window, cx| {
 204                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 205                        panel.update(cx, |panel, cx| {
 206                            panel.reset_agent_zoom(window, cx);
 207                        });
 208                    }
 209                });
 210        },
 211    )
 212    .detach();
 213}
 214
 215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 216enum HistoryKind {
 217    AgentThreads,
 218    TextThreads,
 219}
 220
 221enum ActiveView {
 222    ExternalAgentThread {
 223        thread_view: Entity<AcpThreadView>,
 224    },
 225    TextThread {
 226        text_thread_editor: Entity<TextThreadEditor>,
 227        title_editor: Entity<Editor>,
 228        buffer_search_bar: Entity<BufferSearchBar>,
 229        _subscriptions: Vec<gpui::Subscription>,
 230    },
 231    History {
 232        kind: HistoryKind,
 233    },
 234    Configuration,
 235}
 236
 237enum WhichFontSize {
 238    AgentFont,
 239    BufferFont,
 240    None,
 241}
 242
 243// TODO unify this with ExternalAgent
 244#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
 245pub enum AgentType {
 246    #[default]
 247    NativeAgent,
 248    TextThread,
 249    Gemini,
 250    ClaudeCode,
 251    Codex,
 252    Custom {
 253        name: SharedString,
 254    },
 255}
 256
 257impl AgentType {
 258    fn label(&self) -> SharedString {
 259        match self {
 260            Self::NativeAgent | Self::TextThread => "Zed Agent".into(),
 261            Self::Gemini => "Gemini CLI".into(),
 262            Self::ClaudeCode => "Claude Code".into(),
 263            Self::Codex => "Codex".into(),
 264            Self::Custom { name, .. } => name.into(),
 265        }
 266    }
 267
 268    fn icon(&self) -> Option<IconName> {
 269        match self {
 270            Self::NativeAgent | Self::TextThread => None,
 271            Self::Gemini => Some(IconName::AiGemini),
 272            Self::ClaudeCode => Some(IconName::AiClaude),
 273            Self::Codex => Some(IconName::AiOpenAi),
 274            Self::Custom { .. } => Some(IconName::Sparkle),
 275        }
 276    }
 277}
 278
 279impl From<ExternalAgent> for AgentType {
 280    fn from(value: ExternalAgent) -> Self {
 281        match value {
 282            ExternalAgent::Gemini => Self::Gemini,
 283            ExternalAgent::ClaudeCode => Self::ClaudeCode,
 284            ExternalAgent::Codex => Self::Codex,
 285            ExternalAgent::Custom { name } => Self::Custom { name },
 286            ExternalAgent::NativeAgent => Self::NativeAgent,
 287        }
 288    }
 289}
 290
 291impl ActiveView {
 292    pub fn which_font_size_used(&self) -> WhichFontSize {
 293        match self {
 294            ActiveView::ExternalAgentThread { .. } | ActiveView::History { .. } => {
 295                WhichFontSize::AgentFont
 296            }
 297            ActiveView::TextThread { .. } => WhichFontSize::BufferFont,
 298            ActiveView::Configuration => WhichFontSize::None,
 299        }
 300    }
 301
 302    fn native_agent(
 303        fs: Arc<dyn Fs>,
 304        prompt_store: Option<Entity<PromptStore>>,
 305        thread_store: Entity<ThreadStore>,
 306        project: Entity<Project>,
 307        workspace: WeakEntity<Workspace>,
 308        history: Entity<AcpThreadHistory>,
 309        window: &mut Window,
 310        cx: &mut App,
 311    ) -> Self {
 312        let thread_view = cx.new(|cx| {
 313            crate::acp::AcpThreadView::new(
 314                ExternalAgent::NativeAgent.server(fs, thread_store.clone()),
 315                None,
 316                None,
 317                workspace,
 318                project,
 319                Some(thread_store),
 320                prompt_store,
 321                history,
 322                false,
 323                window,
 324                cx,
 325            )
 326        });
 327
 328        Self::ExternalAgentThread { thread_view }
 329    }
 330
 331    pub fn text_thread(
 332        text_thread_editor: Entity<TextThreadEditor>,
 333        language_registry: Arc<LanguageRegistry>,
 334        window: &mut Window,
 335        cx: &mut App,
 336    ) -> Self {
 337        let title = text_thread_editor.read(cx).title(cx).to_string();
 338
 339        let editor = cx.new(|cx| {
 340            let mut editor = Editor::single_line(window, cx);
 341            editor.set_text(title, window, cx);
 342            editor
 343        });
 344
 345        // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
 346        // cause a custom summary to be set. The presence of this custom summary would cause
 347        // summarization to not happen.
 348        let mut suppress_first_edit = true;
 349
 350        let subscriptions = vec![
 351            window.subscribe(&editor, cx, {
 352                {
 353                    let text_thread_editor = text_thread_editor.clone();
 354                    move |editor, event, window, cx| match event {
 355                        EditorEvent::BufferEdited => {
 356                            if suppress_first_edit {
 357                                suppress_first_edit = false;
 358                                return;
 359                            }
 360                            let new_summary = editor.read(cx).text(cx);
 361
 362                            text_thread_editor.update(cx, |text_thread_editor, cx| {
 363                                text_thread_editor
 364                                    .text_thread()
 365                                    .update(cx, |text_thread, cx| {
 366                                        text_thread.set_custom_summary(new_summary, cx);
 367                                    })
 368                            })
 369                        }
 370                        EditorEvent::Blurred => {
 371                            if editor.read(cx).text(cx).is_empty() {
 372                                let summary = text_thread_editor
 373                                    .read(cx)
 374                                    .text_thread()
 375                                    .read(cx)
 376                                    .summary()
 377                                    .or_default();
 378
 379                                editor.update(cx, |editor, cx| {
 380                                    editor.set_text(summary, window, cx);
 381                                });
 382                            }
 383                        }
 384                        _ => {}
 385                    }
 386                }
 387            }),
 388            window.subscribe(&text_thread_editor.read(cx).text_thread().clone(), cx, {
 389                let editor = editor.clone();
 390                move |text_thread, event, window, cx| match event {
 391                    TextThreadEvent::SummaryGenerated => {
 392                        let summary = text_thread.read(cx).summary().or_default();
 393
 394                        editor.update(cx, |editor, cx| {
 395                            editor.set_text(summary, window, cx);
 396                        })
 397                    }
 398                    TextThreadEvent::PathChanged { .. } => {}
 399                    _ => {}
 400                }
 401            }),
 402        ];
 403
 404        let buffer_search_bar =
 405            cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
 406        buffer_search_bar.update(cx, |buffer_search_bar, cx| {
 407            buffer_search_bar.set_active_pane_item(Some(&text_thread_editor), window, cx)
 408        });
 409
 410        Self::TextThread {
 411            text_thread_editor,
 412            title_editor: editor,
 413            buffer_search_bar,
 414            _subscriptions: subscriptions,
 415        }
 416    }
 417}
 418
 419pub struct AgentPanel {
 420    workspace: WeakEntity<Workspace>,
 421    loading: bool,
 422    user_store: Entity<UserStore>,
 423    project: Entity<Project>,
 424    fs: Arc<dyn Fs>,
 425    language_registry: Arc<LanguageRegistry>,
 426    acp_history: Entity<AcpThreadHistory>,
 427    text_thread_history: Entity<TextThreadHistory>,
 428    thread_store: Entity<ThreadStore>,
 429    text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
 430    prompt_store: Option<Entity<PromptStore>>,
 431    context_server_registry: Entity<ContextServerRegistry>,
 432    configuration: Option<Entity<AgentConfiguration>>,
 433    configuration_subscription: Option<Subscription>,
 434    active_view: ActiveView,
 435    previous_view: Option<ActiveView>,
 436    new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
 437    agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
 438    agent_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
 439    agent_navigation_menu: Option<Entity<ContextMenu>>,
 440    _extension_subscription: Option<Subscription>,
 441    width: Option<Pixels>,
 442    height: Option<Pixels>,
 443    zoomed: bool,
 444    pending_serialization: Option<Task<Result<()>>>,
 445    onboarding: Entity<AgentPanelOnboarding>,
 446    selected_agent: AgentType,
 447    show_trust_workspace_message: bool,
 448}
 449
 450impl AgentPanel {
 451    fn serialize(&mut self, cx: &mut Context<Self>) {
 452        let width = self.width;
 453        let selected_agent = self.selected_agent.clone();
 454        self.pending_serialization = Some(cx.background_spawn(async move {
 455            KEY_VALUE_STORE
 456                .write_kvp(
 457                    AGENT_PANEL_KEY.into(),
 458                    serde_json::to_string(&SerializedAgentPanel {
 459                        width,
 460                        selected_agent: Some(selected_agent),
 461                    })?,
 462                )
 463                .await?;
 464            anyhow::Ok(())
 465        }));
 466    }
 467
 468    pub fn load(
 469        workspace: WeakEntity<Workspace>,
 470        prompt_builder: Arc<PromptBuilder>,
 471        mut cx: AsyncWindowContext,
 472    ) -> Task<Result<Entity<Self>>> {
 473        let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
 474        cx.spawn(async move |cx| {
 475            let prompt_store = match prompt_store {
 476                Ok(prompt_store) => prompt_store.await.ok(),
 477                Err(_) => None,
 478            };
 479            let serialized_panel = if let Some(panel) = cx
 480                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(AGENT_PANEL_KEY) })
 481                .await
 482                .log_err()
 483                .flatten()
 484            {
 485                serde_json::from_str::<SerializedAgentPanel>(&panel).log_err()
 486            } else {
 487                None
 488            };
 489
 490            let slash_commands = Arc::new(SlashCommandWorkingSet::default());
 491            let text_thread_store = workspace
 492                .update(cx, |workspace, cx| {
 493                    let project = workspace.project().clone();
 494                    assistant_text_thread::TextThreadStore::new(
 495                        project,
 496                        prompt_builder,
 497                        slash_commands,
 498                        cx,
 499                    )
 500                })?
 501                .await?;
 502
 503            let panel = workspace.update_in(cx, |workspace, window, cx| {
 504                let panel =
 505                    cx.new(|cx| Self::new(workspace, text_thread_store, prompt_store, window, cx));
 506
 507                panel.as_mut(cx).loading = true;
 508                if let Some(serialized_panel) = serialized_panel {
 509                    panel.update(cx, |panel, cx| {
 510                        panel.width = serialized_panel.width.map(|w| w.round());
 511                        if let Some(selected_agent) = serialized_panel.selected_agent {
 512                            panel.selected_agent = selected_agent.clone();
 513                            panel.new_agent_thread(selected_agent, window, cx);
 514                        }
 515                        cx.notify();
 516                    });
 517                } else {
 518                    panel.update(cx, |panel, cx| {
 519                        panel.new_agent_thread(AgentType::NativeAgent, window, cx);
 520                    });
 521                }
 522                panel.as_mut(cx).loading = false;
 523                panel
 524            })?;
 525
 526            Ok(panel)
 527        })
 528    }
 529
 530    fn new(
 531        workspace: &Workspace,
 532        text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
 533        prompt_store: Option<Entity<PromptStore>>,
 534        window: &mut Window,
 535        cx: &mut Context<Self>,
 536    ) -> Self {
 537        let fs = workspace.app_state().fs.clone();
 538        let user_store = workspace.app_state().user_store.clone();
 539        let project = workspace.project();
 540        let language_registry = project.read(cx).languages().clone();
 541        let client = workspace.client().clone();
 542        let workspace = workspace.weak_handle();
 543
 544        let context_server_registry =
 545            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 546
 547        let thread_store = cx.new(|cx| ThreadStore::new(cx));
 548        let acp_history = cx.new(|cx| AcpThreadHistory::new(None, window, cx));
 549        let text_thread_history =
 550            cx.new(|cx| TextThreadHistory::new(text_thread_store.clone(), window, cx));
 551        cx.subscribe_in(
 552            &acp_history,
 553            window,
 554            |this, _, event, window, cx| match event {
 555                ThreadHistoryEvent::Open(thread) => {
 556                    this.external_thread(
 557                        Some(crate::ExternalAgent::NativeAgent),
 558                        Some(thread.clone()),
 559                        None,
 560                        window,
 561                        cx,
 562                    );
 563                }
 564            },
 565        )
 566        .detach();
 567        cx.subscribe_in(
 568            &text_thread_history,
 569            window,
 570            |this, _, event, window, cx| match event {
 571                TextThreadHistoryEvent::Open(thread) => {
 572                    this.open_saved_text_thread(thread.path.clone(), window, cx)
 573                        .detach_and_log_err(cx);
 574                }
 575            },
 576        )
 577        .detach();
 578
 579        let panel_type = AgentSettings::get_global(cx).default_view;
 580        let active_view = match panel_type {
 581            DefaultView::Thread => ActiveView::native_agent(
 582                fs.clone(),
 583                prompt_store.clone(),
 584                thread_store.clone(),
 585                project.clone(),
 586                workspace.clone(),
 587                acp_history.clone(),
 588                window,
 589                cx,
 590            ),
 591            DefaultView::TextThread => {
 592                let context = text_thread_store.update(cx, |store, cx| store.create(cx));
 593                let lsp_adapter_delegate = make_lsp_adapter_delegate(&project.clone(), cx).unwrap();
 594                let text_thread_editor = cx.new(|cx| {
 595                    let mut editor = TextThreadEditor::for_text_thread(
 596                        context,
 597                        fs.clone(),
 598                        workspace.clone(),
 599                        project.clone(),
 600                        lsp_adapter_delegate,
 601                        window,
 602                        cx,
 603                    );
 604                    editor.insert_default_prompt(window, cx);
 605                    editor
 606                });
 607                ActiveView::text_thread(text_thread_editor, language_registry.clone(), window, cx)
 608            }
 609        };
 610
 611        let weak_panel = cx.entity().downgrade();
 612
 613        window.defer(cx, move |window, cx| {
 614            let panel = weak_panel.clone();
 615            let agent_navigation_menu =
 616                ContextMenu::build_persistent(window, cx, move |mut menu, _window, cx| {
 617                    if let Some(panel) = panel.upgrade() {
 618                        if let Some(kind) = panel.read(cx).history_kind_for_selected_agent(cx) {
 619                            menu =
 620                                Self::populate_recently_updated_menu_section(menu, panel, kind, cx);
 621                            menu = menu.action("View All", Box::new(OpenHistory));
 622                        }
 623                    }
 624
 625                    menu = menu
 626                        .fixed_width(px(320.).into())
 627                        .keep_open_on_confirm(false)
 628                        .key_context("NavigationMenu");
 629
 630                    menu
 631                });
 632            weak_panel
 633                .update(cx, |panel, cx| {
 634                    cx.subscribe_in(
 635                        &agent_navigation_menu,
 636                        window,
 637                        |_, menu, _: &DismissEvent, window, cx| {
 638                            menu.update(cx, |menu, _| {
 639                                menu.clear_selected();
 640                            });
 641                            cx.focus_self(window);
 642                        },
 643                    )
 644                    .detach();
 645                    panel.agent_navigation_menu = Some(agent_navigation_menu);
 646                })
 647                .ok();
 648        });
 649
 650        let onboarding = cx.new(|cx| {
 651            AgentPanelOnboarding::new(
 652                user_store.clone(),
 653                client,
 654                |_window, cx| {
 655                    OnboardingUpsell::set_dismissed(true, cx);
 656                },
 657                cx,
 658            )
 659        });
 660
 661        // Subscribe to extension events to sync agent servers when extensions change
 662        let extension_subscription = if let Some(extension_events) = ExtensionEvents::try_global(cx)
 663        {
 664            Some(
 665                cx.subscribe(&extension_events, |this, _source, event, cx| match event {
 666                    extension::Event::ExtensionInstalled(_)
 667                    | extension::Event::ExtensionUninstalled(_)
 668                    | extension::Event::ExtensionsInstalledChanged => {
 669                        this.sync_agent_servers_from_extensions(cx);
 670                    }
 671                    _ => {}
 672                }),
 673            )
 674        } else {
 675            None
 676        };
 677
 678        let mut panel = Self {
 679            active_view,
 680            workspace,
 681            user_store,
 682            project: project.clone(),
 683            fs: fs.clone(),
 684            language_registry,
 685            text_thread_store,
 686            prompt_store,
 687            configuration: None,
 688            configuration_subscription: None,
 689            context_server_registry,
 690            previous_view: None,
 691            new_thread_menu_handle: PopoverMenuHandle::default(),
 692            agent_panel_menu_handle: PopoverMenuHandle::default(),
 693            agent_navigation_menu_handle: PopoverMenuHandle::default(),
 694            agent_navigation_menu: None,
 695            _extension_subscription: extension_subscription,
 696            width: None,
 697            height: None,
 698            zoomed: false,
 699            pending_serialization: None,
 700            onboarding,
 701            acp_history,
 702            text_thread_history,
 703            thread_store,
 704            selected_agent: AgentType::default(),
 705            loading: false,
 706            show_trust_workspace_message: false,
 707        };
 708
 709        // Initial sync of agent servers from extensions
 710        panel.sync_agent_servers_from_extensions(cx);
 711        panel
 712    }
 713
 714    pub fn toggle_focus(
 715        workspace: &mut Workspace,
 716        _: &ToggleFocus,
 717        window: &mut Window,
 718        cx: &mut Context<Workspace>,
 719    ) {
 720        if workspace
 721            .panel::<Self>(cx)
 722            .is_some_and(|panel| panel.read(cx).enabled(cx))
 723        {
 724            workspace.toggle_panel_focus::<Self>(window, cx);
 725        }
 726    }
 727
 728    pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
 729        &self.prompt_store
 730    }
 731
 732    pub fn thread_store(&self) -> &Entity<ThreadStore> {
 733        &self.thread_store
 734    }
 735
 736    pub fn history(&self) -> &Entity<AcpThreadHistory> {
 737        &self.acp_history
 738    }
 739
 740    pub fn open_thread(
 741        &mut self,
 742        thread: AgentSessionInfo,
 743        window: &mut Window,
 744        cx: &mut Context<Self>,
 745    ) {
 746        self.external_thread(
 747            Some(crate::ExternalAgent::NativeAgent),
 748            Some(thread),
 749            None,
 750            window,
 751            cx,
 752        );
 753    }
 754
 755    pub(crate) fn context_server_registry(&self) -> &Entity<ContextServerRegistry> {
 756        &self.context_server_registry
 757    }
 758
 759    pub fn is_hidden(workspace: &Entity<Workspace>, cx: &App) -> bool {
 760        let workspace_read = workspace.read(cx);
 761
 762        workspace_read
 763            .panel::<AgentPanel>(cx)
 764            .map(|panel| {
 765                let panel_id = Entity::entity_id(&panel);
 766
 767                let is_visible = workspace_read.all_docks().iter().any(|dock| {
 768                    dock.read(cx)
 769                        .visible_panel()
 770                        .is_some_and(|visible_panel| visible_panel.panel_id() == panel_id)
 771                });
 772
 773                !is_visible
 774            })
 775            .unwrap_or(true)
 776    }
 777
 778    pub(crate) fn active_thread_view(&self) -> Option<&Entity<AcpThreadView>> {
 779        match &self.active_view {
 780            ActiveView::ExternalAgentThread { thread_view, .. } => Some(thread_view),
 781            ActiveView::TextThread { .. }
 782            | ActiveView::History { .. }
 783            | ActiveView::Configuration => None,
 784        }
 785    }
 786
 787    fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
 788        self.new_agent_thread(AgentType::NativeAgent, window, cx);
 789    }
 790
 791    fn new_native_agent_thread_from_summary(
 792        &mut self,
 793        action: &NewNativeAgentThreadFromSummary,
 794        window: &mut Window,
 795        cx: &mut Context<Self>,
 796    ) {
 797        let Some(thread) = self
 798            .acp_history
 799            .read(cx)
 800            .session_for_id(&action.from_session_id)
 801        else {
 802            return;
 803        };
 804
 805        self.external_thread(
 806            Some(ExternalAgent::NativeAgent),
 807            None,
 808            Some(thread),
 809            window,
 810            cx,
 811        );
 812    }
 813
 814    fn new_text_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 815        telemetry::event!("Agent Thread Started", agent = "zed-text");
 816
 817        let context = self
 818            .text_thread_store
 819            .update(cx, |context_store, cx| context_store.create(cx));
 820        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
 821            .log_err()
 822            .flatten();
 823
 824        let text_thread_editor = cx.new(|cx| {
 825            let mut editor = TextThreadEditor::for_text_thread(
 826                context,
 827                self.fs.clone(),
 828                self.workspace.clone(),
 829                self.project.clone(),
 830                lsp_adapter_delegate,
 831                window,
 832                cx,
 833            );
 834            editor.insert_default_prompt(window, cx);
 835            editor
 836        });
 837
 838        if self.selected_agent != AgentType::TextThread {
 839            self.selected_agent = AgentType::TextThread;
 840            self.serialize(cx);
 841        }
 842
 843        self.set_active_view(
 844            ActiveView::text_thread(
 845                text_thread_editor.clone(),
 846                self.language_registry.clone(),
 847                window,
 848                cx,
 849            ),
 850            true,
 851            window,
 852            cx,
 853        );
 854        text_thread_editor.focus_handle(cx).focus(window, cx);
 855    }
 856
 857    fn external_thread(
 858        &mut self,
 859        agent_choice: Option<crate::ExternalAgent>,
 860        resume_thread: Option<AgentSessionInfo>,
 861        summarize_thread: Option<AgentSessionInfo>,
 862        window: &mut Window,
 863        cx: &mut Context<Self>,
 864    ) {
 865        let workspace = self.workspace.clone();
 866        let project = self.project.clone();
 867        let fs = self.fs.clone();
 868        let is_via_collab = self.project.read(cx).is_via_collab();
 869
 870        const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
 871
 872        #[derive(Serialize, Deserialize)]
 873        struct LastUsedExternalAgent {
 874            agent: crate::ExternalAgent,
 875        }
 876
 877        let loading = self.loading;
 878        let thread_store = self.thread_store.clone();
 879
 880        cx.spawn_in(window, async move |this, cx| {
 881            let ext_agent = match agent_choice {
 882                Some(agent) => {
 883                    cx.background_spawn({
 884                        let agent = agent.clone();
 885                        async move {
 886                            if let Some(serialized) =
 887                                serde_json::to_string(&LastUsedExternalAgent { agent }).log_err()
 888                            {
 889                                KEY_VALUE_STORE
 890                                    .write_kvp(LAST_USED_EXTERNAL_AGENT_KEY.to_string(), serialized)
 891                                    .await
 892                                    .log_err();
 893                            }
 894                        }
 895                    })
 896                    .detach();
 897
 898                    agent
 899                }
 900                None => {
 901                    if is_via_collab {
 902                        ExternalAgent::NativeAgent
 903                    } else {
 904                        cx.background_spawn(async move {
 905                            KEY_VALUE_STORE.read_kvp(LAST_USED_EXTERNAL_AGENT_KEY)
 906                        })
 907                        .await
 908                        .log_err()
 909                        .flatten()
 910                        .and_then(|value| {
 911                            serde_json::from_str::<LastUsedExternalAgent>(&value).log_err()
 912                        })
 913                        .map(|agent| agent.agent)
 914                        .unwrap_or(ExternalAgent::NativeAgent)
 915                    }
 916                }
 917            };
 918
 919            let server = ext_agent.server(fs, thread_store);
 920            this.update_in(cx, |agent_panel, window, cx| {
 921                agent_panel._external_thread(
 922                    server,
 923                    resume_thread,
 924                    summarize_thread,
 925                    workspace,
 926                    project,
 927                    loading,
 928                    ext_agent,
 929                    window,
 930                    cx,
 931                );
 932            })?;
 933
 934            anyhow::Ok(())
 935        })
 936        .detach_and_log_err(cx);
 937    }
 938
 939    fn deploy_rules_library(
 940        &mut self,
 941        action: &OpenRulesLibrary,
 942        _window: &mut Window,
 943        cx: &mut Context<Self>,
 944    ) {
 945        open_rules_library(
 946            self.language_registry.clone(),
 947            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
 948            Rc::new(|| {
 949                Rc::new(SlashCommandCompletionProvider::new(
 950                    Arc::new(SlashCommandWorkingSet::default()),
 951                    None,
 952                    None,
 953                ))
 954            }),
 955            action
 956                .prompt_to_select
 957                .map(|uuid| UserPromptId(uuid).into()),
 958            cx,
 959        )
 960        .detach_and_log_err(cx);
 961    }
 962
 963    fn expand_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 964        if let Some(thread_view) = self.active_thread_view() {
 965            thread_view.update(cx, |view, cx| {
 966                view.expand_message_editor(&ExpandMessageEditor, window, cx);
 967                view.focus_handle(cx).focus(window, cx);
 968            });
 969        }
 970    }
 971
 972    fn history_kind_for_selected_agent(&self, cx: &App) -> Option<HistoryKind> {
 973        match self.selected_agent {
 974            AgentType::NativeAgent => Some(HistoryKind::AgentThreads),
 975            AgentType::TextThread => Some(HistoryKind::TextThreads),
 976            AgentType::Gemini
 977            | AgentType::ClaudeCode
 978            | AgentType::Codex
 979            | AgentType::Custom { .. } => {
 980                if self.acp_history.read(cx).has_session_list() {
 981                    Some(HistoryKind::AgentThreads)
 982                } else {
 983                    None
 984                }
 985            }
 986        }
 987    }
 988
 989    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 990        let Some(kind) = self.history_kind_for_selected_agent(cx) else {
 991            return;
 992        };
 993
 994        if let ActiveView::History { kind: active_kind } = self.active_view {
 995            if active_kind == kind {
 996                if let Some(previous_view) = self.previous_view.take() {
 997                    self.set_active_view(previous_view, true, window, cx);
 998                }
 999                return;
1000            }
1001        }
1002
1003        self.set_active_view(ActiveView::History { kind }, true, window, cx);
1004        cx.notify();
1005    }
1006
1007    pub(crate) fn open_saved_text_thread(
1008        &mut self,
1009        path: Arc<Path>,
1010        window: &mut Window,
1011        cx: &mut Context<Self>,
1012    ) -> Task<Result<()>> {
1013        let text_thread_task = self
1014            .text_thread_store
1015            .update(cx, |store, cx| store.open_local(path, cx));
1016        cx.spawn_in(window, async move |this, cx| {
1017            let text_thread = text_thread_task.await?;
1018            this.update_in(cx, |this, window, cx| {
1019                this.open_text_thread(text_thread, window, cx);
1020            })
1021        })
1022    }
1023
1024    pub(crate) fn open_text_thread(
1025        &mut self,
1026        text_thread: Entity<TextThread>,
1027        window: &mut Window,
1028        cx: &mut Context<Self>,
1029    ) {
1030        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
1031            .log_err()
1032            .flatten();
1033        let editor = cx.new(|cx| {
1034            TextThreadEditor::for_text_thread(
1035                text_thread,
1036                self.fs.clone(),
1037                self.workspace.clone(),
1038                self.project.clone(),
1039                lsp_adapter_delegate,
1040                window,
1041                cx,
1042            )
1043        });
1044
1045        if self.selected_agent != AgentType::TextThread {
1046            self.selected_agent = AgentType::TextThread;
1047            self.serialize(cx);
1048        }
1049
1050        self.set_active_view(
1051            ActiveView::text_thread(editor, self.language_registry.clone(), window, cx),
1052            true,
1053            window,
1054            cx,
1055        );
1056    }
1057
1058    pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1059        match self.active_view {
1060            ActiveView::Configuration | ActiveView::History { .. } => {
1061                if let Some(previous_view) = self.previous_view.take() {
1062                    self.active_view = previous_view;
1063
1064                    match &self.active_view {
1065                        ActiveView::ExternalAgentThread { thread_view } => {
1066                            thread_view.focus_handle(cx).focus(window, cx);
1067                        }
1068                        ActiveView::TextThread {
1069                            text_thread_editor, ..
1070                        } => {
1071                            text_thread_editor.focus_handle(cx).focus(window, cx);
1072                        }
1073                        ActiveView::History { .. } | ActiveView::Configuration => {}
1074                    }
1075                }
1076                cx.notify();
1077            }
1078            _ => {}
1079        }
1080    }
1081
1082    pub fn toggle_navigation_menu(
1083        &mut self,
1084        _: &ToggleNavigationMenu,
1085        window: &mut Window,
1086        cx: &mut Context<Self>,
1087    ) {
1088        if self.history_kind_for_selected_agent(cx).is_none() {
1089            return;
1090        }
1091        self.agent_navigation_menu_handle.toggle(window, cx);
1092    }
1093
1094    pub fn toggle_options_menu(
1095        &mut self,
1096        _: &ToggleOptionsMenu,
1097        window: &mut Window,
1098        cx: &mut Context<Self>,
1099    ) {
1100        self.agent_panel_menu_handle.toggle(window, cx);
1101    }
1102
1103    pub fn toggle_new_thread_menu(
1104        &mut self,
1105        _: &ToggleNewThreadMenu,
1106        window: &mut Window,
1107        cx: &mut Context<Self>,
1108    ) {
1109        self.new_thread_menu_handle.toggle(window, cx);
1110    }
1111
1112    pub fn increase_font_size(
1113        &mut self,
1114        action: &IncreaseBufferFontSize,
1115        _: &mut Window,
1116        cx: &mut Context<Self>,
1117    ) {
1118        self.handle_font_size_action(action.persist, px(1.0), cx);
1119    }
1120
1121    pub fn decrease_font_size(
1122        &mut self,
1123        action: &DecreaseBufferFontSize,
1124        _: &mut Window,
1125        cx: &mut Context<Self>,
1126    ) {
1127        self.handle_font_size_action(action.persist, px(-1.0), cx);
1128    }
1129
1130    fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1131        match self.active_view.which_font_size_used() {
1132            WhichFontSize::AgentFont => {
1133                if persist {
1134                    update_settings_file(self.fs.clone(), cx, move |settings, cx| {
1135                        let agent_ui_font_size =
1136                            ThemeSettings::get_global(cx).agent_ui_font_size(cx) + delta;
1137                        let agent_buffer_font_size =
1138                            ThemeSettings::get_global(cx).agent_buffer_font_size(cx) + delta;
1139
1140                        let _ = settings
1141                            .theme
1142                            .agent_ui_font_size
1143                            .insert(f32::from(theme::clamp_font_size(agent_ui_font_size)).into());
1144                        let _ = settings.theme.agent_buffer_font_size.insert(
1145                            f32::from(theme::clamp_font_size(agent_buffer_font_size)).into(),
1146                        );
1147                    });
1148                } else {
1149                    theme::adjust_agent_ui_font_size(cx, |size| size + delta);
1150                    theme::adjust_agent_buffer_font_size(cx, |size| size + delta);
1151                }
1152            }
1153            WhichFontSize::BufferFont => {
1154                // Prompt editor uses the buffer font size, so allow the action to propagate to the
1155                // default handler that changes that font size.
1156                cx.propagate();
1157            }
1158            WhichFontSize::None => {}
1159        }
1160    }
1161
1162    pub fn reset_font_size(
1163        &mut self,
1164        action: &ResetBufferFontSize,
1165        _: &mut Window,
1166        cx: &mut Context<Self>,
1167    ) {
1168        if action.persist {
1169            update_settings_file(self.fs.clone(), cx, move |settings, _| {
1170                settings.theme.agent_ui_font_size = None;
1171                settings.theme.agent_buffer_font_size = None;
1172            });
1173        } else {
1174            theme::reset_agent_ui_font_size(cx);
1175            theme::reset_agent_buffer_font_size(cx);
1176        }
1177    }
1178
1179    pub fn reset_agent_zoom(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1180        theme::reset_agent_ui_font_size(cx);
1181        theme::reset_agent_buffer_font_size(cx);
1182    }
1183
1184    pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1185        if self.zoomed {
1186            cx.emit(PanelEvent::ZoomOut);
1187        } else {
1188            if !self.focus_handle(cx).contains_focused(window, cx) {
1189                cx.focus_self(window);
1190            }
1191            cx.emit(PanelEvent::ZoomIn);
1192        }
1193    }
1194
1195    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1196        let agent_server_store = self.project.read(cx).agent_server_store().clone();
1197        let context_server_store = self.project.read(cx).context_server_store();
1198        let fs = self.fs.clone();
1199
1200        self.set_active_view(ActiveView::Configuration, true, window, cx);
1201        self.configuration = Some(cx.new(|cx| {
1202            AgentConfiguration::new(
1203                fs,
1204                agent_server_store,
1205                context_server_store,
1206                self.context_server_registry.clone(),
1207                self.language_registry.clone(),
1208                self.workspace.clone(),
1209                window,
1210                cx,
1211            )
1212        }));
1213
1214        if let Some(configuration) = self.configuration.as_ref() {
1215            self.configuration_subscription = Some(cx.subscribe_in(
1216                configuration,
1217                window,
1218                Self::handle_agent_configuration_event,
1219            ));
1220
1221            configuration.focus_handle(cx).focus(window, cx);
1222        }
1223    }
1224
1225    pub(crate) fn open_active_thread_as_markdown(
1226        &mut self,
1227        _: &OpenActiveThreadAsMarkdown,
1228        window: &mut Window,
1229        cx: &mut Context<Self>,
1230    ) {
1231        let Some(workspace) = self.workspace.upgrade() else {
1232            return;
1233        };
1234
1235        match &self.active_view {
1236            ActiveView::ExternalAgentThread { thread_view } => {
1237                thread_view
1238                    .update(cx, |thread_view, cx| {
1239                        thread_view.open_thread_as_markdown(workspace, window, cx)
1240                    })
1241                    .detach_and_log_err(cx);
1242            }
1243            ActiveView::TextThread { .. }
1244            | ActiveView::History { .. }
1245            | ActiveView::Configuration => {}
1246        }
1247    }
1248
1249    fn handle_agent_configuration_event(
1250        &mut self,
1251        _entity: &Entity<AgentConfiguration>,
1252        event: &AssistantConfigurationEvent,
1253        window: &mut Window,
1254        cx: &mut Context<Self>,
1255    ) {
1256        match event {
1257            AssistantConfigurationEvent::NewThread(provider) => {
1258                if LanguageModelRegistry::read_global(cx)
1259                    .default_model()
1260                    .is_none_or(|model| model.provider.id() != provider.id())
1261                    && let Some(model) = provider.default_model(cx)
1262                {
1263                    update_settings_file(self.fs.clone(), cx, move |settings, _| {
1264                        let provider = model.provider_id().0.to_string();
1265                        let model = model.id().0.to_string();
1266                        settings
1267                            .agent
1268                            .get_or_insert_default()
1269                            .set_model(LanguageModelSelection {
1270                                provider: LanguageModelProviderSetting(provider),
1271                                model,
1272                            })
1273                    });
1274                }
1275
1276                self.new_thread(&NewThread, window, cx);
1277                if let Some((thread, model)) = self
1278                    .active_native_agent_thread(cx)
1279                    .zip(provider.default_model(cx))
1280                {
1281                    thread.update(cx, |thread, cx| {
1282                        thread.set_model(model, cx);
1283                    });
1284                }
1285            }
1286        }
1287    }
1288
1289    pub(crate) fn active_agent_thread(&self, cx: &App) -> Option<Entity<AcpThread>> {
1290        match &self.active_view {
1291            ActiveView::ExternalAgentThread { thread_view, .. } => {
1292                thread_view.read(cx).thread().cloned()
1293            }
1294            _ => None,
1295        }
1296    }
1297
1298    pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
1299        match &self.active_view {
1300            ActiveView::ExternalAgentThread { thread_view, .. } => {
1301                thread_view.read(cx).as_native_thread(cx)
1302            }
1303            _ => None,
1304        }
1305    }
1306
1307    pub(crate) fn active_text_thread_editor(&self) -> Option<Entity<TextThreadEditor>> {
1308        match &self.active_view {
1309            ActiveView::TextThread {
1310                text_thread_editor, ..
1311            } => Some(text_thread_editor.clone()),
1312            _ => None,
1313        }
1314    }
1315
1316    fn set_active_view(
1317        &mut self,
1318        new_view: ActiveView,
1319        focus: bool,
1320        window: &mut Window,
1321        cx: &mut Context<Self>,
1322    ) {
1323        let current_is_history = matches!(self.active_view, ActiveView::History { .. });
1324        let new_is_history = matches!(new_view, ActiveView::History { .. });
1325
1326        let current_is_config = matches!(self.active_view, ActiveView::Configuration);
1327        let new_is_config = matches!(new_view, ActiveView::Configuration);
1328
1329        let current_is_special = current_is_history || current_is_config;
1330        let new_is_special = new_is_history || new_is_config;
1331
1332        match &new_view {
1333            ActiveView::TextThread { .. } => {}
1334            ActiveView::ExternalAgentThread { .. } => {}
1335            ActiveView::History { .. } | ActiveView::Configuration => {}
1336        }
1337
1338        if current_is_special && !new_is_special {
1339            self.active_view = new_view;
1340        } else if !current_is_special && new_is_special {
1341            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1342        } else {
1343            if !new_is_special {
1344                self.previous_view = None;
1345            }
1346            self.active_view = new_view;
1347        }
1348
1349        if focus {
1350            self.focus_handle(cx).focus(window, cx);
1351        }
1352    }
1353
1354    fn populate_recently_updated_menu_section(
1355        mut menu: ContextMenu,
1356        panel: Entity<Self>,
1357        kind: HistoryKind,
1358        cx: &mut Context<ContextMenu>,
1359    ) -> ContextMenu {
1360        match kind {
1361            HistoryKind::AgentThreads => {
1362                let entries = panel
1363                    .read(cx)
1364                    .acp_history
1365                    .read(cx)
1366                    .sessions()
1367                    .iter()
1368                    .take(RECENTLY_UPDATED_MENU_LIMIT)
1369                    .cloned()
1370                    .collect::<Vec<_>>();
1371
1372                if entries.is_empty() {
1373                    return menu;
1374                }
1375
1376                menu = menu.header("Recently Updated");
1377
1378                for entry in entries {
1379                    let title = entry
1380                        .title
1381                        .as_ref()
1382                        .filter(|title| !title.is_empty())
1383                        .cloned()
1384                        .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE));
1385
1386                    menu = menu.entry(title, None, {
1387                        let panel = panel.downgrade();
1388                        let entry = entry.clone();
1389                        move |window, cx| {
1390                            let entry = entry.clone();
1391                            panel
1392                                .update(cx, move |this, cx| {
1393                                    this.external_thread(
1394                                        Some(ExternalAgent::NativeAgent),
1395                                        Some(entry.clone()),
1396                                        None,
1397                                        window,
1398                                        cx,
1399                                    );
1400                                })
1401                                .ok();
1402                        }
1403                    });
1404                }
1405            }
1406            HistoryKind::TextThreads => {
1407                let entries = panel
1408                    .read(cx)
1409                    .text_thread_store
1410                    .read(cx)
1411                    .ordered_text_threads()
1412                    .take(RECENTLY_UPDATED_MENU_LIMIT)
1413                    .cloned()
1414                    .collect::<Vec<_>>();
1415
1416                if entries.is_empty() {
1417                    return menu;
1418                }
1419
1420                menu = menu.header("Recently Updated");
1421
1422                for entry in entries {
1423                    let title = if entry.title.is_empty() {
1424                        SharedString::new_static(DEFAULT_THREAD_TITLE)
1425                    } else {
1426                        entry.title.clone()
1427                    };
1428
1429                    menu = menu.entry(title, None, {
1430                        let panel = panel.downgrade();
1431                        let entry = entry.clone();
1432                        move |window, cx| {
1433                            let path = entry.path.clone();
1434                            panel
1435                                .update(cx, move |this, cx| {
1436                                    this.open_saved_text_thread(path.clone(), window, cx)
1437                                        .detach_and_log_err(cx);
1438                                })
1439                                .ok();
1440                        }
1441                    });
1442                }
1443            }
1444        }
1445
1446        menu.separator()
1447    }
1448
1449    pub fn selected_agent(&self) -> AgentType {
1450        self.selected_agent.clone()
1451    }
1452
1453    fn sync_agent_servers_from_extensions(&mut self, cx: &mut Context<Self>) {
1454        if let Some(extension_store) = ExtensionStore::try_global(cx) {
1455            let (manifests, extensions_dir) = {
1456                let store = extension_store.read(cx);
1457                let installed = store.installed_extensions();
1458                let manifests: Vec<_> = installed
1459                    .iter()
1460                    .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1461                    .collect();
1462                let extensions_dir = paths::extensions_dir().join("installed");
1463                (manifests, extensions_dir)
1464            };
1465
1466            self.project.update(cx, |project, cx| {
1467                project.agent_server_store().update(cx, |store, cx| {
1468                    let manifest_refs: Vec<_> = manifests
1469                        .iter()
1470                        .map(|(id, manifest)| (id.as_ref(), manifest.as_ref()))
1471                        .collect();
1472                    store.sync_extension_agents(manifest_refs, extensions_dir, cx);
1473                });
1474            });
1475        }
1476    }
1477
1478    pub fn new_agent_thread(
1479        &mut self,
1480        agent: AgentType,
1481        window: &mut Window,
1482        cx: &mut Context<Self>,
1483    ) {
1484        match agent {
1485            AgentType::TextThread => {
1486                window.dispatch_action(NewTextThread.boxed_clone(), cx);
1487            }
1488            AgentType::NativeAgent => self.external_thread(
1489                Some(crate::ExternalAgent::NativeAgent),
1490                None,
1491                None,
1492                window,
1493                cx,
1494            ),
1495            AgentType::Gemini => {
1496                self.external_thread(Some(crate::ExternalAgent::Gemini), None, None, window, cx)
1497            }
1498            AgentType::ClaudeCode => {
1499                self.selected_agent = AgentType::ClaudeCode;
1500                self.serialize(cx);
1501                self.external_thread(
1502                    Some(crate::ExternalAgent::ClaudeCode),
1503                    None,
1504                    None,
1505                    window,
1506                    cx,
1507                )
1508            }
1509            AgentType::Codex => {
1510                self.selected_agent = AgentType::Codex;
1511                self.serialize(cx);
1512                self.external_thread(Some(crate::ExternalAgent::Codex), None, None, window, cx)
1513            }
1514            AgentType::Custom { name } => self.external_thread(
1515                Some(crate::ExternalAgent::Custom { name }),
1516                None,
1517                None,
1518                window,
1519                cx,
1520            ),
1521        }
1522    }
1523
1524    pub fn load_agent_thread(
1525        &mut self,
1526        thread: AgentSessionInfo,
1527        window: &mut Window,
1528        cx: &mut Context<Self>,
1529    ) {
1530        self.external_thread(
1531            Some(ExternalAgent::NativeAgent),
1532            Some(thread),
1533            None,
1534            window,
1535            cx,
1536        );
1537    }
1538
1539    fn _external_thread(
1540        &mut self,
1541        server: Rc<dyn AgentServer>,
1542        resume_thread: Option<AgentSessionInfo>,
1543        summarize_thread: Option<AgentSessionInfo>,
1544        workspace: WeakEntity<Workspace>,
1545        project: Entity<Project>,
1546        loading: bool,
1547        ext_agent: ExternalAgent,
1548        window: &mut Window,
1549        cx: &mut Context<Self>,
1550    ) {
1551        let selected_agent = AgentType::from(ext_agent);
1552        if self.selected_agent != selected_agent {
1553            self.selected_agent = selected_agent;
1554            self.serialize(cx);
1555        }
1556        let thread_store = server
1557            .clone()
1558            .downcast::<agent::NativeAgentServer>()
1559            .is_some()
1560            .then(|| self.thread_store.clone());
1561
1562        let thread_view = cx.new(|cx| {
1563            crate::acp::AcpThreadView::new(
1564                server,
1565                resume_thread,
1566                summarize_thread,
1567                workspace.clone(),
1568                project,
1569                thread_store,
1570                self.prompt_store.clone(),
1571                self.acp_history.clone(),
1572                !loading,
1573                window,
1574                cx,
1575            )
1576        });
1577
1578        self.set_active_view(
1579            ActiveView::ExternalAgentThread { thread_view },
1580            !loading,
1581            window,
1582            cx,
1583        );
1584    }
1585}
1586
1587impl Focusable for AgentPanel {
1588    fn focus_handle(&self, cx: &App) -> FocusHandle {
1589        match &self.active_view {
1590            ActiveView::ExternalAgentThread { thread_view, .. } => thread_view.focus_handle(cx),
1591            ActiveView::History { kind } => match kind {
1592                HistoryKind::AgentThreads => self.acp_history.focus_handle(cx),
1593                HistoryKind::TextThreads => self.text_thread_history.focus_handle(cx),
1594            },
1595            ActiveView::TextThread {
1596                text_thread_editor, ..
1597            } => text_thread_editor.focus_handle(cx),
1598            ActiveView::Configuration => {
1599                if let Some(configuration) = self.configuration.as_ref() {
1600                    configuration.focus_handle(cx)
1601                } else {
1602                    cx.focus_handle()
1603                }
1604            }
1605        }
1606    }
1607}
1608
1609fn agent_panel_dock_position(cx: &App) -> DockPosition {
1610    AgentSettings::get_global(cx).dock.into()
1611}
1612
1613impl EventEmitter<PanelEvent> for AgentPanel {}
1614
1615impl Panel for AgentPanel {
1616    fn persistent_name() -> &'static str {
1617        "AgentPanel"
1618    }
1619
1620    fn panel_key() -> &'static str {
1621        AGENT_PANEL_KEY
1622    }
1623
1624    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1625        agent_panel_dock_position(cx)
1626    }
1627
1628    fn position_is_valid(&self, position: DockPosition) -> bool {
1629        position != DockPosition::Bottom
1630    }
1631
1632    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1633        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1634            settings
1635                .agent
1636                .get_or_insert_default()
1637                .set_dock(position.into());
1638        });
1639    }
1640
1641    fn size(&self, window: &Window, cx: &App) -> Pixels {
1642        let settings = AgentSettings::get_global(cx);
1643        match self.position(window, cx) {
1644            DockPosition::Left | DockPosition::Right => {
1645                self.width.unwrap_or(settings.default_width)
1646            }
1647            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1648        }
1649    }
1650
1651    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1652        match self.position(window, cx) {
1653            DockPosition::Left | DockPosition::Right => self.width = size,
1654            DockPosition::Bottom => self.height = size,
1655        }
1656        self.serialize(cx);
1657        cx.notify();
1658    }
1659
1660    fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
1661
1662    fn remote_id() -> Option<proto::PanelId> {
1663        Some(proto::PanelId::AssistantPanel)
1664    }
1665
1666    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1667        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
1668    }
1669
1670    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1671        Some("Agent Panel")
1672    }
1673
1674    fn toggle_action(&self) -> Box<dyn Action> {
1675        Box::new(ToggleFocus)
1676    }
1677
1678    fn activation_priority(&self) -> u32 {
1679        3
1680    }
1681
1682    fn enabled(&self, cx: &App) -> bool {
1683        AgentSettings::get_global(cx).enabled(cx)
1684    }
1685
1686    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1687        self.zoomed
1688    }
1689
1690    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1691        self.zoomed = zoomed;
1692        cx.notify();
1693    }
1694}
1695
1696impl AgentPanel {
1697    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
1698        const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
1699
1700        let content = match &self.active_view {
1701            ActiveView::ExternalAgentThread { thread_view } => {
1702                let is_generating_title = thread_view
1703                    .read(cx)
1704                    .as_native_thread(cx)
1705                    .map_or(false, |t| t.read(cx).is_generating_title());
1706
1707                if let Some(title_editor) = thread_view.read(cx).title_editor() {
1708                    let container = div()
1709                        .w_full()
1710                        .on_action({
1711                            let thread_view = thread_view.downgrade();
1712                            move |_: &menu::Confirm, window, cx| {
1713                                if let Some(thread_view) = thread_view.upgrade() {
1714                                    thread_view.focus_handle(cx).focus(window, cx);
1715                                }
1716                            }
1717                        })
1718                        .on_action({
1719                            let thread_view = thread_view.downgrade();
1720                            move |_: &editor::actions::Cancel, window, cx| {
1721                                if let Some(thread_view) = thread_view.upgrade() {
1722                                    thread_view.focus_handle(cx).focus(window, cx);
1723                                }
1724                            }
1725                        })
1726                        .child(title_editor);
1727
1728                    if is_generating_title {
1729                        container
1730                            .with_animation(
1731                                "generating_title",
1732                                Animation::new(Duration::from_secs(2))
1733                                    .repeat()
1734                                    .with_easing(pulsating_between(0.4, 0.8)),
1735                                |div, delta| div.opacity(delta),
1736                            )
1737                            .into_any_element()
1738                    } else {
1739                        container.into_any_element()
1740                    }
1741                } else {
1742                    Label::new(thread_view.read(cx).title(cx))
1743                        .color(Color::Muted)
1744                        .truncate()
1745                        .into_any_element()
1746                }
1747            }
1748            ActiveView::TextThread {
1749                title_editor,
1750                text_thread_editor,
1751                ..
1752            } => {
1753                let summary = text_thread_editor.read(cx).text_thread().read(cx).summary();
1754
1755                match summary {
1756                    TextThreadSummary::Pending => Label::new(TextThreadSummary::DEFAULT)
1757                        .color(Color::Muted)
1758                        .truncate()
1759                        .into_any_element(),
1760                    TextThreadSummary::Content(summary) => {
1761                        if summary.done {
1762                            div()
1763                                .w_full()
1764                                .child(title_editor.clone())
1765                                .into_any_element()
1766                        } else {
1767                            Label::new(LOADING_SUMMARY_PLACEHOLDER)
1768                                .truncate()
1769                                .color(Color::Muted)
1770                                .with_animation(
1771                                    "generating_title",
1772                                    Animation::new(Duration::from_secs(2))
1773                                        .repeat()
1774                                        .with_easing(pulsating_between(0.4, 0.8)),
1775                                    |label, delta| label.alpha(delta),
1776                                )
1777                                .into_any_element()
1778                        }
1779                    }
1780                    TextThreadSummary::Error => h_flex()
1781                        .w_full()
1782                        .child(title_editor.clone())
1783                        .child(
1784                            IconButton::new("retry-summary-generation", IconName::RotateCcw)
1785                                .icon_size(IconSize::Small)
1786                                .on_click({
1787                                    let text_thread_editor = text_thread_editor.clone();
1788                                    move |_, _window, cx| {
1789                                        text_thread_editor.update(cx, |text_thread_editor, cx| {
1790                                            text_thread_editor.regenerate_summary(cx);
1791                                        });
1792                                    }
1793                                })
1794                                .tooltip(move |_window, cx| {
1795                                    cx.new(|_| {
1796                                        Tooltip::new("Failed to generate title")
1797                                            .meta("Click to try again")
1798                                    })
1799                                    .into()
1800                                }),
1801                        )
1802                        .into_any_element(),
1803                }
1804            }
1805            ActiveView::History { kind } => {
1806                let title = match kind {
1807                    HistoryKind::AgentThreads => "History",
1808                    HistoryKind::TextThreads => "Text Threads",
1809                };
1810                Label::new(title).truncate().into_any_element()
1811            }
1812            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
1813        };
1814
1815        h_flex()
1816            .key_context("TitleEditor")
1817            .id("TitleEditor")
1818            .flex_grow()
1819            .w_full()
1820            .max_w_full()
1821            .overflow_x_scroll()
1822            .child(content)
1823            .into_any()
1824    }
1825
1826    fn handle_regenerate_thread_title(thread_view: Entity<AcpThreadView>, cx: &mut App) {
1827        thread_view.update(cx, |thread_view, cx| {
1828            if let Some(thread) = thread_view.as_native_thread(cx) {
1829                thread.update(cx, |thread, cx| {
1830                    thread.generate_title(cx);
1831                });
1832            }
1833        });
1834    }
1835
1836    fn handle_regenerate_text_thread_title(
1837        text_thread_editor: Entity<TextThreadEditor>,
1838        cx: &mut App,
1839    ) {
1840        text_thread_editor.update(cx, |text_thread_editor, cx| {
1841            text_thread_editor.regenerate_summary(cx);
1842        });
1843    }
1844
1845    fn render_panel_options_menu(
1846        &self,
1847        window: &mut Window,
1848        cx: &mut Context<Self>,
1849    ) -> impl IntoElement {
1850        let focus_handle = self.focus_handle(cx);
1851
1852        let full_screen_label = if self.is_zoomed(window, cx) {
1853            "Disable Full Screen"
1854        } else {
1855            "Enable Full Screen"
1856        };
1857
1858        let selected_agent = self.selected_agent.clone();
1859
1860        let text_thread_view = match &self.active_view {
1861            ActiveView::TextThread {
1862                text_thread_editor, ..
1863            } => Some(text_thread_editor.clone()),
1864            _ => None,
1865        };
1866        let text_thread_with_messages = match &self.active_view {
1867            ActiveView::TextThread {
1868                text_thread_editor, ..
1869            } => text_thread_editor
1870                .read(cx)
1871                .text_thread()
1872                .read(cx)
1873                .messages(cx)
1874                .any(|message| message.role == language_model::Role::Assistant),
1875            _ => false,
1876        };
1877
1878        let thread_view = match &self.active_view {
1879            ActiveView::ExternalAgentThread { thread_view } => Some(thread_view.clone()),
1880            _ => None,
1881        };
1882        let thread_with_messages = match &self.active_view {
1883            ActiveView::ExternalAgentThread { thread_view } => {
1884                thread_view.read(cx).has_user_submitted_prompt(cx)
1885            }
1886            _ => false,
1887        };
1888
1889        PopoverMenu::new("agent-options-menu")
1890            .trigger_with_tooltip(
1891                IconButton::new("agent-options-menu", IconName::Ellipsis)
1892                    .icon_size(IconSize::Small),
1893                {
1894                    let focus_handle = focus_handle.clone();
1895                    move |_window, cx| {
1896                        Tooltip::for_action_in(
1897                            "Toggle Agent Menu",
1898                            &ToggleOptionsMenu,
1899                            &focus_handle,
1900                            cx,
1901                        )
1902                    }
1903                },
1904            )
1905            .anchor(Corner::TopRight)
1906            .with_handle(self.agent_panel_menu_handle.clone())
1907            .menu({
1908                move |window, cx| {
1909                    Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
1910                        menu = menu.context(focus_handle.clone());
1911
1912                        if thread_with_messages | text_thread_with_messages {
1913                            menu = menu.header("Current Thread");
1914
1915                            if let Some(text_thread_view) = text_thread_view.as_ref() {
1916                                menu = menu
1917                                    .entry("Regenerate Thread Title", None, {
1918                                        let text_thread_view = text_thread_view.clone();
1919                                        move |_, cx| {
1920                                            Self::handle_regenerate_text_thread_title(
1921                                                text_thread_view.clone(),
1922                                                cx,
1923                                            );
1924                                        }
1925                                    })
1926                                    .separator();
1927                            }
1928
1929                            if let Some(thread_view) = thread_view.as_ref() {
1930                                menu = menu
1931                                    .entry("Regenerate Thread Title", None, {
1932                                        let thread_view = thread_view.clone();
1933                                        move |_, cx| {
1934                                            Self::handle_regenerate_thread_title(
1935                                                thread_view.clone(),
1936                                                cx,
1937                                            );
1938                                        }
1939                                    })
1940                                    .separator();
1941                            }
1942                        }
1943
1944                        menu = menu
1945                            .header("MCP Servers")
1946                            .action(
1947                                "View Server Extensions",
1948                                Box::new(zed_actions::Extensions {
1949                                    category_filter: Some(
1950                                        zed_actions::ExtensionCategoryFilter::ContextServers,
1951                                    ),
1952                                    id: None,
1953                                }),
1954                            )
1955                            .action("Add Custom Server…", Box::new(AddContextServer))
1956                            .separator()
1957                            .action("Rules", Box::new(OpenRulesLibrary::default()))
1958                            .action("Profiles", Box::new(ManageProfiles::default()))
1959                            .action("Settings", Box::new(OpenSettings))
1960                            .separator()
1961                            .action(full_screen_label, Box::new(ToggleZoom));
1962
1963                        if selected_agent == AgentType::Gemini {
1964                            menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
1965                        }
1966
1967                        menu
1968                    }))
1969                }
1970            })
1971    }
1972
1973    fn render_recent_entries_menu(
1974        &self,
1975        icon: IconName,
1976        corner: Corner,
1977        cx: &mut Context<Self>,
1978    ) -> impl IntoElement {
1979        let focus_handle = self.focus_handle(cx);
1980
1981        PopoverMenu::new("agent-nav-menu")
1982            .trigger_with_tooltip(
1983                IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
1984                {
1985                    move |_window, cx| {
1986                        Tooltip::for_action_in(
1987                            "Toggle Recently Updated Threads",
1988                            &ToggleNavigationMenu,
1989                            &focus_handle,
1990                            cx,
1991                        )
1992                    }
1993                },
1994            )
1995            .anchor(corner)
1996            .with_handle(self.agent_navigation_menu_handle.clone())
1997            .menu({
1998                let menu = self.agent_navigation_menu.clone();
1999                move |window, cx| {
2000                    telemetry::event!("View Thread History Clicked");
2001
2002                    if let Some(menu) = menu.as_ref() {
2003                        menu.update(cx, |_, cx| {
2004                            cx.defer_in(window, |menu, window, cx| {
2005                                menu.rebuild(window, cx);
2006                            });
2007                        })
2008                    }
2009                    menu.clone()
2010                }
2011            })
2012    }
2013
2014    fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
2015        let focus_handle = self.focus_handle(cx);
2016
2017        IconButton::new("go-back", IconName::ArrowLeft)
2018            .icon_size(IconSize::Small)
2019            .on_click(cx.listener(|this, _, window, cx| {
2020                this.go_back(&workspace::GoBack, window, cx);
2021            }))
2022            .tooltip({
2023                move |_window, cx| {
2024                    Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
2025                }
2026            })
2027    }
2028
2029    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2030        let agent_server_store = self.project.read(cx).agent_server_store().clone();
2031        let focus_handle = self.focus_handle(cx);
2032
2033        let (selected_agent_custom_icon, selected_agent_label) =
2034            if let AgentType::Custom { name, .. } = &self.selected_agent {
2035                let store = agent_server_store.read(cx);
2036                let icon = store.agent_icon(&ExternalAgentServerName(name.clone()));
2037
2038                let label = store
2039                    .agent_display_name(&ExternalAgentServerName(name.clone()))
2040                    .unwrap_or_else(|| self.selected_agent.label());
2041                (icon, label)
2042            } else {
2043                (None, self.selected_agent.label())
2044            };
2045
2046        let active_thread = match &self.active_view {
2047            ActiveView::ExternalAgentThread { thread_view } => {
2048                thread_view.read(cx).as_native_thread(cx)
2049            }
2050            ActiveView::TextThread { .. }
2051            | ActiveView::History { .. }
2052            | ActiveView::Configuration => None,
2053        };
2054
2055        let new_thread_menu = PopoverMenu::new("new_thread_menu")
2056            .trigger_with_tooltip(
2057                IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
2058                {
2059                    let focus_handle = focus_handle.clone();
2060                    move |_window, cx| {
2061                        Tooltip::for_action_in(
2062                            "New Thread…",
2063                            &ToggleNewThreadMenu,
2064                            &focus_handle,
2065                            cx,
2066                        )
2067                    }
2068                },
2069            )
2070            .anchor(Corner::TopRight)
2071            .with_handle(self.new_thread_menu_handle.clone())
2072            .menu({
2073                let selected_agent = self.selected_agent.clone();
2074                let is_agent_selected = move |agent_type: AgentType| selected_agent == agent_type;
2075
2076                let workspace = self.workspace.clone();
2077                let is_via_collab = workspace
2078                    .update(cx, |workspace, cx| {
2079                        workspace.project().read(cx).is_via_collab()
2080                    })
2081                    .unwrap_or_default();
2082
2083                move |window, cx| {
2084                    telemetry::event!("New Thread Clicked");
2085
2086                    let active_thread = active_thread.clone();
2087                    Some(ContextMenu::build(window, cx, |menu, _window, cx| {
2088                        menu.context(focus_handle.clone())
2089                            .when_some(active_thread, |this, active_thread| {
2090                                let thread = active_thread.read(cx);
2091
2092                                if !thread.is_empty() {
2093                                    let session_id = thread.id().clone();
2094                                    this.item(
2095                                        ContextMenuEntry::new("New From Summary")
2096                                            .icon(IconName::ThreadFromSummary)
2097                                            .icon_color(Color::Muted)
2098                                            .handler(move |window, cx| {
2099                                                window.dispatch_action(
2100                                                    Box::new(NewNativeAgentThreadFromSummary {
2101                                                        from_session_id: session_id.clone(),
2102                                                    }),
2103                                                    cx,
2104                                                );
2105                                            }),
2106                                    )
2107                                } else {
2108                                    this
2109                                }
2110                            })
2111                            .item(
2112                                ContextMenuEntry::new("Zed Agent")
2113                                    .when(is_agent_selected(AgentType::NativeAgent) | is_agent_selected(AgentType::TextThread) , |this| {
2114                                        this.action(Box::new(NewExternalAgentThread { agent: None }))
2115                                    })
2116                                    .icon(IconName::ZedAgent)
2117                                    .icon_color(Color::Muted)
2118                                    .handler({
2119                                        let workspace = workspace.clone();
2120                                        move |window, cx| {
2121                                            if let Some(workspace) = workspace.upgrade() {
2122                                                workspace.update(cx, |workspace, cx| {
2123                                                    if let Some(panel) =
2124                                                        workspace.panel::<AgentPanel>(cx)
2125                                                    {
2126                                                        panel.update(cx, |panel, cx| {
2127                                                            panel.new_agent_thread(
2128                                                                AgentType::NativeAgent,
2129                                                                window,
2130                                                                cx,
2131                                                            );
2132                                                        });
2133                                                    }
2134                                                });
2135                                            }
2136                                        }
2137                                    }),
2138                            )
2139                            .item(
2140                                ContextMenuEntry::new("Text Thread")
2141                                    .action(NewTextThread.boxed_clone())
2142                                    .icon(IconName::TextThread)
2143                                    .icon_color(Color::Muted)
2144                                    .handler({
2145                                        let workspace = workspace.clone();
2146                                        move |window, cx| {
2147                                            if let Some(workspace) = workspace.upgrade() {
2148                                                workspace.update(cx, |workspace, cx| {
2149                                                    if let Some(panel) =
2150                                                        workspace.panel::<AgentPanel>(cx)
2151                                                    {
2152                                                        panel.update(cx, |panel, cx| {
2153                                                            panel.new_agent_thread(
2154                                                                AgentType::TextThread,
2155                                                                window,
2156                                                                cx,
2157                                                            );
2158                                                        });
2159                                                    }
2160                                                });
2161                                            }
2162                                        }
2163                                    }),
2164                            )
2165                            .separator()
2166                            .header("External Agents")
2167                            .item(
2168                                ContextMenuEntry::new("Claude Code")
2169                                    .when(is_agent_selected(AgentType::ClaudeCode), |this| {
2170                                        this.action(Box::new(NewExternalAgentThread { agent: None }))
2171                                    })
2172                                    .icon(IconName::AiClaude)
2173                                    .disabled(is_via_collab)
2174                                    .icon_color(Color::Muted)
2175                                    .handler({
2176                                        let workspace = workspace.clone();
2177                                        move |window, cx| {
2178                                            if let Some(workspace) = workspace.upgrade() {
2179                                                workspace.update(cx, |workspace, cx| {
2180                                                    if let Some(panel) =
2181                                                        workspace.panel::<AgentPanel>(cx)
2182                                                    {
2183                                                        panel.update(cx, |panel, cx| {
2184                                                            panel.new_agent_thread(
2185                                                                AgentType::ClaudeCode,
2186                                                                window,
2187                                                                cx,
2188                                                            );
2189                                                        });
2190                                                    }
2191                                                });
2192                                            }
2193                                        }
2194                                    }),
2195                            )
2196                            .item(
2197                                ContextMenuEntry::new("Codex CLI")
2198                                    .when(is_agent_selected(AgentType::Codex), |this| {
2199                                        this.action(Box::new(NewExternalAgentThread { agent: None }))
2200                                    })
2201                                    .icon(IconName::AiOpenAi)
2202                                    .disabled(is_via_collab)
2203                                    .icon_color(Color::Muted)
2204                                    .handler({
2205                                        let workspace = workspace.clone();
2206                                        move |window, cx| {
2207                                            if let Some(workspace) = workspace.upgrade() {
2208                                                workspace.update(cx, |workspace, cx| {
2209                                                    if let Some(panel) =
2210                                                        workspace.panel::<AgentPanel>(cx)
2211                                                    {
2212                                                        panel.update(cx, |panel, cx| {
2213                                                            panel.new_agent_thread(
2214                                                                AgentType::Codex,
2215                                                                window,
2216                                                                cx,
2217                                                            );
2218                                                        });
2219                                                    }
2220                                                });
2221                                            }
2222                                        }
2223                                    }),
2224                            )
2225                            .item(
2226                                ContextMenuEntry::new("Gemini CLI")
2227                                    .when(is_agent_selected(AgentType::Gemini), |this| {
2228                                        this.action(Box::new(NewExternalAgentThread { agent: None }))
2229                                    })
2230                                    .icon(IconName::AiGemini)
2231                                    .icon_color(Color::Muted)
2232                                    .disabled(is_via_collab)
2233                                    .handler({
2234                                        let workspace = workspace.clone();
2235                                        move |window, cx| {
2236                                            if let Some(workspace) = workspace.upgrade() {
2237                                                workspace.update(cx, |workspace, cx| {
2238                                                    if let Some(panel) =
2239                                                        workspace.panel::<AgentPanel>(cx)
2240                                                    {
2241                                                        panel.update(cx, |panel, cx| {
2242                                                            panel.new_agent_thread(
2243                                                                AgentType::Gemini,
2244                                                                window,
2245                                                                cx,
2246                                                            );
2247                                                        });
2248                                                    }
2249                                                });
2250                                            }
2251                                        }
2252                                    }),
2253                            )
2254                            .map(|mut menu| {
2255                                let agent_server_store = agent_server_store.read(cx);
2256                                let agent_names = agent_server_store
2257                                    .external_agents()
2258                                    .filter(|name| {
2259                                        name.0 != GEMINI_NAME
2260                                            && name.0 != CLAUDE_CODE_NAME
2261                                            && name.0 != CODEX_NAME
2262                                    })
2263                                    .cloned()
2264                                    .collect::<Vec<_>>();
2265
2266                                for agent_name in agent_names {
2267                                    let icon_path = agent_server_store.agent_icon(&agent_name);
2268                                    let display_name = agent_server_store
2269                                        .agent_display_name(&agent_name)
2270                                        .unwrap_or_else(|| agent_name.0.clone());
2271
2272                                    let mut entry = ContextMenuEntry::new(display_name);
2273
2274                                    if let Some(icon_path) = icon_path {
2275                                        entry = entry.custom_icon_svg(icon_path);
2276                                    } else {
2277                                        entry = entry.icon(IconName::Sparkle);
2278                                    }
2279                                    entry = entry
2280                                        .when(
2281                                            is_agent_selected(AgentType::Custom {
2282                                                name: agent_name.0.clone(),
2283                                            }),
2284                                            |this| {
2285                                                this.action(Box::new(NewExternalAgentThread { agent: None }))
2286                                            },
2287                                        )
2288                                        .icon_color(Color::Muted)
2289                                        .disabled(is_via_collab)
2290                                        .handler({
2291                                            let workspace = workspace.clone();
2292                                            let agent_name = agent_name.clone();
2293                                            move |window, cx| {
2294                                                if let Some(workspace) = workspace.upgrade() {
2295                                                    workspace.update(cx, |workspace, cx| {
2296                                                        if let Some(panel) =
2297                                                            workspace.panel::<AgentPanel>(cx)
2298                                                        {
2299                                                            panel.update(cx, |panel, cx| {
2300                                                                panel.new_agent_thread(
2301                                                                    AgentType::Custom {
2302                                                                        name: agent_name
2303                                                                            .clone()
2304                                                                            .into(),
2305                                                                    },
2306                                                                    window,
2307                                                                    cx,
2308                                                                );
2309                                                            });
2310                                                        }
2311                                                    });
2312                                                }
2313                                            }
2314                                        });
2315
2316                                    menu = menu.item(entry);
2317                                }
2318
2319                                menu
2320                            })
2321                            .separator()
2322                            .item(
2323                                ContextMenuEntry::new("Add More Agents")
2324                                    .icon(IconName::Plus)
2325                                    .icon_color(Color::Muted)
2326                                    .handler({
2327                                        move |window, cx| {
2328                                            window.dispatch_action(Box::new(zed_actions::Extensions {
2329                                                category_filter: Some(
2330                                                    zed_actions::ExtensionCategoryFilter::AgentServers,
2331                                                ),
2332                                                id: None,
2333                                            }), cx)
2334                                        }
2335                                    }),
2336                            )
2337                    }))
2338                }
2339            });
2340
2341        let is_thread_loading = self
2342            .active_thread_view()
2343            .map(|thread| thread.read(cx).is_loading())
2344            .unwrap_or(false);
2345
2346        let has_custom_icon = selected_agent_custom_icon.is_some();
2347
2348        let selected_agent = div()
2349            .id("selected_agent_icon")
2350            .when_some(selected_agent_custom_icon, |this, icon_path| {
2351                this.px_1()
2352                    .child(Icon::from_external_svg(icon_path).color(Color::Muted))
2353            })
2354            .when(!has_custom_icon, |this| {
2355                this.when_some(self.selected_agent.icon(), |this, icon| {
2356                    this.px_1().child(Icon::new(icon).color(Color::Muted))
2357                })
2358            })
2359            .tooltip(move |_, cx| {
2360                Tooltip::with_meta(selected_agent_label.clone(), None, "Selected Agent", cx)
2361            });
2362
2363        let selected_agent = if is_thread_loading {
2364            selected_agent
2365                .with_animation(
2366                    "pulsating-icon",
2367                    Animation::new(Duration::from_secs(1))
2368                        .repeat()
2369                        .with_easing(pulsating_between(0.2, 0.6)),
2370                    |icon, delta| icon.opacity(delta),
2371                )
2372                .into_any_element()
2373        } else {
2374            selected_agent.into_any_element()
2375        };
2376
2377        let show_history_menu = self.history_kind_for_selected_agent(cx).is_some();
2378
2379        h_flex()
2380            .id("agent-panel-toolbar")
2381            .h(Tab::container_height(cx))
2382            .max_w_full()
2383            .flex_none()
2384            .justify_between()
2385            .gap_2()
2386            .bg(cx.theme().colors().tab_bar_background)
2387            .border_b_1()
2388            .border_color(cx.theme().colors().border)
2389            .child(
2390                h_flex()
2391                    .size_full()
2392                    .gap(DynamicSpacing::Base04.rems(cx))
2393                    .pl(DynamicSpacing::Base04.rems(cx))
2394                    .child(match &self.active_view {
2395                        ActiveView::History { .. } | ActiveView::Configuration => {
2396                            self.render_toolbar_back_button(cx).into_any_element()
2397                        }
2398                        _ => selected_agent.into_any_element(),
2399                    })
2400                    .child(self.render_title_view(window, cx)),
2401            )
2402            .child(
2403                h_flex()
2404                    .flex_none()
2405                    .gap(DynamicSpacing::Base02.rems(cx))
2406                    .pl(DynamicSpacing::Base04.rems(cx))
2407                    .pr(DynamicSpacing::Base06.rems(cx))
2408                    .child(new_thread_menu)
2409                    .when(show_history_menu, |this| {
2410                        this.child(self.render_recent_entries_menu(
2411                            IconName::MenuAltTemp,
2412                            Corner::TopRight,
2413                            cx,
2414                        ))
2415                    })
2416                    .child(self.render_panel_options_menu(window, cx)),
2417            )
2418    }
2419
2420    fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2421        if TrialEndUpsell::dismissed() {
2422            return false;
2423        }
2424
2425        match &self.active_view {
2426            ActiveView::TextThread { .. } => {
2427                if LanguageModelRegistry::global(cx)
2428                    .read(cx)
2429                    .default_model()
2430                    .is_some_and(|model| {
2431                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2432                    })
2433                {
2434                    return false;
2435                }
2436            }
2437            ActiveView::ExternalAgentThread { .. }
2438            | ActiveView::History { .. }
2439            | ActiveView::Configuration => return false,
2440        }
2441
2442        let plan = self.user_store.read(cx).plan();
2443        let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2444
2445        plan.is_some_and(|plan| plan == Plan::V2(PlanV2::ZedFree)) && has_previous_trial
2446    }
2447
2448    fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
2449        if OnboardingUpsell::dismissed() {
2450            return false;
2451        }
2452
2453        let user_store = self.user_store.read(cx);
2454
2455        if user_store
2456            .plan()
2457            .is_some_and(|plan| plan == Plan::V2(PlanV2::ZedPro))
2458            && user_store
2459                .subscription_period()
2460                .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
2461                .is_some_and(|date| date < chrono::Utc::now())
2462        {
2463            OnboardingUpsell::set_dismissed(true, cx);
2464            return false;
2465        }
2466
2467        match &self.active_view {
2468            ActiveView::History { .. } | ActiveView::Configuration => false,
2469            ActiveView::ExternalAgentThread { thread_view, .. }
2470                if thread_view.read(cx).as_native_thread(cx).is_none() =>
2471            {
2472                false
2473            }
2474            _ => {
2475                let history_is_empty = self.acp_history.read(cx).is_empty();
2476
2477                let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
2478                    .visible_providers()
2479                    .iter()
2480                    .any(|provider| {
2481                        provider.is_authenticated(cx)
2482                            && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2483                    });
2484
2485                history_is_empty || !has_configured_non_zed_providers
2486            }
2487        }
2488    }
2489
2490    fn render_onboarding(
2491        &self,
2492        _window: &mut Window,
2493        cx: &mut Context<Self>,
2494    ) -> Option<impl IntoElement> {
2495        if !self.should_render_onboarding(cx) {
2496            return None;
2497        }
2498
2499        let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
2500
2501        Some(
2502            div()
2503                .when(text_thread_view, |this| {
2504                    this.bg(cx.theme().colors().editor_background)
2505                })
2506                .child(self.onboarding.clone()),
2507        )
2508    }
2509
2510    fn render_trial_end_upsell(
2511        &self,
2512        _window: &mut Window,
2513        cx: &mut Context<Self>,
2514    ) -> Option<impl IntoElement> {
2515        if !self.should_render_trial_end_upsell(cx) {
2516            return None;
2517        }
2518
2519        Some(
2520            v_flex()
2521                .absolute()
2522                .inset_0()
2523                .size_full()
2524                .bg(cx.theme().colors().panel_background)
2525                .opacity(0.85)
2526                .block_mouse_except_scroll()
2527                .child(EndTrialUpsell::new(Arc::new({
2528                    let this = cx.entity();
2529                    move |_, cx| {
2530                        this.update(cx, |_this, cx| {
2531                            TrialEndUpsell::set_dismissed(true, cx);
2532                            cx.notify();
2533                        });
2534                    }
2535                }))),
2536        )
2537    }
2538
2539    fn render_configuration_error(
2540        &self,
2541        border_bottom: bool,
2542        configuration_error: &ConfigurationError,
2543        focus_handle: &FocusHandle,
2544        cx: &mut App,
2545    ) -> impl IntoElement {
2546        let zed_provider_configured = AgentSettings::get_global(cx)
2547            .default_model
2548            .as_ref()
2549            .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
2550
2551        let callout = if zed_provider_configured {
2552            Callout::new()
2553                .icon(IconName::Warning)
2554                .severity(Severity::Warning)
2555                .when(border_bottom, |this| {
2556                    this.border_position(ui::BorderPosition::Bottom)
2557                })
2558                .title("Sign in to continue using Zed as your LLM provider.")
2559                .actions_slot(
2560                    Button::new("sign_in", "Sign In")
2561                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2562                        .label_size(LabelSize::Small)
2563                        .on_click({
2564                            let workspace = self.workspace.clone();
2565                            move |_, _, cx| {
2566                                let Ok(client) =
2567                                    workspace.update(cx, |workspace, _| workspace.client().clone())
2568                                else {
2569                                    return;
2570                                };
2571
2572                                cx.spawn(async move |cx| {
2573                                    client.sign_in_with_optional_connect(true, cx).await
2574                                })
2575                                .detach_and_log_err(cx);
2576                            }
2577                        }),
2578                )
2579        } else {
2580            Callout::new()
2581                .icon(IconName::Warning)
2582                .severity(Severity::Warning)
2583                .when(border_bottom, |this| {
2584                    this.border_position(ui::BorderPosition::Bottom)
2585                })
2586                .title(configuration_error.to_string())
2587                .actions_slot(
2588                    Button::new("settings", "Configure")
2589                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2590                        .label_size(LabelSize::Small)
2591                        .key_binding(
2592                            KeyBinding::for_action_in(&OpenSettings, focus_handle, cx)
2593                                .map(|kb| kb.size(rems_from_px(12.))),
2594                        )
2595                        .on_click(|_event, window, cx| {
2596                            window.dispatch_action(OpenSettings.boxed_clone(), cx)
2597                        }),
2598                )
2599        };
2600
2601        match configuration_error {
2602            ConfigurationError::ModelNotFound
2603            | ConfigurationError::ProviderNotAuthenticated(_)
2604            | ConfigurationError::NoProvider => callout.into_any_element(),
2605        }
2606    }
2607
2608    fn render_text_thread(
2609        &self,
2610        text_thread_editor: &Entity<TextThreadEditor>,
2611        buffer_search_bar: &Entity<BufferSearchBar>,
2612        window: &mut Window,
2613        cx: &mut Context<Self>,
2614    ) -> Div {
2615        let mut registrar = buffer_search::DivRegistrar::new(
2616            |this, _, _cx| match &this.active_view {
2617                ActiveView::TextThread {
2618                    buffer_search_bar, ..
2619                } => Some(buffer_search_bar.clone()),
2620                _ => None,
2621            },
2622            cx,
2623        );
2624        BufferSearchBar::register(&mut registrar);
2625        registrar
2626            .into_div()
2627            .size_full()
2628            .relative()
2629            .map(|parent| {
2630                buffer_search_bar.update(cx, |buffer_search_bar, cx| {
2631                    if buffer_search_bar.is_dismissed() {
2632                        return parent;
2633                    }
2634                    parent.child(
2635                        div()
2636                            .p(DynamicSpacing::Base08.rems(cx))
2637                            .border_b_1()
2638                            .border_color(cx.theme().colors().border_variant)
2639                            .bg(cx.theme().colors().editor_background)
2640                            .child(buffer_search_bar.render(window, cx)),
2641                    )
2642                })
2643            })
2644            .child(text_thread_editor.clone())
2645            .child(self.render_drag_target(cx))
2646    }
2647
2648    fn render_drag_target(&self, cx: &Context<Self>) -> Div {
2649        let is_local = self.project.read(cx).is_local();
2650        div()
2651            .invisible()
2652            .absolute()
2653            .top_0()
2654            .right_0()
2655            .bottom_0()
2656            .left_0()
2657            .bg(cx.theme().colors().drop_target_background)
2658            .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
2659            .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
2660            .when(is_local, |this| {
2661                this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
2662            })
2663            .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
2664                let item = tab.pane.read(cx).item_for_index(tab.ix);
2665                let project_paths = item
2666                    .and_then(|item| item.project_path(cx))
2667                    .into_iter()
2668                    .collect::<Vec<_>>();
2669                this.handle_drop(project_paths, vec![], window, cx);
2670            }))
2671            .on_drop(
2672                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2673                    let project_paths = selection
2674                        .items()
2675                        .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
2676                        .collect::<Vec<_>>();
2677                    this.handle_drop(project_paths, vec![], window, cx);
2678                }),
2679            )
2680            .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
2681                let tasks = paths
2682                    .paths()
2683                    .iter()
2684                    .map(|path| {
2685                        Workspace::project_path_for_path(this.project.clone(), path, false, cx)
2686                    })
2687                    .collect::<Vec<_>>();
2688                cx.spawn_in(window, async move |this, cx| {
2689                    let mut paths = vec![];
2690                    let mut added_worktrees = vec![];
2691                    let opened_paths = futures::future::join_all(tasks).await;
2692                    for entry in opened_paths {
2693                        if let Some((worktree, project_path)) = entry.log_err() {
2694                            added_worktrees.push(worktree);
2695                            paths.push(project_path);
2696                        }
2697                    }
2698                    this.update_in(cx, |this, window, cx| {
2699                        this.handle_drop(paths, added_worktrees, window, cx);
2700                    })
2701                    .ok();
2702                })
2703                .detach();
2704            }))
2705    }
2706
2707    fn handle_drop(
2708        &mut self,
2709        paths: Vec<ProjectPath>,
2710        added_worktrees: Vec<Entity<Worktree>>,
2711        window: &mut Window,
2712        cx: &mut Context<Self>,
2713    ) {
2714        match &self.active_view {
2715            ActiveView::ExternalAgentThread { thread_view } => {
2716                thread_view.update(cx, |thread_view, cx| {
2717                    thread_view.insert_dragged_files(paths, added_worktrees, window, cx);
2718                });
2719            }
2720            ActiveView::TextThread {
2721                text_thread_editor, ..
2722            } => {
2723                text_thread_editor.update(cx, |text_thread_editor, cx| {
2724                    TextThreadEditor::insert_dragged_files(
2725                        text_thread_editor,
2726                        paths,
2727                        added_worktrees,
2728                        window,
2729                        cx,
2730                    );
2731                });
2732            }
2733            ActiveView::History { .. } | ActiveView::Configuration => {}
2734        }
2735    }
2736
2737    fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
2738        if !self.show_trust_workspace_message {
2739            return None;
2740        }
2741
2742        let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
2743
2744        Some(
2745            Callout::new()
2746                .icon(IconName::Warning)
2747                .severity(Severity::Warning)
2748                .border_position(ui::BorderPosition::Bottom)
2749                .title("You're in Restricted Mode")
2750                .description(description)
2751                .actions_slot(
2752                    Button::new("open-trust-modal", "Configure Project Trust")
2753                        .label_size(LabelSize::Small)
2754                        .style(ButtonStyle::Outlined)
2755                        .on_click({
2756                            cx.listener(move |this, _, window, cx| {
2757                                this.workspace
2758                                    .update(cx, |workspace, cx| {
2759                                        workspace
2760                                            .show_worktree_trust_security_modal(true, window, cx)
2761                                    })
2762                                    .log_err();
2763                            })
2764                        }),
2765                ),
2766        )
2767    }
2768
2769    fn key_context(&self) -> KeyContext {
2770        let mut key_context = KeyContext::new_with_defaults();
2771        key_context.add("AgentPanel");
2772        match &self.active_view {
2773            ActiveView::ExternalAgentThread { .. } => key_context.add("acp_thread"),
2774            ActiveView::TextThread { .. } => key_context.add("text_thread"),
2775            ActiveView::History { .. } | ActiveView::Configuration => {}
2776        }
2777        key_context
2778    }
2779}
2780
2781impl Render for AgentPanel {
2782    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2783        // WARNING: Changes to this element hierarchy can have
2784        // non-obvious implications to the layout of children.
2785        //
2786        // If you need to change it, please confirm:
2787        // - The message editor expands (cmd-option-esc) correctly
2788        // - When expanded, the buttons at the bottom of the panel are displayed correctly
2789        // - Font size works as expected and can be changed with cmd-+/cmd-
2790        // - Scrolling in all views works as expected
2791        // - Files can be dropped into the panel
2792        let content = v_flex()
2793            .relative()
2794            .size_full()
2795            .justify_between()
2796            .key_context(self.key_context())
2797            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
2798                this.new_thread(action, window, cx);
2799            }))
2800            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
2801                this.open_history(window, cx);
2802            }))
2803            .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
2804                this.open_configuration(window, cx);
2805            }))
2806            .on_action(cx.listener(Self::open_active_thread_as_markdown))
2807            .on_action(cx.listener(Self::deploy_rules_library))
2808            .on_action(cx.listener(Self::go_back))
2809            .on_action(cx.listener(Self::toggle_navigation_menu))
2810            .on_action(cx.listener(Self::toggle_options_menu))
2811            .on_action(cx.listener(Self::increase_font_size))
2812            .on_action(cx.listener(Self::decrease_font_size))
2813            .on_action(cx.listener(Self::reset_font_size))
2814            .on_action(cx.listener(Self::toggle_zoom))
2815            .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
2816                if let Some(thread_view) = this.active_thread_view() {
2817                    thread_view.update(cx, |thread_view, cx| thread_view.reauthenticate(window, cx))
2818                }
2819            }))
2820            .child(self.render_toolbar(window, cx))
2821            .children(self.render_workspace_trust_message(cx))
2822            .children(self.render_onboarding(window, cx))
2823            .map(|parent| match &self.active_view {
2824                ActiveView::ExternalAgentThread { thread_view, .. } => parent
2825                    .child(thread_view.clone())
2826                    .child(self.render_drag_target(cx)),
2827                ActiveView::History { kind } => match kind {
2828                    HistoryKind::AgentThreads => parent.child(self.acp_history.clone()),
2829                    HistoryKind::TextThreads => parent.child(self.text_thread_history.clone()),
2830                },
2831                ActiveView::TextThread {
2832                    text_thread_editor,
2833                    buffer_search_bar,
2834                    ..
2835                } => {
2836                    let model_registry = LanguageModelRegistry::read_global(cx);
2837                    let configuration_error =
2838                        model_registry.configuration_error(model_registry.default_model(), cx);
2839                    parent
2840                        .map(|this| {
2841                            if !self.should_render_onboarding(cx)
2842                                && let Some(err) = configuration_error.as_ref()
2843                            {
2844                                this.child(self.render_configuration_error(
2845                                    true,
2846                                    err,
2847                                    &self.focus_handle(cx),
2848                                    cx,
2849                                ))
2850                            } else {
2851                                this
2852                            }
2853                        })
2854                        .child(self.render_text_thread(
2855                            text_thread_editor,
2856                            buffer_search_bar,
2857                            window,
2858                            cx,
2859                        ))
2860                }
2861                ActiveView::Configuration => parent.children(self.configuration.clone()),
2862            })
2863            .children(self.render_trial_end_upsell(window, cx));
2864
2865        match self.active_view.which_font_size_used() {
2866            WhichFontSize::AgentFont => {
2867                WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
2868                    .size_full()
2869                    .child(content)
2870                    .into_any()
2871            }
2872            _ => content.into_any(),
2873        }
2874    }
2875}
2876
2877struct PromptLibraryInlineAssist {
2878    workspace: WeakEntity<Workspace>,
2879}
2880
2881impl PromptLibraryInlineAssist {
2882    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
2883        Self { workspace }
2884    }
2885}
2886
2887impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
2888    fn assist(
2889        &self,
2890        prompt_editor: &Entity<Editor>,
2891        initial_prompt: Option<String>,
2892        window: &mut Window,
2893        cx: &mut Context<RulesLibrary>,
2894    ) {
2895        InlineAssistant::update_global(cx, |assistant, cx| {
2896            let Some(workspace) = self.workspace.upgrade() else {
2897                return;
2898            };
2899            let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
2900                return;
2901            };
2902            let project = workspace.read(cx).project().downgrade();
2903            let panel = panel.read(cx);
2904            let thread_store = panel.thread_store().clone();
2905            let history = panel.history().downgrade();
2906            assistant.assist(
2907                prompt_editor,
2908                self.workspace.clone(),
2909                project,
2910                thread_store,
2911                None,
2912                history,
2913                initial_prompt,
2914                window,
2915                cx,
2916            );
2917        })
2918    }
2919
2920    fn focus_agent_panel(
2921        &self,
2922        workspace: &mut Workspace,
2923        window: &mut Window,
2924        cx: &mut Context<Workspace>,
2925    ) -> bool {
2926        workspace.focus_panel::<AgentPanel>(window, cx).is_some()
2927    }
2928}
2929
2930pub struct ConcreteAssistantPanelDelegate;
2931
2932impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
2933    fn active_text_thread_editor(
2934        &self,
2935        workspace: &mut Workspace,
2936        _window: &mut Window,
2937        cx: &mut Context<Workspace>,
2938    ) -> Option<Entity<TextThreadEditor>> {
2939        let panel = workspace.panel::<AgentPanel>(cx)?;
2940        panel.read(cx).active_text_thread_editor()
2941    }
2942
2943    fn open_local_text_thread(
2944        &self,
2945        workspace: &mut Workspace,
2946        path: Arc<Path>,
2947        window: &mut Window,
2948        cx: &mut Context<Workspace>,
2949    ) -> Task<Result<()>> {
2950        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
2951            return Task::ready(Err(anyhow!("Agent panel not found")));
2952        };
2953
2954        panel.update(cx, |panel, cx| {
2955            panel.open_saved_text_thread(path, window, cx)
2956        })
2957    }
2958
2959    fn open_remote_text_thread(
2960        &self,
2961        _workspace: &mut Workspace,
2962        _text_thread_id: assistant_text_thread::TextThreadId,
2963        _window: &mut Window,
2964        _cx: &mut Context<Workspace>,
2965    ) -> Task<Result<Entity<TextThreadEditor>>> {
2966        Task::ready(Err(anyhow!("opening remote context not implemented")))
2967    }
2968
2969    fn quote_selection(
2970        &self,
2971        workspace: &mut Workspace,
2972        selection_ranges: Vec<Range<Anchor>>,
2973        buffer: Entity<MultiBuffer>,
2974        window: &mut Window,
2975        cx: &mut Context<Workspace>,
2976    ) {
2977        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
2978            return;
2979        };
2980
2981        if !panel.focus_handle(cx).contains_focused(window, cx) {
2982            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
2983        }
2984
2985        panel.update(cx, |_, cx| {
2986            // Wait to create a new context until the workspace is no longer
2987            // being updated.
2988            cx.defer_in(window, move |panel, window, cx| {
2989                if let Some(thread_view) = panel.active_thread_view() {
2990                    thread_view.update(cx, |thread_view, cx| {
2991                        thread_view.insert_selections(window, cx);
2992                    });
2993                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
2994                    let snapshot = buffer.read(cx).snapshot(cx);
2995                    let selection_ranges = selection_ranges
2996                        .into_iter()
2997                        .map(|range| range.to_point(&snapshot))
2998                        .collect::<Vec<_>>();
2999
3000                    text_thread_editor.update(cx, |text_thread_editor, cx| {
3001                        text_thread_editor.quote_ranges(selection_ranges, snapshot, window, cx)
3002                    });
3003                }
3004            });
3005        });
3006    }
3007}
3008
3009struct OnboardingUpsell;
3010
3011impl Dismissable for OnboardingUpsell {
3012    const KEY: &'static str = "dismissed-trial-upsell";
3013}
3014
3015struct TrialEndUpsell;
3016
3017impl Dismissable for TrialEndUpsell {
3018    const KEY: &'static str = "dismissed-trial-end-upsell";
3019}
3020
3021#[cfg(feature = "test-support")]
3022impl AgentPanel {
3023    /// Opens an external thread using an arbitrary AgentServer.
3024    ///
3025    /// This is a test-only helper that allows visual tests and integration tests
3026    /// to inject a stub server without modifying production code paths.
3027    /// Not compiled into production builds.
3028    pub fn open_external_thread_with_server(
3029        &mut self,
3030        server: Rc<dyn AgentServer>,
3031        window: &mut Window,
3032        cx: &mut Context<Self>,
3033    ) {
3034        let workspace = self.workspace.clone();
3035        let project = self.project.clone();
3036
3037        let ext_agent = ExternalAgent::Custom {
3038            name: server.name(),
3039        };
3040
3041        self._external_thread(
3042            server, None, None, workspace, project, false, ext_agent, window, cx,
3043        );
3044    }
3045
3046    /// Returns the currently active thread view, if any.
3047    ///
3048    /// This is a test-only accessor that exposes the private `active_thread_view()`
3049    /// method for test assertions. Not compiled into production builds.
3050    pub fn active_thread_view_for_tests(&self) -> Option<&Entity<AcpThreadView>> {
3051        self.active_thread_view()
3052    }
3053}