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