agent_panel.rs

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