agent_panel.rs

   1use std::ops::{Not, Range};
   2use std::path::Path;
   3use std::rc::Rc;
   4use std::sync::Arc;
   5use std::time::Duration;
   6
   7use agent2::{DbThreadMetadata, HistoryEntry};
   8use db::kvp::{Dismissable, KEY_VALUE_STORE};
   9use serde::{Deserialize, Serialize};
  10
  11use crate::acp::{AcpThreadHistory, ThreadHistoryEvent};
  12use crate::agent_diff::AgentDiffThread;
  13use crate::{
  14    AddContextServer, AgentDiffPane, ContinueThread, ContinueWithBurnMode,
  15    DeleteRecentlyOpenThread, ExpandMessageEditor, Follow, InlineAssistant, NewTextThread,
  16    NewThread, OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell,
  17    ResetTrialUpsell, ToggleBurnMode, ToggleContextPicker, ToggleNavigationMenu,
  18    ToggleNewThreadMenu, ToggleOptionsMenu,
  19    acp::AcpThreadView,
  20    active_thread::{self, ActiveThread, ActiveThreadEvent},
  21    agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
  22    agent_diff::AgentDiff,
  23    message_editor::{MessageEditor, MessageEditorEvent},
  24    slash_command::SlashCommandCompletionProvider,
  25    text_thread_editor::{
  26        AgentPanelDelegate, TextThreadEditor, humanize_token_count, make_lsp_adapter_delegate,
  27        render_remaining_tokens,
  28    },
  29    thread_history::{HistoryEntryElement, ThreadHistory},
  30    ui::{AgentOnboardingModal, EndTrialUpsell},
  31};
  32use crate::{ExternalAgent, NewExternalAgentThread};
  33use agent::{
  34    Thread, ThreadError, ThreadEvent, ThreadId, ThreadSummary, TokenUsageRatio,
  35    context_store::ContextStore,
  36    history_store::{HistoryEntryId, HistoryStore},
  37    thread_store::{TextThreadStore, ThreadStore},
  38};
  39use agent_settings::{AgentDockPosition, AgentSettings, CompletionMode, DefaultView};
  40use ai_onboarding::AgentPanelOnboarding;
  41use anyhow::{Result, anyhow};
  42use assistant_context::{AssistantContext, ContextEvent, ContextSummary};
  43use assistant_slash_command::SlashCommandWorkingSet;
  44use assistant_tool::ToolWorkingSet;
  45use client::{UserStore, zed_urls};
  46use cloud_llm_client::{CompletionIntent, Plan, UsageLimit};
  47use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
  48use feature_flags::{self, AcpFeatureFlag, ClaudeCodeFeatureFlag, FeatureFlagAppExt};
  49use fs::Fs;
  50use gpui::{
  51    Action, Animation, AnimationExt as _, AnyElement, App, AsyncWindowContext, ClipboardItem,
  52    Corner, DismissEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, KeyContext,
  53    Pixels, Subscription, Task, UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
  54};
  55use language::LanguageRegistry;
  56use language_model::{
  57    ConfigurationError, ConfiguredModel, LanguageModelProviderTosView, LanguageModelRegistry,
  58};
  59use project::{DisableAiSettings, Project, ProjectPath, Worktree};
  60use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
  61use rules_library::{RulesLibrary, open_rules_library};
  62use search::{BufferSearchBar, buffer_search};
  63use settings::{Settings, update_settings_file};
  64use theme::ThemeSettings;
  65use time::UtcOffset;
  66use ui::utils::WithRemSize;
  67use ui::{
  68    Banner, Callout, ContextMenu, ContextMenuEntry, Divider, ElevationIndex, KeyBinding,
  69    PopoverMenu, PopoverMenuHandle, ProgressBar, Tab, Tooltip, prelude::*,
  70};
  71use util::ResultExt as _;
  72use workspace::{
  73    CollaboratorId, DraggedSelection, DraggedTab, ToggleZoom, ToolbarItemView, Workspace,
  74    dock::{DockPosition, Panel, PanelEvent},
  75};
  76use zed_actions::{
  77    DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
  78    agent::{OpenOnboardingModal, OpenSettings, ResetOnboarding, ToggleModelSelector},
  79    assistant::{OpenRulesLibrary, ToggleFocus},
  80};
  81
  82const AGENT_PANEL_KEY: &str = "agent_panel";
  83
  84#[derive(Serialize, Deserialize)]
  85struct SerializedAgentPanel {
  86    width: Option<Pixels>,
  87    selected_agent: Option<AgentType>,
  88}
  89
  90pub fn init(cx: &mut App) {
  91    cx.observe_new(
  92        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
  93            workspace
  94                .register_action(|workspace, action: &NewThread, window, cx| {
  95                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
  96                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
  97                        workspace.focus_panel::<AgentPanel>(window, cx);
  98                    }
  99                })
 100                .register_action(|workspace, _: &OpenHistory, window, cx| {
 101                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 102                        workspace.focus_panel::<AgentPanel>(window, cx);
 103                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
 104                    }
 105                })
 106                .register_action(|workspace, _: &OpenSettings, window, cx| {
 107                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 108                        workspace.focus_panel::<AgentPanel>(window, cx);
 109                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
 110                    }
 111                })
 112                .register_action(|workspace, _: &NewTextThread, window, cx| {
 113                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 114                        workspace.focus_panel::<AgentPanel>(window, cx);
 115                        panel.update(cx, |panel, cx| panel.new_prompt_editor(window, cx));
 116                    }
 117                })
 118                .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
 119                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 120                        workspace.focus_panel::<AgentPanel>(window, cx);
 121                        panel.update(cx, |panel, cx| {
 122                            panel.external_thread(action.agent, None, window, cx)
 123                        });
 124                    }
 125                })
 126                .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
 127                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 128                        workspace.focus_panel::<AgentPanel>(window, cx);
 129                        panel.update(cx, |panel, cx| {
 130                            panel.deploy_rules_library(action, window, cx)
 131                        });
 132                    }
 133                })
 134                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
 135                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 136                        workspace.focus_panel::<AgentPanel>(window, cx);
 137                        match &panel.read(cx).active_view {
 138                            ActiveView::Thread { thread, .. } => {
 139                                let thread = thread.read(cx).thread().clone();
 140                                AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
 141                            }
 142                            ActiveView::ExternalAgentThread { .. }
 143                            | ActiveView::TextThread { .. }
 144                            | ActiveView::History
 145                            | ActiveView::Configuration => {}
 146                        }
 147                    }
 148                })
 149                .register_action(|workspace, _: &Follow, window, cx| {
 150                    workspace.follow(CollaboratorId::Agent, window, cx);
 151                })
 152                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
 153                    let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 154                        return;
 155                    };
 156                    workspace.focus_panel::<AgentPanel>(window, cx);
 157                    panel.update(cx, |panel, cx| {
 158                        if let Some(message_editor) = panel.active_message_editor() {
 159                            message_editor.update(cx, |editor, cx| {
 160                                editor.expand_message_editor(&ExpandMessageEditor, window, cx);
 161                            });
 162                        }
 163                    });
 164                })
 165                .register_action(|workspace, _: &ToggleNavigationMenu, 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_navigation_menu(&ToggleNavigationMenu, window, cx);
 170                        });
 171                    }
 172                })
 173                .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
 174                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 175                        workspace.focus_panel::<AgentPanel>(window, cx);
 176                        panel.update(cx, |panel, cx| {
 177                            panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
 178                        });
 179                    }
 180                })
 181                .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
 182                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 183                        workspace.focus_panel::<AgentPanel>(window, cx);
 184                        panel.update(cx, |panel, cx| {
 185                            panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
 186                        });
 187                    }
 188                })
 189                .register_action(|workspace, _: &OpenOnboardingModal, window, cx| {
 190                    AgentOnboardingModal::toggle(workspace, window, cx)
 191                })
 192                .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
 193                    window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
 194                    window.refresh();
 195                })
 196                .register_action(|_workspace, _: &ResetTrialUpsell, _window, cx| {
 197                    OnboardingUpsell::set_dismissed(false, cx);
 198                })
 199                .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
 200                    TrialEndUpsell::set_dismissed(false, cx);
 201                });
 202        },
 203    )
 204    .detach();
 205}
 206
 207enum ActiveView {
 208    Thread {
 209        thread: Entity<ActiveThread>,
 210        change_title_editor: Entity<Editor>,
 211        message_editor: Entity<MessageEditor>,
 212        _subscriptions: Vec<gpui::Subscription>,
 213    },
 214    ExternalAgentThread {
 215        thread_view: Entity<AcpThreadView>,
 216    },
 217    TextThread {
 218        context_editor: Entity<TextThreadEditor>,
 219        title_editor: Entity<Editor>,
 220        buffer_search_bar: Entity<BufferSearchBar>,
 221        _subscriptions: Vec<gpui::Subscription>,
 222    },
 223    History,
 224    Configuration,
 225}
 226
 227enum WhichFontSize {
 228    AgentFont,
 229    BufferFont,
 230    None,
 231}
 232
 233#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
 234pub enum AgentType {
 235    #[default]
 236    Zed,
 237    TextThread,
 238    Gemini,
 239    ClaudeCode,
 240    NativeAgent,
 241}
 242
 243impl AgentType {
 244    fn label(self) -> impl Into<SharedString> {
 245        match self {
 246            Self::Zed | Self::TextThread => "Zed Agent",
 247            Self::NativeAgent => "Agent 2",
 248            Self::Gemini => "Google Gemini",
 249            Self::ClaudeCode => "Claude Code",
 250        }
 251    }
 252
 253    fn icon(self) -> IconName {
 254        match self {
 255            Self::Zed | Self::TextThread => IconName::AiZed,
 256            Self::NativeAgent => IconName::ZedAssistant,
 257            Self::Gemini => IconName::AiGemini,
 258            Self::ClaudeCode => IconName::AiClaude,
 259        }
 260    }
 261}
 262
 263impl ActiveView {
 264    pub fn which_font_size_used(&self) -> WhichFontSize {
 265        match self {
 266            ActiveView::Thread { .. }
 267            | ActiveView::ExternalAgentThread { .. }
 268            | ActiveView::History => WhichFontSize::AgentFont,
 269            ActiveView::TextThread { .. } => WhichFontSize::BufferFont,
 270            ActiveView::Configuration => WhichFontSize::None,
 271        }
 272    }
 273
 274    pub fn thread(
 275        active_thread: Entity<ActiveThread>,
 276        message_editor: Entity<MessageEditor>,
 277        window: &mut Window,
 278        cx: &mut Context<AgentPanel>,
 279    ) -> Self {
 280        let summary = active_thread.read(cx).summary(cx).or_default();
 281
 282        let editor = cx.new(|cx| {
 283            let mut editor = Editor::single_line(window, cx);
 284            editor.set_text(summary.clone(), window, cx);
 285            editor
 286        });
 287
 288        let subscriptions = vec![
 289            cx.subscribe(&message_editor, |this, _, event, cx| match event {
 290                MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
 291                    cx.notify();
 292                }
 293                MessageEditorEvent::ScrollThreadToBottom => match &this.active_view {
 294                    ActiveView::Thread { thread, .. } => {
 295                        thread.update(cx, |thread, cx| {
 296                            thread.scroll_to_bottom(cx);
 297                        });
 298                    }
 299                    ActiveView::ExternalAgentThread { .. } => {}
 300                    ActiveView::TextThread { .. }
 301                    | ActiveView::History
 302                    | ActiveView::Configuration => {}
 303                },
 304            }),
 305            window.subscribe(&editor, cx, {
 306                {
 307                    let thread = active_thread.clone();
 308                    move |editor, event, window, cx| match event {
 309                        EditorEvent::BufferEdited => {
 310                            let new_summary = editor.read(cx).text(cx);
 311
 312                            thread.update(cx, |thread, cx| {
 313                                thread.thread().update(cx, |thread, cx| {
 314                                    thread.set_summary(new_summary, cx);
 315                                });
 316                            })
 317                        }
 318                        EditorEvent::Blurred => {
 319                            if editor.read(cx).text(cx).is_empty() {
 320                                let summary = thread.read(cx).summary(cx).or_default();
 321
 322                                editor.update(cx, |editor, cx| {
 323                                    editor.set_text(summary, window, cx);
 324                                });
 325                            }
 326                        }
 327                        _ => {}
 328                    }
 329                }
 330            }),
 331            cx.subscribe(&active_thread, |_, _, event, cx| match &event {
 332                ActiveThreadEvent::EditingMessageTokenCountChanged => {
 333                    cx.notify();
 334                }
 335            }),
 336            cx.subscribe_in(&active_thread.read(cx).thread().clone(), window, {
 337                let editor = editor.clone();
 338                move |_, thread, event, window, cx| match event {
 339                    ThreadEvent::SummaryGenerated => {
 340                        let summary = thread.read(cx).summary().or_default();
 341
 342                        editor.update(cx, |editor, cx| {
 343                            editor.set_text(summary, window, cx);
 344                        })
 345                    }
 346                    ThreadEvent::MessageAdded(_) => {
 347                        cx.notify();
 348                    }
 349                    _ => {}
 350                }
 351            }),
 352        ];
 353
 354        Self::Thread {
 355            change_title_editor: editor,
 356            thread: active_thread,
 357            message_editor,
 358            _subscriptions: subscriptions,
 359        }
 360    }
 361
 362    pub fn prompt_editor(
 363        context_editor: Entity<TextThreadEditor>,
 364        history_store: Entity<HistoryStore>,
 365        acp_history_store: Entity<agent2::HistoryStore>,
 366        language_registry: Arc<LanguageRegistry>,
 367        window: &mut Window,
 368        cx: &mut App,
 369    ) -> Self {
 370        let title = context_editor.read(cx).title(cx).to_string();
 371
 372        let editor = cx.new(|cx| {
 373            let mut editor = Editor::single_line(window, cx);
 374            editor.set_text(title, window, cx);
 375            editor
 376        });
 377
 378        // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
 379        // cause a custom summary to be set. The presence of this custom summary would cause
 380        // summarization to not happen.
 381        let mut suppress_first_edit = true;
 382
 383        let subscriptions = vec![
 384            window.subscribe(&editor, cx, {
 385                {
 386                    let context_editor = context_editor.clone();
 387                    move |editor, event, window, cx| match event {
 388                        EditorEvent::BufferEdited => {
 389                            if suppress_first_edit {
 390                                suppress_first_edit = false;
 391                                return;
 392                            }
 393                            let new_summary = editor.read(cx).text(cx);
 394
 395                            context_editor.update(cx, |context_editor, cx| {
 396                                context_editor
 397                                    .context()
 398                                    .update(cx, |assistant_context, cx| {
 399                                        assistant_context.set_custom_summary(new_summary, cx);
 400                                    })
 401                            })
 402                        }
 403                        EditorEvent::Blurred => {
 404                            if editor.read(cx).text(cx).is_empty() {
 405                                let summary = context_editor
 406                                    .read(cx)
 407                                    .context()
 408                                    .read(cx)
 409                                    .summary()
 410                                    .or_default();
 411
 412                                editor.update(cx, |editor, cx| {
 413                                    editor.set_text(summary, window, cx);
 414                                });
 415                            }
 416                        }
 417                        _ => {}
 418                    }
 419                }
 420            }),
 421            window.subscribe(&context_editor.read(cx).context().clone(), cx, {
 422                let editor = editor.clone();
 423                move |assistant_context, event, window, cx| match event {
 424                    ContextEvent::SummaryGenerated => {
 425                        let summary = assistant_context.read(cx).summary().or_default();
 426
 427                        editor.update(cx, |editor, cx| {
 428                            editor.set_text(summary, window, cx);
 429                        })
 430                    }
 431                    ContextEvent::PathChanged { old_path, new_path } => {
 432                        history_store.update(cx, |history_store, cx| {
 433                            if let Some(old_path) = old_path {
 434                                history_store
 435                                    .replace_recently_opened_text_thread(old_path, new_path, cx);
 436                            } else {
 437                                history_store.push_recently_opened_entry(
 438                                    HistoryEntryId::Context(new_path.clone()),
 439                                    cx,
 440                                );
 441                            }
 442                        });
 443
 444                        acp_history_store.update(cx, |history_store, cx| {
 445                            if let Some(old_path) = old_path {
 446                                history_store
 447                                    .replace_recently_opened_text_thread(old_path, new_path, cx);
 448                            } else {
 449                                history_store.push_recently_opened_entry(
 450                                    agent2::HistoryEntryId::TextThread(new_path.clone()),
 451                                    cx,
 452                                );
 453                            }
 454                        });
 455                    }
 456                    _ => {}
 457                }
 458            }),
 459        ];
 460
 461        let buffer_search_bar =
 462            cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
 463        buffer_search_bar.update(cx, |buffer_search_bar, cx| {
 464            buffer_search_bar.set_active_pane_item(Some(&context_editor), window, cx)
 465        });
 466
 467        Self::TextThread {
 468            context_editor,
 469            title_editor: editor,
 470            buffer_search_bar,
 471            _subscriptions: subscriptions,
 472        }
 473    }
 474}
 475
 476pub struct AgentPanel {
 477    workspace: WeakEntity<Workspace>,
 478    user_store: Entity<UserStore>,
 479    project: Entity<Project>,
 480    fs: Arc<dyn Fs>,
 481    language_registry: Arc<LanguageRegistry>,
 482    thread_store: Entity<ThreadStore>,
 483    acp_history: Entity<AcpThreadHistory>,
 484    acp_history_store: Entity<agent2::HistoryStore>,
 485    _default_model_subscription: Subscription,
 486    context_store: Entity<TextThreadStore>,
 487    prompt_store: Option<Entity<PromptStore>>,
 488    inline_assist_context_store: Entity<ContextStore>,
 489    configuration: Option<Entity<AgentConfiguration>>,
 490    configuration_subscription: Option<Subscription>,
 491    local_timezone: UtcOffset,
 492    active_view: ActiveView,
 493    previous_view: Option<ActiveView>,
 494    history_store: Entity<HistoryStore>,
 495    history: Entity<ThreadHistory>,
 496    hovered_recent_history_item: Option<usize>,
 497    new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
 498    agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
 499    assistant_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
 500    assistant_navigation_menu: Option<Entity<ContextMenu>>,
 501    width: Option<Pixels>,
 502    height: Option<Pixels>,
 503    zoomed: bool,
 504    pending_serialization: Option<Task<Result<()>>>,
 505    onboarding: Entity<AgentPanelOnboarding>,
 506    selected_agent: AgentType,
 507}
 508
 509impl AgentPanel {
 510    fn serialize(&mut self, cx: &mut Context<Self>) {
 511        let width = self.width;
 512        let selected_agent = self.selected_agent;
 513        self.pending_serialization = Some(cx.background_spawn(async move {
 514            KEY_VALUE_STORE
 515                .write_kvp(
 516                    AGENT_PANEL_KEY.into(),
 517                    serde_json::to_string(&SerializedAgentPanel {
 518                        width,
 519                        selected_agent: Some(selected_agent),
 520                    })?,
 521                )
 522                .await?;
 523            anyhow::Ok(())
 524        }));
 525    }
 526    pub fn load(
 527        workspace: WeakEntity<Workspace>,
 528        prompt_builder: Arc<PromptBuilder>,
 529        mut cx: AsyncWindowContext,
 530    ) -> Task<Result<Entity<Self>>> {
 531        let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
 532        cx.spawn(async move |cx| {
 533            let prompt_store = match prompt_store {
 534                Ok(prompt_store) => prompt_store.await.ok(),
 535                Err(_) => None,
 536            };
 537            let tools = cx.new(|_| ToolWorkingSet::default())?;
 538            let thread_store = workspace
 539                .update(cx, |workspace, cx| {
 540                    let project = workspace.project().clone();
 541                    ThreadStore::load(
 542                        project,
 543                        tools.clone(),
 544                        prompt_store.clone(),
 545                        prompt_builder.clone(),
 546                        cx,
 547                    )
 548                })?
 549                .await?;
 550
 551            let slash_commands = Arc::new(SlashCommandWorkingSet::default());
 552            let context_store = workspace
 553                .update(cx, |workspace, cx| {
 554                    let project = workspace.project().clone();
 555                    assistant_context::ContextStore::new(
 556                        project,
 557                        prompt_builder.clone(),
 558                        slash_commands,
 559                        cx,
 560                    )
 561                })?
 562                .await?;
 563
 564            let serialized_panel = if let Some(panel) = cx
 565                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(AGENT_PANEL_KEY) })
 566                .await
 567                .log_err()
 568                .flatten()
 569            {
 570                Some(serde_json::from_str::<SerializedAgentPanel>(&panel)?)
 571            } else {
 572                None
 573            };
 574
 575            let panel = workspace.update_in(cx, |workspace, window, cx| {
 576                let panel = cx.new(|cx| {
 577                    Self::new(
 578                        workspace,
 579                        thread_store,
 580                        context_store,
 581                        prompt_store,
 582                        window,
 583                        cx,
 584                    )
 585                });
 586                if let Some(serialized_panel) = serialized_panel {
 587                    panel.update(cx, |panel, cx| {
 588                        panel.width = serialized_panel.width.map(|w| w.round());
 589                        if let Some(selected_agent) = serialized_panel.selected_agent {
 590                            panel.selected_agent = selected_agent;
 591                            panel.new_agent_thread(selected_agent, window, cx);
 592                        }
 593                        cx.notify();
 594                    });
 595                }
 596                panel
 597            })?;
 598
 599            Ok(panel)
 600        })
 601    }
 602
 603    fn new(
 604        workspace: &Workspace,
 605        thread_store: Entity<ThreadStore>,
 606        context_store: Entity<TextThreadStore>,
 607        prompt_store: Option<Entity<PromptStore>>,
 608        window: &mut Window,
 609        cx: &mut Context<Self>,
 610    ) -> Self {
 611        let thread = thread_store.update(cx, |this, cx| this.create_thread(cx));
 612        let fs = workspace.app_state().fs.clone();
 613        let user_store = workspace.app_state().user_store.clone();
 614        let project = workspace.project();
 615        let language_registry = project.read(cx).languages().clone();
 616        let client = workspace.client().clone();
 617        let workspace = workspace.weak_handle();
 618        let weak_self = cx.entity().downgrade();
 619
 620        let message_editor_context_store =
 621            cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
 622        let inline_assist_context_store =
 623            cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
 624
 625        let thread_id = thread.read(cx).id().clone();
 626
 627        let history_store = cx.new(|cx| {
 628            HistoryStore::new(
 629                thread_store.clone(),
 630                context_store.clone(),
 631                [HistoryEntryId::Thread(thread_id)],
 632                cx,
 633            )
 634        });
 635
 636        let message_editor = cx.new(|cx| {
 637            MessageEditor::new(
 638                fs.clone(),
 639                workspace.clone(),
 640                message_editor_context_store.clone(),
 641                prompt_store.clone(),
 642                thread_store.downgrade(),
 643                context_store.downgrade(),
 644                Some(history_store.downgrade()),
 645                thread.clone(),
 646                window,
 647                cx,
 648            )
 649        });
 650
 651        let acp_history_store =
 652            cx.new(|cx| agent2::HistoryStore::new(context_store.clone(), [], cx));
 653        let acp_history = cx.new(|cx| AcpThreadHistory::new(acp_history_store.clone(), window, cx));
 654        cx.subscribe_in(
 655            &acp_history,
 656            window,
 657            |this, _, event, window, cx| match event {
 658                ThreadHistoryEvent::Open(HistoryEntry::AcpThread(thread)) => {
 659                    this.external_thread(
 660                        Some(crate::ExternalAgent::NativeAgent),
 661                        Some(thread.clone()),
 662                        window,
 663                        cx,
 664                    );
 665                }
 666                ThreadHistoryEvent::Open(HistoryEntry::TextThread(thread)) => {
 667                    this.open_saved_prompt_editor(thread.path.clone(), window, cx)
 668                        .detach_and_log_err(cx);
 669                }
 670            },
 671        )
 672        .detach();
 673
 674        cx.observe(&history_store, |_, _, cx| cx.notify()).detach();
 675
 676        let active_thread = cx.new(|cx| {
 677            ActiveThread::new(
 678                thread.clone(),
 679                thread_store.clone(),
 680                context_store.clone(),
 681                message_editor_context_store.clone(),
 682                language_registry.clone(),
 683                workspace.clone(),
 684                window,
 685                cx,
 686            )
 687        });
 688
 689        let panel_type = AgentSettings::get_global(cx).default_view;
 690        let active_view = match panel_type {
 691            DefaultView::Thread => ActiveView::thread(active_thread, message_editor, window, cx),
 692            DefaultView::TextThread => {
 693                let context =
 694                    context_store.update(cx, |context_store, cx| context_store.create(cx));
 695                let lsp_adapter_delegate = make_lsp_adapter_delegate(&project.clone(), cx).unwrap();
 696                let context_editor = cx.new(|cx| {
 697                    let mut editor = TextThreadEditor::for_context(
 698                        context,
 699                        fs.clone(),
 700                        workspace.clone(),
 701                        project.clone(),
 702                        lsp_adapter_delegate,
 703                        window,
 704                        cx,
 705                    );
 706                    editor.insert_default_prompt(window, cx);
 707                    editor
 708                });
 709                ActiveView::prompt_editor(
 710                    context_editor,
 711                    history_store.clone(),
 712                    acp_history_store.clone(),
 713                    language_registry.clone(),
 714                    window,
 715                    cx,
 716                )
 717            }
 718        };
 719
 720        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 721
 722        let weak_panel = weak_self.clone();
 723
 724        window.defer(cx, move |window, cx| {
 725            let panel = weak_panel.clone();
 726            let assistant_navigation_menu =
 727                ContextMenu::build_persistent(window, cx, move |mut menu, _window, cx| {
 728                    if let Some(panel) = panel.upgrade() {
 729                        if cx.has_flag::<AcpFeatureFlag>() {
 730                            menu = Self::populate_recently_opened_menu_section_new(menu, panel, cx);
 731                        } else {
 732                            menu = Self::populate_recently_opened_menu_section_old(menu, panel, cx);
 733                        }
 734                    }
 735                    menu.action("View All", Box::new(OpenHistory))
 736                        .end_slot_action(DeleteRecentlyOpenThread.boxed_clone())
 737                        .fixed_width(px(320.).into())
 738                        .keep_open_on_confirm(false)
 739                        .key_context("NavigationMenu")
 740                });
 741            weak_panel
 742                .update(cx, |panel, cx| {
 743                    cx.subscribe_in(
 744                        &assistant_navigation_menu,
 745                        window,
 746                        |_, menu, _: &DismissEvent, window, cx| {
 747                            menu.update(cx, |menu, _| {
 748                                menu.clear_selected();
 749                            });
 750                            cx.focus_self(window);
 751                        },
 752                    )
 753                    .detach();
 754                    panel.assistant_navigation_menu = Some(assistant_navigation_menu);
 755                })
 756                .ok();
 757        });
 758
 759        let _default_model_subscription =
 760            cx.subscribe(
 761                &LanguageModelRegistry::global(cx),
 762                |this, _, event: &language_model::Event, cx| {
 763                    if let language_model::Event::DefaultModelChanged = event {
 764                        match &this.active_view {
 765                            ActiveView::Thread { thread, .. } => {
 766                                thread.read(cx).thread().clone().update(cx, |thread, cx| {
 767                                    thread.get_or_init_configured_model(cx)
 768                                });
 769                            }
 770                            ActiveView::ExternalAgentThread { .. }
 771                            | ActiveView::TextThread { .. }
 772                            | ActiveView::History
 773                            | ActiveView::Configuration => {}
 774                        }
 775                    }
 776                },
 777            );
 778
 779        let onboarding = cx.new(|cx| {
 780            AgentPanelOnboarding::new(
 781                user_store.clone(),
 782                client,
 783                |_window, cx| {
 784                    OnboardingUpsell::set_dismissed(true, cx);
 785                },
 786                cx,
 787            )
 788        });
 789
 790        Self {
 791            active_view,
 792            workspace,
 793            user_store,
 794            project: project.clone(),
 795            fs: fs.clone(),
 796            language_registry,
 797            thread_store: thread_store.clone(),
 798            _default_model_subscription,
 799            context_store,
 800            prompt_store,
 801            configuration: None,
 802            configuration_subscription: None,
 803            local_timezone: UtcOffset::from_whole_seconds(
 804                chrono::Local::now().offset().local_minus_utc(),
 805            )
 806            .unwrap(),
 807            inline_assist_context_store,
 808            previous_view: None,
 809            history_store: history_store.clone(),
 810            history: cx.new(|cx| ThreadHistory::new(weak_self, history_store, window, cx)),
 811            hovered_recent_history_item: None,
 812            new_thread_menu_handle: PopoverMenuHandle::default(),
 813            agent_panel_menu_handle: PopoverMenuHandle::default(),
 814            assistant_navigation_menu_handle: PopoverMenuHandle::default(),
 815            assistant_navigation_menu: None,
 816            width: None,
 817            height: None,
 818            zoomed: false,
 819            pending_serialization: None,
 820            onboarding,
 821            acp_history,
 822            acp_history_store,
 823            selected_agent: AgentType::default(),
 824        }
 825    }
 826
 827    pub fn toggle_focus(
 828        workspace: &mut Workspace,
 829        _: &ToggleFocus,
 830        window: &mut Window,
 831        cx: &mut Context<Workspace>,
 832    ) {
 833        if workspace
 834            .panel::<Self>(cx)
 835            .is_some_and(|panel| panel.read(cx).enabled(cx))
 836            && !DisableAiSettings::get_global(cx).disable_ai
 837        {
 838            workspace.toggle_panel_focus::<Self>(window, cx);
 839        }
 840    }
 841
 842    pub(crate) fn local_timezone(&self) -> UtcOffset {
 843        self.local_timezone
 844    }
 845
 846    pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
 847        &self.prompt_store
 848    }
 849
 850    pub(crate) fn inline_assist_context_store(&self) -> &Entity<ContextStore> {
 851        &self.inline_assist_context_store
 852    }
 853
 854    pub(crate) fn thread_store(&self) -> &Entity<ThreadStore> {
 855        &self.thread_store
 856    }
 857
 858    pub(crate) fn text_thread_store(&self) -> &Entity<TextThreadStore> {
 859        &self.context_store
 860    }
 861
 862    fn cancel(&mut self, _: &editor::actions::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 863        match &self.active_view {
 864            ActiveView::Thread { thread, .. } => {
 865                thread.update(cx, |thread, cx| thread.cancel_last_completion(window, cx));
 866            }
 867            ActiveView::ExternalAgentThread { .. }
 868            | ActiveView::TextThread { .. }
 869            | ActiveView::History
 870            | ActiveView::Configuration => {}
 871        }
 872    }
 873
 874    fn active_message_editor(&self) -> Option<&Entity<MessageEditor>> {
 875        match &self.active_view {
 876            ActiveView::Thread { message_editor, .. } => Some(message_editor),
 877            ActiveView::ExternalAgentThread { .. }
 878            | ActiveView::TextThread { .. }
 879            | ActiveView::History
 880            | ActiveView::Configuration => None,
 881        }
 882    }
 883
 884    fn new_thread(&mut self, action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
 885        // Preserve chat box text when using creating new thread
 886        let preserved_text = self
 887            .active_message_editor()
 888            .map(|editor| editor.read(cx).get_text(cx).trim().to_string());
 889
 890        let thread = self
 891            .thread_store
 892            .update(cx, |this, cx| this.create_thread(cx));
 893
 894        let context_store = cx.new(|_cx| {
 895            ContextStore::new(
 896                self.project.downgrade(),
 897                Some(self.thread_store.downgrade()),
 898            )
 899        });
 900
 901        if let Some(other_thread_id) = action.from_thread_id.clone() {
 902            let other_thread_task = self.thread_store.update(cx, |this, cx| {
 903                this.open_thread(&other_thread_id, window, cx)
 904            });
 905
 906            cx.spawn({
 907                let context_store = context_store.clone();
 908
 909                async move |_panel, cx| {
 910                    let other_thread = other_thread_task.await?;
 911
 912                    context_store.update(cx, |this, cx| {
 913                        this.add_thread(other_thread, false, cx);
 914                    })?;
 915                    anyhow::Ok(())
 916                }
 917            })
 918            .detach_and_log_err(cx);
 919        }
 920
 921        let active_thread = cx.new(|cx| {
 922            ActiveThread::new(
 923                thread.clone(),
 924                self.thread_store.clone(),
 925                self.context_store.clone(),
 926                context_store.clone(),
 927                self.language_registry.clone(),
 928                self.workspace.clone(),
 929                window,
 930                cx,
 931            )
 932        });
 933
 934        let message_editor = cx.new(|cx| {
 935            MessageEditor::new(
 936                self.fs.clone(),
 937                self.workspace.clone(),
 938                context_store.clone(),
 939                self.prompt_store.clone(),
 940                self.thread_store.downgrade(),
 941                self.context_store.downgrade(),
 942                Some(self.history_store.downgrade()),
 943                thread.clone(),
 944                window,
 945                cx,
 946            )
 947        });
 948
 949        if let Some(text) = preserved_text {
 950            message_editor.update(cx, |editor, cx| {
 951                editor.set_text(text, window, cx);
 952            });
 953        }
 954
 955        message_editor.focus_handle(cx).focus(window);
 956
 957        let thread_view = ActiveView::thread(active_thread.clone(), message_editor, window, cx);
 958        self.set_active_view(thread_view, window, cx);
 959
 960        AgentDiff::set_active_thread(&self.workspace, thread.clone(), window, cx);
 961    }
 962
 963    fn new_prompt_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 964        let context = self
 965            .context_store
 966            .update(cx, |context_store, cx| context_store.create(cx));
 967        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
 968            .log_err()
 969            .flatten();
 970
 971        let context_editor = cx.new(|cx| {
 972            let mut editor = TextThreadEditor::for_context(
 973                context,
 974                self.fs.clone(),
 975                self.workspace.clone(),
 976                self.project.clone(),
 977                lsp_adapter_delegate,
 978                window,
 979                cx,
 980            );
 981            editor.insert_default_prompt(window, cx);
 982            editor
 983        });
 984
 985        self.set_active_view(
 986            ActiveView::prompt_editor(
 987                context_editor.clone(),
 988                self.history_store.clone(),
 989                self.acp_history_store.clone(),
 990                self.language_registry.clone(),
 991                window,
 992                cx,
 993            ),
 994            window,
 995            cx,
 996        );
 997        context_editor.focus_handle(cx).focus(window);
 998    }
 999
1000    fn external_thread(
1001        &mut self,
1002        agent_choice: Option<crate::ExternalAgent>,
1003        resume_thread: Option<DbThreadMetadata>,
1004        window: &mut Window,
1005        cx: &mut Context<Self>,
1006    ) {
1007        let workspace = self.workspace.clone();
1008        let project = self.project.clone();
1009        let fs = self.fs.clone();
1010
1011        const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
1012
1013        #[derive(Default, Serialize, Deserialize)]
1014        struct LastUsedExternalAgent {
1015            agent: crate::ExternalAgent,
1016        }
1017
1018        let thread_store = self.thread_store.clone();
1019        let text_thread_store = self.context_store.clone();
1020        let history = self.acp_history_store.clone();
1021
1022        cx.spawn_in(window, async move |this, cx| {
1023            let ext_agent = match agent_choice {
1024                Some(agent) => {
1025                    cx.background_spawn(async move {
1026                        if let Some(serialized) =
1027                            serde_json::to_string(&LastUsedExternalAgent { agent }).log_err()
1028                        {
1029                            KEY_VALUE_STORE
1030                                .write_kvp(LAST_USED_EXTERNAL_AGENT_KEY.to_string(), serialized)
1031                                .await
1032                                .log_err();
1033                        }
1034                    })
1035                    .detach();
1036
1037                    agent
1038                }
1039                None => {
1040                    cx.background_spawn(async move {
1041                        KEY_VALUE_STORE.read_kvp(LAST_USED_EXTERNAL_AGENT_KEY)
1042                    })
1043                    .await
1044                    .log_err()
1045                    .flatten()
1046                    .and_then(|value| {
1047                        serde_json::from_str::<LastUsedExternalAgent>(&value).log_err()
1048                    })
1049                    .unwrap_or_default()
1050                    .agent
1051                }
1052            };
1053
1054            let server = ext_agent.server(fs, history);
1055
1056            this.update_in(cx, |this, window, cx| {
1057                match ext_agent {
1058                    crate::ExternalAgent::Gemini | crate::ExternalAgent::NativeAgent => {
1059                        if !cx.has_flag::<AcpFeatureFlag>() {
1060                            return;
1061                        }
1062                    }
1063                    crate::ExternalAgent::ClaudeCode => {
1064                        if !cx.has_flag::<ClaudeCodeFeatureFlag>() {
1065                            return;
1066                        }
1067                    }
1068                }
1069
1070                let thread_view = cx.new(|cx| {
1071                    crate::acp::AcpThreadView::new(
1072                        server,
1073                        resume_thread,
1074                        workspace.clone(),
1075                        project,
1076                        thread_store.clone(),
1077                        text_thread_store.clone(),
1078                        window,
1079                        cx,
1080                    )
1081                });
1082
1083                this.set_active_view(ActiveView::ExternalAgentThread { thread_view }, window, cx);
1084            })
1085        })
1086        .detach_and_log_err(cx);
1087    }
1088
1089    fn deploy_rules_library(
1090        &mut self,
1091        action: &OpenRulesLibrary,
1092        _window: &mut Window,
1093        cx: &mut Context<Self>,
1094    ) {
1095        open_rules_library(
1096            self.language_registry.clone(),
1097            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
1098            Rc::new(|| {
1099                Rc::new(SlashCommandCompletionProvider::new(
1100                    Arc::new(SlashCommandWorkingSet::default()),
1101                    None,
1102                    None,
1103                ))
1104            }),
1105            action
1106                .prompt_to_select
1107                .map(|uuid| UserPromptId(uuid).into()),
1108            cx,
1109        )
1110        .detach_and_log_err(cx);
1111    }
1112
1113    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1114        if matches!(self.active_view, ActiveView::History) {
1115            if let Some(previous_view) = self.previous_view.take() {
1116                self.set_active_view(previous_view, window, cx);
1117            }
1118        } else {
1119            self.thread_store
1120                .update(cx, |thread_store, cx| thread_store.reload(cx))
1121                .detach_and_log_err(cx);
1122            self.set_active_view(ActiveView::History, window, cx);
1123        }
1124        cx.notify();
1125    }
1126
1127    pub(crate) fn open_saved_prompt_editor(
1128        &mut self,
1129        path: Arc<Path>,
1130        window: &mut Window,
1131        cx: &mut Context<Self>,
1132    ) -> Task<Result<()>> {
1133        let context = self
1134            .context_store
1135            .update(cx, |store, cx| store.open_local_context(path, cx));
1136        cx.spawn_in(window, async move |this, cx| {
1137            let context = context.await?;
1138            this.update_in(cx, |this, window, cx| {
1139                this.open_prompt_editor(context, window, cx);
1140            })
1141        })
1142    }
1143
1144    pub(crate) fn open_prompt_editor(
1145        &mut self,
1146        context: Entity<AssistantContext>,
1147        window: &mut Window,
1148        cx: &mut Context<Self>,
1149    ) {
1150        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
1151            .log_err()
1152            .flatten();
1153        let editor = cx.new(|cx| {
1154            TextThreadEditor::for_context(
1155                context,
1156                self.fs.clone(),
1157                self.workspace.clone(),
1158                self.project.clone(),
1159                lsp_adapter_delegate,
1160                window,
1161                cx,
1162            )
1163        });
1164        self.set_active_view(
1165            ActiveView::prompt_editor(
1166                editor.clone(),
1167                self.history_store.clone(),
1168                self.acp_history_store.clone(),
1169                self.language_registry.clone(),
1170                window,
1171                cx,
1172            ),
1173            window,
1174            cx,
1175        );
1176    }
1177
1178    pub(crate) fn open_thread_by_id(
1179        &mut self,
1180        thread_id: &ThreadId,
1181        window: &mut Window,
1182        cx: &mut Context<Self>,
1183    ) -> Task<Result<()>> {
1184        let open_thread_task = self
1185            .thread_store
1186            .update(cx, |this, cx| this.open_thread(thread_id, window, cx));
1187        cx.spawn_in(window, async move |this, cx| {
1188            let thread = open_thread_task.await?;
1189            this.update_in(cx, |this, window, cx| {
1190                this.open_thread(thread, window, cx);
1191                anyhow::Ok(())
1192            })??;
1193            Ok(())
1194        })
1195    }
1196
1197    pub(crate) fn open_thread(
1198        &mut self,
1199        thread: Entity<Thread>,
1200        window: &mut Window,
1201        cx: &mut Context<Self>,
1202    ) {
1203        let context_store = cx.new(|_cx| {
1204            ContextStore::new(
1205                self.project.downgrade(),
1206                Some(self.thread_store.downgrade()),
1207            )
1208        });
1209
1210        let active_thread = cx.new(|cx| {
1211            ActiveThread::new(
1212                thread.clone(),
1213                self.thread_store.clone(),
1214                self.context_store.clone(),
1215                context_store.clone(),
1216                self.language_registry.clone(),
1217                self.workspace.clone(),
1218                window,
1219                cx,
1220            )
1221        });
1222
1223        let message_editor = cx.new(|cx| {
1224            MessageEditor::new(
1225                self.fs.clone(),
1226                self.workspace.clone(),
1227                context_store,
1228                self.prompt_store.clone(),
1229                self.thread_store.downgrade(),
1230                self.context_store.downgrade(),
1231                Some(self.history_store.downgrade()),
1232                thread.clone(),
1233                window,
1234                cx,
1235            )
1236        });
1237        message_editor.focus_handle(cx).focus(window);
1238
1239        let thread_view = ActiveView::thread(active_thread.clone(), message_editor, window, cx);
1240        self.set_active_view(thread_view, window, cx);
1241        AgentDiff::set_active_thread(&self.workspace, thread.clone(), window, cx);
1242    }
1243
1244    pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1245        match self.active_view {
1246            ActiveView::Configuration | ActiveView::History => {
1247                if let Some(previous_view) = self.previous_view.take() {
1248                    self.active_view = previous_view;
1249
1250                    match &self.active_view {
1251                        ActiveView::Thread { message_editor, .. } => {
1252                            message_editor.focus_handle(cx).focus(window);
1253                        }
1254                        ActiveView::ExternalAgentThread { thread_view } => {
1255                            thread_view.focus_handle(cx).focus(window);
1256                        }
1257                        ActiveView::TextThread { context_editor, .. } => {
1258                            context_editor.focus_handle(cx).focus(window);
1259                        }
1260                        ActiveView::History | ActiveView::Configuration => {}
1261                    }
1262                }
1263                cx.notify();
1264            }
1265            _ => {}
1266        }
1267    }
1268
1269    pub fn toggle_navigation_menu(
1270        &mut self,
1271        _: &ToggleNavigationMenu,
1272        window: &mut Window,
1273        cx: &mut Context<Self>,
1274    ) {
1275        self.assistant_navigation_menu_handle.toggle(window, cx);
1276    }
1277
1278    pub fn toggle_options_menu(
1279        &mut self,
1280        _: &ToggleOptionsMenu,
1281        window: &mut Window,
1282        cx: &mut Context<Self>,
1283    ) {
1284        self.agent_panel_menu_handle.toggle(window, cx);
1285    }
1286
1287    pub fn toggle_new_thread_menu(
1288        &mut self,
1289        _: &ToggleNewThreadMenu,
1290        window: &mut Window,
1291        cx: &mut Context<Self>,
1292    ) {
1293        self.new_thread_menu_handle.toggle(window, cx);
1294    }
1295
1296    pub fn increase_font_size(
1297        &mut self,
1298        action: &IncreaseBufferFontSize,
1299        _: &mut Window,
1300        cx: &mut Context<Self>,
1301    ) {
1302        self.handle_font_size_action(action.persist, px(1.0), cx);
1303    }
1304
1305    pub fn decrease_font_size(
1306        &mut self,
1307        action: &DecreaseBufferFontSize,
1308        _: &mut Window,
1309        cx: &mut Context<Self>,
1310    ) {
1311        self.handle_font_size_action(action.persist, px(-1.0), cx);
1312    }
1313
1314    fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1315        match self.active_view.which_font_size_used() {
1316            WhichFontSize::AgentFont => {
1317                if persist {
1318                    update_settings_file::<ThemeSettings>(
1319                        self.fs.clone(),
1320                        cx,
1321                        move |settings, cx| {
1322                            let agent_font_size =
1323                                ThemeSettings::get_global(cx).agent_font_size(cx) + delta;
1324                            let _ = settings
1325                                .agent_font_size
1326                                .insert(Some(theme::clamp_font_size(agent_font_size).into()));
1327                        },
1328                    );
1329                } else {
1330                    theme::adjust_agent_font_size(cx, |size| size + delta);
1331                }
1332            }
1333            WhichFontSize::BufferFont => {
1334                // Prompt editor uses the buffer font size, so allow the action to propagate to the
1335                // default handler that changes that font size.
1336                cx.propagate();
1337            }
1338            WhichFontSize::None => {}
1339        }
1340    }
1341
1342    pub fn reset_font_size(
1343        &mut self,
1344        action: &ResetBufferFontSize,
1345        _: &mut Window,
1346        cx: &mut Context<Self>,
1347    ) {
1348        if action.persist {
1349            update_settings_file::<ThemeSettings>(self.fs.clone(), cx, move |settings, _| {
1350                settings.agent_font_size = None;
1351            });
1352        } else {
1353            theme::reset_agent_font_size(cx);
1354        }
1355    }
1356
1357    pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1358        if self.zoomed {
1359            cx.emit(PanelEvent::ZoomOut);
1360        } else {
1361            if !self.focus_handle(cx).contains_focused(window, cx) {
1362                cx.focus_self(window);
1363            }
1364            cx.emit(PanelEvent::ZoomIn);
1365        }
1366    }
1367
1368    pub fn open_agent_diff(
1369        &mut self,
1370        _: &OpenAgentDiff,
1371        window: &mut Window,
1372        cx: &mut Context<Self>,
1373    ) {
1374        match &self.active_view {
1375            ActiveView::Thread { thread, .. } => {
1376                let thread = thread.read(cx).thread().clone();
1377                self.workspace
1378                    .update(cx, |workspace, cx| {
1379                        AgentDiffPane::deploy_in_workspace(
1380                            AgentDiffThread::Native(thread),
1381                            workspace,
1382                            window,
1383                            cx,
1384                        )
1385                    })
1386                    .log_err();
1387            }
1388            ActiveView::ExternalAgentThread { .. }
1389            | ActiveView::TextThread { .. }
1390            | ActiveView::History
1391            | ActiveView::Configuration => {}
1392        }
1393    }
1394
1395    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1396        let context_server_store = self.project.read(cx).context_server_store();
1397        let tools = self.thread_store.read(cx).tools();
1398        let fs = self.fs.clone();
1399
1400        self.set_active_view(ActiveView::Configuration, window, cx);
1401        self.configuration = Some(cx.new(|cx| {
1402            AgentConfiguration::new(
1403                fs,
1404                context_server_store,
1405                tools,
1406                self.language_registry.clone(),
1407                self.workspace.clone(),
1408                window,
1409                cx,
1410            )
1411        }));
1412
1413        if let Some(configuration) = self.configuration.as_ref() {
1414            self.configuration_subscription = Some(cx.subscribe_in(
1415                configuration,
1416                window,
1417                Self::handle_agent_configuration_event,
1418            ));
1419
1420            configuration.focus_handle(cx).focus(window);
1421        }
1422    }
1423
1424    pub(crate) fn open_active_thread_as_markdown(
1425        &mut self,
1426        _: &OpenActiveThreadAsMarkdown,
1427        window: &mut Window,
1428        cx: &mut Context<Self>,
1429    ) {
1430        let Some(workspace) = self.workspace.upgrade() else {
1431            return;
1432        };
1433
1434        match &self.active_view {
1435            ActiveView::Thread { thread, .. } => {
1436                active_thread::open_active_thread_as_markdown(
1437                    thread.read(cx).thread().clone(),
1438                    workspace,
1439                    window,
1440                    cx,
1441                )
1442                .detach_and_log_err(cx);
1443            }
1444            ActiveView::ExternalAgentThread { thread_view } => {
1445                thread_view
1446                    .update(cx, |thread_view, cx| {
1447                        thread_view.open_thread_as_markdown(workspace, window, cx)
1448                    })
1449                    .detach_and_log_err(cx);
1450            }
1451            ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {}
1452        }
1453    }
1454
1455    fn handle_agent_configuration_event(
1456        &mut self,
1457        _entity: &Entity<AgentConfiguration>,
1458        event: &AssistantConfigurationEvent,
1459        window: &mut Window,
1460        cx: &mut Context<Self>,
1461    ) {
1462        match event {
1463            AssistantConfigurationEvent::NewThread(provider) => {
1464                if LanguageModelRegistry::read_global(cx)
1465                    .default_model()
1466                    .is_none_or(|model| model.provider.id() != provider.id())
1467                    && let Some(model) = provider.default_model(cx)
1468                {
1469                    update_settings_file::<AgentSettings>(
1470                        self.fs.clone(),
1471                        cx,
1472                        move |settings, _| settings.set_model(model),
1473                    );
1474                }
1475
1476                self.new_thread(&NewThread::default(), window, cx);
1477                if let Some((thread, model)) =
1478                    self.active_thread(cx).zip(provider.default_model(cx))
1479                {
1480                    thread.update(cx, |thread, cx| {
1481                        thread.set_configured_model(
1482                            Some(ConfiguredModel {
1483                                provider: provider.clone(),
1484                                model,
1485                            }),
1486                            cx,
1487                        );
1488                    });
1489                }
1490            }
1491        }
1492    }
1493
1494    pub(crate) fn active_thread(&self, cx: &App) -> Option<Entity<Thread>> {
1495        match &self.active_view {
1496            ActiveView::Thread { thread, .. } => Some(thread.read(cx).thread().clone()),
1497            _ => None,
1498        }
1499    }
1500
1501    pub(crate) fn delete_thread(
1502        &mut self,
1503        thread_id: &ThreadId,
1504        cx: &mut Context<Self>,
1505    ) -> Task<Result<()>> {
1506        self.thread_store
1507            .update(cx, |this, cx| this.delete_thread(thread_id, cx))
1508    }
1509
1510    fn continue_conversation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1511        let ActiveView::Thread { thread, .. } = &self.active_view else {
1512            return;
1513        };
1514
1515        let thread_state = thread.read(cx).thread().read(cx);
1516        if !thread_state.tool_use_limit_reached() {
1517            return;
1518        }
1519
1520        let model = thread_state.configured_model().map(|cm| cm.model.clone());
1521        if let Some(model) = model {
1522            thread.update(cx, |active_thread, cx| {
1523                active_thread.thread().update(cx, |thread, cx| {
1524                    thread.insert_invisible_continue_message(cx);
1525                    thread.advance_prompt_id();
1526                    thread.send_to_model(
1527                        model,
1528                        CompletionIntent::UserPrompt,
1529                        Some(window.window_handle()),
1530                        cx,
1531                    );
1532                });
1533            });
1534        } else {
1535            log::warn!("No configured model available for continuation");
1536        }
1537    }
1538
1539    fn toggle_burn_mode(
1540        &mut self,
1541        _: &ToggleBurnMode,
1542        _window: &mut Window,
1543        cx: &mut Context<Self>,
1544    ) {
1545        let ActiveView::Thread { thread, .. } = &self.active_view else {
1546            return;
1547        };
1548
1549        thread.update(cx, |active_thread, cx| {
1550            active_thread.thread().update(cx, |thread, _cx| {
1551                let current_mode = thread.completion_mode();
1552
1553                thread.set_completion_mode(match current_mode {
1554                    CompletionMode::Burn => CompletionMode::Normal,
1555                    CompletionMode::Normal => CompletionMode::Burn,
1556                });
1557            });
1558        });
1559    }
1560
1561    pub(crate) fn active_context_editor(&self) -> Option<Entity<TextThreadEditor>> {
1562        match &self.active_view {
1563            ActiveView::TextThread { context_editor, .. } => Some(context_editor.clone()),
1564            _ => None,
1565        }
1566    }
1567
1568    pub(crate) fn delete_context(
1569        &mut self,
1570        path: Arc<Path>,
1571        cx: &mut Context<Self>,
1572    ) -> Task<Result<()>> {
1573        self.context_store
1574            .update(cx, |this, cx| this.delete_local_context(path, cx))
1575    }
1576
1577    fn set_active_view(
1578        &mut self,
1579        new_view: ActiveView,
1580        window: &mut Window,
1581        cx: &mut Context<Self>,
1582    ) {
1583        let current_is_history = matches!(self.active_view, ActiveView::History);
1584        let new_is_history = matches!(new_view, ActiveView::History);
1585
1586        let current_is_config = matches!(self.active_view, ActiveView::Configuration);
1587        let new_is_config = matches!(new_view, ActiveView::Configuration);
1588
1589        let current_is_special = current_is_history || current_is_config;
1590        let new_is_special = new_is_history || new_is_config;
1591
1592        if let ActiveView::Thread { thread, .. } = &self.active_view {
1593            let thread = thread.read(cx);
1594            if thread.is_empty() {
1595                let id = thread.thread().read(cx).id().clone();
1596                self.history_store.update(cx, |store, cx| {
1597                    store.remove_recently_opened_thread(id, cx);
1598                });
1599            }
1600        }
1601
1602        match &new_view {
1603            ActiveView::Thread { thread, .. } => self.history_store.update(cx, |store, cx| {
1604                let id = thread.read(cx).thread().read(cx).id().clone();
1605                store.push_recently_opened_entry(HistoryEntryId::Thread(id), cx);
1606            }),
1607            ActiveView::TextThread { context_editor, .. } => {
1608                self.history_store.update(cx, |store, cx| {
1609                    if let Some(path) = context_editor.read(cx).context().read(cx).path() {
1610                        store.push_recently_opened_entry(HistoryEntryId::Context(path.clone()), cx)
1611                    }
1612                })
1613            }
1614            ActiveView::ExternalAgentThread { .. } => {}
1615            ActiveView::History | ActiveView::Configuration => {}
1616        }
1617
1618        if current_is_special && !new_is_special {
1619            self.active_view = new_view;
1620        } else if !current_is_special && new_is_special {
1621            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
1622        } else {
1623            if !new_is_special {
1624                self.previous_view = None;
1625            }
1626            self.active_view = new_view;
1627        }
1628
1629        self.focus_handle(cx).focus(window);
1630    }
1631
1632    fn populate_recently_opened_menu_section_old(
1633        mut menu: ContextMenu,
1634        panel: Entity<Self>,
1635        cx: &mut Context<ContextMenu>,
1636    ) -> ContextMenu {
1637        let entries = panel
1638            .read(cx)
1639            .history_store
1640            .read(cx)
1641            .recently_opened_entries(cx);
1642
1643        if entries.is_empty() {
1644            return menu;
1645        }
1646
1647        menu = menu.header("Recently Opened");
1648
1649        for entry in entries {
1650            let title = entry.title().clone();
1651            let id = entry.id();
1652
1653            menu = menu.entry_with_end_slot_on_hover(
1654                title,
1655                None,
1656                {
1657                    let panel = panel.downgrade();
1658                    let id = id.clone();
1659                    move |window, cx| {
1660                        let id = id.clone();
1661                        panel
1662                            .update(cx, move |this, cx| match id {
1663                                HistoryEntryId::Thread(id) => this
1664                                    .open_thread_by_id(&id, window, cx)
1665                                    .detach_and_log_err(cx),
1666                                HistoryEntryId::Context(path) => this
1667                                    .open_saved_prompt_editor(path.clone(), window, cx)
1668                                    .detach_and_log_err(cx),
1669                            })
1670                            .ok();
1671                    }
1672                },
1673                IconName::Close,
1674                "Close Entry".into(),
1675                {
1676                    let panel = panel.downgrade();
1677                    let id = id.clone();
1678                    move |_window, cx| {
1679                        panel
1680                            .update(cx, |this, cx| {
1681                                this.history_store.update(cx, |history_store, cx| {
1682                                    history_store.remove_recently_opened_entry(&id, cx);
1683                                });
1684                            })
1685                            .ok();
1686                    }
1687                },
1688            );
1689        }
1690
1691        menu = menu.separator();
1692
1693        menu
1694    }
1695
1696    fn populate_recently_opened_menu_section_new(
1697        mut menu: ContextMenu,
1698        panel: Entity<Self>,
1699        cx: &mut Context<ContextMenu>,
1700    ) -> ContextMenu {
1701        let entries = panel
1702            .read(cx)
1703            .acp_history_store
1704            .read(cx)
1705            .recently_opened_entries(cx);
1706
1707        if entries.is_empty() {
1708            return menu;
1709        }
1710
1711        menu = menu.header("Recently Opened");
1712
1713        for entry in entries {
1714            let title = entry.title().clone();
1715
1716            menu = menu.entry_with_end_slot_on_hover(
1717                title,
1718                None,
1719                {
1720                    let panel = panel.downgrade();
1721                    let entry = entry.clone();
1722                    move |window, cx| {
1723                        let entry = entry.clone();
1724                        panel
1725                            .update(cx, move |this, cx| match &entry {
1726                                agent2::HistoryEntry::AcpThread(entry) => this.external_thread(
1727                                    Some(ExternalAgent::NativeAgent),
1728                                    Some(entry.clone()),
1729                                    window,
1730                                    cx,
1731                                ),
1732                                agent2::HistoryEntry::TextThread(entry) => this
1733                                    .open_saved_prompt_editor(entry.path.clone(), window, cx)
1734                                    .detach_and_log_err(cx),
1735                            })
1736                            .ok();
1737                    }
1738                },
1739                IconName::Close,
1740                "Close Entry".into(),
1741                {
1742                    let panel = panel.downgrade();
1743                    let id = entry.id();
1744                    move |_window, cx| {
1745                        panel
1746                            .update(cx, |this, cx| {
1747                                this.acp_history_store.update(cx, |history_store, cx| {
1748                                    history_store.remove_recently_opened_entry(&id, cx);
1749                                });
1750                            })
1751                            .ok();
1752                    }
1753                },
1754            );
1755        }
1756
1757        menu = menu.separator();
1758
1759        menu
1760    }
1761
1762    pub fn set_selected_agent(
1763        &mut self,
1764        agent: AgentType,
1765        window: &mut Window,
1766        cx: &mut Context<Self>,
1767    ) {
1768        if self.selected_agent != agent {
1769            self.selected_agent = agent;
1770            self.serialize(cx);
1771        }
1772        self.new_agent_thread(agent, window, cx);
1773    }
1774
1775    pub fn selected_agent(&self) -> AgentType {
1776        self.selected_agent
1777    }
1778
1779    pub fn new_agent_thread(
1780        &mut self,
1781        agent: AgentType,
1782        window: &mut Window,
1783        cx: &mut Context<Self>,
1784    ) {
1785        match agent {
1786            AgentType::Zed => {
1787                window.dispatch_action(
1788                    NewThread {
1789                        from_thread_id: None,
1790                    }
1791                    .boxed_clone(),
1792                    cx,
1793                );
1794            }
1795            AgentType::TextThread => {
1796                window.dispatch_action(NewTextThread.boxed_clone(), cx);
1797            }
1798            AgentType::NativeAgent => {
1799                self.external_thread(Some(crate::ExternalAgent::NativeAgent), None, window, cx)
1800            }
1801            AgentType::Gemini => {
1802                self.external_thread(Some(crate::ExternalAgent::Gemini), None, window, cx)
1803            }
1804            AgentType::ClaudeCode => {
1805                self.external_thread(Some(crate::ExternalAgent::ClaudeCode), None, window, cx)
1806            }
1807        }
1808    }
1809}
1810
1811impl Focusable for AgentPanel {
1812    fn focus_handle(&self, cx: &App) -> FocusHandle {
1813        match &self.active_view {
1814            ActiveView::Thread { message_editor, .. } => message_editor.focus_handle(cx),
1815            ActiveView::ExternalAgentThread { thread_view, .. } => thread_view.focus_handle(cx),
1816            ActiveView::History => {
1817                if cx.has_flag::<feature_flags::AcpFeatureFlag>() {
1818                    self.acp_history.focus_handle(cx)
1819                } else {
1820                    self.history.focus_handle(cx)
1821                }
1822            }
1823            ActiveView::TextThread { context_editor, .. } => context_editor.focus_handle(cx),
1824            ActiveView::Configuration => {
1825                if let Some(configuration) = self.configuration.as_ref() {
1826                    configuration.focus_handle(cx)
1827                } else {
1828                    cx.focus_handle()
1829                }
1830            }
1831        }
1832    }
1833}
1834
1835fn agent_panel_dock_position(cx: &App) -> DockPosition {
1836    match AgentSettings::get_global(cx).dock {
1837        AgentDockPosition::Left => DockPosition::Left,
1838        AgentDockPosition::Bottom => DockPosition::Bottom,
1839        AgentDockPosition::Right => DockPosition::Right,
1840    }
1841}
1842
1843impl EventEmitter<PanelEvent> for AgentPanel {}
1844
1845impl Panel for AgentPanel {
1846    fn persistent_name() -> &'static str {
1847        "AgentPanel"
1848    }
1849
1850    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1851        agent_panel_dock_position(cx)
1852    }
1853
1854    fn position_is_valid(&self, position: DockPosition) -> bool {
1855        position != DockPosition::Bottom
1856    }
1857
1858    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1859        settings::update_settings_file::<AgentSettings>(self.fs.clone(), cx, move |settings, _| {
1860            let dock = match position {
1861                DockPosition::Left => AgentDockPosition::Left,
1862                DockPosition::Bottom => AgentDockPosition::Bottom,
1863                DockPosition::Right => AgentDockPosition::Right,
1864            };
1865            settings.set_dock(dock);
1866        });
1867    }
1868
1869    fn size(&self, window: &Window, cx: &App) -> Pixels {
1870        let settings = AgentSettings::get_global(cx);
1871        match self.position(window, cx) {
1872            DockPosition::Left | DockPosition::Right => {
1873                self.width.unwrap_or(settings.default_width)
1874            }
1875            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1876        }
1877    }
1878
1879    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1880        match self.position(window, cx) {
1881            DockPosition::Left | DockPosition::Right => self.width = size,
1882            DockPosition::Bottom => self.height = size,
1883        }
1884        self.serialize(cx);
1885        cx.notify();
1886    }
1887
1888    fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
1889
1890    fn remote_id() -> Option<proto::PanelId> {
1891        Some(proto::PanelId::AssistantPanel)
1892    }
1893
1894    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1895        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
1896    }
1897
1898    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1899        Some("Agent Panel")
1900    }
1901
1902    fn toggle_action(&self) -> Box<dyn Action> {
1903        Box::new(ToggleFocus)
1904    }
1905
1906    fn activation_priority(&self) -> u32 {
1907        3
1908    }
1909
1910    fn enabled(&self, cx: &App) -> bool {
1911        DisableAiSettings::get_global(cx).disable_ai.not() && AgentSettings::get_global(cx).enabled
1912    }
1913
1914    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1915        self.zoomed
1916    }
1917
1918    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1919        self.zoomed = zoomed;
1920        cx.notify();
1921    }
1922}
1923
1924impl AgentPanel {
1925    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
1926        const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
1927
1928        let content = match &self.active_view {
1929            ActiveView::Thread {
1930                thread: active_thread,
1931                change_title_editor,
1932                ..
1933            } => {
1934                let state = {
1935                    let active_thread = active_thread.read(cx);
1936                    if active_thread.is_empty() {
1937                        &ThreadSummary::Pending
1938                    } else {
1939                        active_thread.summary(cx)
1940                    }
1941                };
1942
1943                match state {
1944                    ThreadSummary::Pending => Label::new(ThreadSummary::DEFAULT.clone())
1945                        .truncate()
1946                        .into_any_element(),
1947                    ThreadSummary::Generating => Label::new(LOADING_SUMMARY_PLACEHOLDER)
1948                        .truncate()
1949                        .into_any_element(),
1950                    ThreadSummary::Ready(_) => div()
1951                        .w_full()
1952                        .child(change_title_editor.clone())
1953                        .into_any_element(),
1954                    ThreadSummary::Error => h_flex()
1955                        .w_full()
1956                        .child(change_title_editor.clone())
1957                        .child(
1958                            IconButton::new("retry-summary-generation", IconName::RotateCcw)
1959                                .icon_size(IconSize::Small)
1960                                .on_click({
1961                                    let active_thread = active_thread.clone();
1962                                    move |_, _window, cx| {
1963                                        active_thread.update(cx, |thread, cx| {
1964                                            thread.regenerate_summary(cx);
1965                                        });
1966                                    }
1967                                })
1968                                .tooltip(move |_window, cx| {
1969                                    cx.new(|_| {
1970                                        Tooltip::new("Failed to generate title")
1971                                            .meta("Click to try again")
1972                                    })
1973                                    .into()
1974                                }),
1975                        )
1976                        .into_any_element(),
1977                }
1978            }
1979            ActiveView::ExternalAgentThread { thread_view } => {
1980                Label::new(thread_view.read(cx).title(cx))
1981                    .truncate()
1982                    .into_any_element()
1983            }
1984            ActiveView::TextThread {
1985                title_editor,
1986                context_editor,
1987                ..
1988            } => {
1989                let summary = context_editor.read(cx).context().read(cx).summary();
1990
1991                match summary {
1992                    ContextSummary::Pending => Label::new(ContextSummary::DEFAULT)
1993                        .truncate()
1994                        .into_any_element(),
1995                    ContextSummary::Content(summary) => {
1996                        if summary.done {
1997                            div()
1998                                .w_full()
1999                                .child(title_editor.clone())
2000                                .into_any_element()
2001                        } else {
2002                            Label::new(LOADING_SUMMARY_PLACEHOLDER)
2003                                .truncate()
2004                                .into_any_element()
2005                        }
2006                    }
2007                    ContextSummary::Error => h_flex()
2008                        .w_full()
2009                        .child(title_editor.clone())
2010                        .child(
2011                            IconButton::new("retry-summary-generation", IconName::RotateCcw)
2012                                .icon_size(IconSize::Small)
2013                                .on_click({
2014                                    let context_editor = context_editor.clone();
2015                                    move |_, _window, cx| {
2016                                        context_editor.update(cx, |context_editor, cx| {
2017                                            context_editor.regenerate_summary(cx);
2018                                        });
2019                                    }
2020                                })
2021                                .tooltip(move |_window, cx| {
2022                                    cx.new(|_| {
2023                                        Tooltip::new("Failed to generate title")
2024                                            .meta("Click to try again")
2025                                    })
2026                                    .into()
2027                                }),
2028                        )
2029                        .into_any_element(),
2030                }
2031            }
2032            ActiveView::History => Label::new("History").truncate().into_any_element(),
2033            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
2034        };
2035
2036        h_flex()
2037            .key_context("TitleEditor")
2038            .id("TitleEditor")
2039            .flex_grow()
2040            .w_full()
2041            .max_w_full()
2042            .overflow_x_scroll()
2043            .child(content)
2044            .into_any()
2045    }
2046
2047    fn render_panel_options_menu(
2048        &self,
2049        window: &mut Window,
2050        cx: &mut Context<Self>,
2051    ) -> impl IntoElement {
2052        let user_store = self.user_store.read(cx);
2053        let usage = user_store.model_request_usage();
2054        let account_url = zed_urls::account_url(cx);
2055
2056        let focus_handle = self.focus_handle(cx);
2057
2058        let full_screen_label = if self.is_zoomed(window, cx) {
2059            "Disable Full Screen"
2060        } else {
2061            "Enable Full Screen"
2062        };
2063
2064        PopoverMenu::new("agent-options-menu")
2065            .trigger_with_tooltip(
2066                IconButton::new("agent-options-menu", IconName::Ellipsis)
2067                    .icon_size(IconSize::Small),
2068                {
2069                    let focus_handle = focus_handle.clone();
2070                    move |window, cx| {
2071                        Tooltip::for_action_in(
2072                            "Toggle Agent Menu",
2073                            &ToggleOptionsMenu,
2074                            &focus_handle,
2075                            window,
2076                            cx,
2077                        )
2078                    }
2079                },
2080            )
2081            .anchor(Corner::TopRight)
2082            .with_handle(self.agent_panel_menu_handle.clone())
2083            .menu({
2084                let focus_handle = focus_handle.clone();
2085                move |window, cx| {
2086                    Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
2087                        menu = menu.context(focus_handle.clone());
2088                        if let Some(usage) = usage {
2089                            menu = menu
2090                                .header_with_link("Prompt Usage", "Manage", account_url.clone())
2091                                .custom_entry(
2092                                    move |_window, cx| {
2093                                        let used_percentage = match usage.limit {
2094                                            UsageLimit::Limited(limit) => {
2095                                                Some((usage.amount as f32 / limit as f32) * 100.)
2096                                            }
2097                                            UsageLimit::Unlimited => None,
2098                                        };
2099
2100                                        h_flex()
2101                                            .flex_1()
2102                                            .gap_1p5()
2103                                            .children(used_percentage.map(|percent| {
2104                                                ProgressBar::new("usage", percent, 100., cx)
2105                                            }))
2106                                            .child(
2107                                                Label::new(match usage.limit {
2108                                                    UsageLimit::Limited(limit) => {
2109                                                        format!("{} / {limit}", usage.amount)
2110                                                    }
2111                                                    UsageLimit::Unlimited => {
2112                                                        format!("{} / ∞", usage.amount)
2113                                                    }
2114                                                })
2115                                                .size(LabelSize::Small)
2116                                                .color(Color::Muted),
2117                                            )
2118                                            .into_any_element()
2119                                    },
2120                                    move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
2121                                )
2122                                .separator()
2123                        }
2124
2125                        menu = menu
2126                            .header("MCP Servers")
2127                            .action(
2128                                "View Server Extensions",
2129                                Box::new(zed_actions::Extensions {
2130                                    category_filter: Some(
2131                                        zed_actions::ExtensionCategoryFilter::ContextServers,
2132                                    ),
2133                                    id: None,
2134                                }),
2135                            )
2136                            .action("Add Custom Server…", Box::new(AddContextServer))
2137                            .separator();
2138
2139                        menu = menu
2140                            .action("Rules…", Box::new(OpenRulesLibrary::default()))
2141                            .action("Settings", Box::new(OpenSettings))
2142                            .separator()
2143                            .action(full_screen_label, Box::new(ToggleZoom));
2144                        menu
2145                    }))
2146                }
2147            })
2148    }
2149
2150    fn render_recent_entries_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2151        let focus_handle = self.focus_handle(cx);
2152
2153        PopoverMenu::new("agent-nav-menu")
2154            .trigger_with_tooltip(
2155                IconButton::new("agent-nav-menu", IconName::MenuAlt).icon_size(IconSize::Small),
2156                {
2157                    let focus_handle = focus_handle.clone();
2158                    move |window, cx| {
2159                        Tooltip::for_action_in(
2160                            "Toggle Recent Threads",
2161                            &ToggleNavigationMenu,
2162                            &focus_handle,
2163                            window,
2164                            cx,
2165                        )
2166                    }
2167                },
2168            )
2169            .anchor(Corner::TopLeft)
2170            .with_handle(self.assistant_navigation_menu_handle.clone())
2171            .menu({
2172                let menu = self.assistant_navigation_menu.clone();
2173                move |window, cx| {
2174                    if let Some(menu) = menu.as_ref() {
2175                        menu.update(cx, |_, cx| {
2176                            cx.defer_in(window, |menu, window, cx| {
2177                                menu.rebuild(window, cx);
2178                            });
2179                        })
2180                    }
2181                    menu.clone()
2182                }
2183            })
2184    }
2185
2186    fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
2187        let focus_handle = self.focus_handle(cx);
2188
2189        IconButton::new("go-back", IconName::ArrowLeft)
2190            .icon_size(IconSize::Small)
2191            .on_click(cx.listener(|this, _, window, cx| {
2192                this.go_back(&workspace::GoBack, window, cx);
2193            }))
2194            .tooltip({
2195                let focus_handle = focus_handle.clone();
2196
2197                move |window, cx| {
2198                    Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, window, cx)
2199                }
2200            })
2201    }
2202
2203    fn render_toolbar_old(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2204        let focus_handle = self.focus_handle(cx);
2205
2206        let active_thread = match &self.active_view {
2207            ActiveView::Thread { thread, .. } => Some(thread.read(cx).thread().clone()),
2208            ActiveView::ExternalAgentThread { .. }
2209            | ActiveView::TextThread { .. }
2210            | ActiveView::History
2211            | ActiveView::Configuration => None,
2212        };
2213
2214        let new_thread_menu = PopoverMenu::new("new_thread_menu")
2215            .trigger_with_tooltip(
2216                IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
2217                Tooltip::text("New Thread…"),
2218            )
2219            .anchor(Corner::TopRight)
2220            .with_handle(self.new_thread_menu_handle.clone())
2221            .menu({
2222                let focus_handle = focus_handle.clone();
2223                move |window, cx| {
2224                    let active_thread = active_thread.clone();
2225                    Some(ContextMenu::build(window, cx, |mut menu, _window, cx| {
2226                        menu = menu
2227                            .context(focus_handle.clone())
2228                            .when_some(active_thread, |this, active_thread| {
2229                                let thread = active_thread.read(cx);
2230
2231                                if !thread.is_empty() {
2232                                    let thread_id = thread.id().clone();
2233                                    this.item(
2234                                        ContextMenuEntry::new("New From Summary")
2235                                            .icon(IconName::ThreadFromSummary)
2236                                            .icon_color(Color::Muted)
2237                                            .handler(move |window, cx| {
2238                                                window.dispatch_action(
2239                                                    Box::new(NewThread {
2240                                                        from_thread_id: Some(thread_id.clone()),
2241                                                    }),
2242                                                    cx,
2243                                                );
2244                                            }),
2245                                    )
2246                                } else {
2247                                    this
2248                                }
2249                            })
2250                            .item(
2251                                ContextMenuEntry::new("New Thread")
2252                                    .icon(IconName::Thread)
2253                                    .icon_color(Color::Muted)
2254                                    .action(NewThread::default().boxed_clone())
2255                                    .handler(move |window, cx| {
2256                                        window.dispatch_action(
2257                                            NewThread::default().boxed_clone(),
2258                                            cx,
2259                                        );
2260                                    }),
2261                            )
2262                            .item(
2263                                ContextMenuEntry::new("New Text Thread")
2264                                    .icon(IconName::TextThread)
2265                                    .icon_color(Color::Muted)
2266                                    .action(NewTextThread.boxed_clone())
2267                                    .handler(move |window, cx| {
2268                                        window.dispatch_action(NewTextThread.boxed_clone(), cx);
2269                                    }),
2270                            );
2271                        menu
2272                    }))
2273                }
2274            });
2275
2276        h_flex()
2277            .id("assistant-toolbar")
2278            .h(Tab::container_height(cx))
2279            .max_w_full()
2280            .flex_none()
2281            .justify_between()
2282            .gap_2()
2283            .bg(cx.theme().colors().tab_bar_background)
2284            .border_b_1()
2285            .border_color(cx.theme().colors().border)
2286            .child(
2287                h_flex()
2288                    .size_full()
2289                    .pl_1()
2290                    .gap_1()
2291                    .child(match &self.active_view {
2292                        ActiveView::History | ActiveView::Configuration => div()
2293                            .pl(DynamicSpacing::Base04.rems(cx))
2294                            .child(self.render_toolbar_back_button(cx))
2295                            .into_any_element(),
2296                        _ => self.render_recent_entries_menu(cx).into_any_element(),
2297                    })
2298                    .child(self.render_title_view(window, cx)),
2299            )
2300            .child(
2301                h_flex()
2302                    .h_full()
2303                    .gap_2()
2304                    .children(self.render_token_count(cx))
2305                    .child(
2306                        h_flex()
2307                            .h_full()
2308                            .gap(DynamicSpacing::Base02.rems(cx))
2309                            .px(DynamicSpacing::Base08.rems(cx))
2310                            .border_l_1()
2311                            .border_color(cx.theme().colors().border)
2312                            .child(new_thread_menu)
2313                            .child(self.render_panel_options_menu(window, cx)),
2314                    ),
2315            )
2316    }
2317
2318    fn render_toolbar_new(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2319        let focus_handle = self.focus_handle(cx);
2320
2321        let active_thread = match &self.active_view {
2322            ActiveView::Thread { thread, .. } => Some(thread.read(cx).thread().clone()),
2323            ActiveView::ExternalAgentThread { .. }
2324            | ActiveView::TextThread { .. }
2325            | ActiveView::History
2326            | ActiveView::Configuration => None,
2327        };
2328
2329        let new_thread_menu = PopoverMenu::new("new_thread_menu")
2330            .trigger_with_tooltip(
2331                IconButton::new("new_thread_menu_btn", IconName::Plus).icon_size(IconSize::Small),
2332                {
2333                    let focus_handle = focus_handle.clone();
2334                    move |window, cx| {
2335                        Tooltip::for_action_in(
2336                            "New…",
2337                            &ToggleNewThreadMenu,
2338                            &focus_handle,
2339                            window,
2340                            cx,
2341                        )
2342                    }
2343                },
2344            )
2345            .anchor(Corner::TopLeft)
2346            .with_handle(self.new_thread_menu_handle.clone())
2347            .menu({
2348                let focus_handle = focus_handle.clone();
2349                let workspace = self.workspace.clone();
2350
2351                move |window, cx| {
2352                    let active_thread = active_thread.clone();
2353                    Some(ContextMenu::build(window, cx, |mut menu, _window, cx| {
2354                        menu = menu
2355                            .context(focus_handle.clone())
2356                            .header("Zed Agent")
2357                            .when_some(active_thread, |this, active_thread| {
2358                                let thread = active_thread.read(cx);
2359
2360                                if !thread.is_empty() {
2361                                    let thread_id = thread.id().clone();
2362                                    this.item(
2363                                        ContextMenuEntry::new("New From Summary")
2364                                            .icon(IconName::ThreadFromSummary)
2365                                            .icon_color(Color::Muted)
2366                                            .handler(move |window, cx| {
2367                                                window.dispatch_action(
2368                                                    Box::new(NewThread {
2369                                                        from_thread_id: Some(thread_id.clone()),
2370                                                    }),
2371                                                    cx,
2372                                                );
2373                                            }),
2374                                    )
2375                                } else {
2376                                    this
2377                                }
2378                            })
2379                            .item(
2380                                ContextMenuEntry::new("New Thread")
2381                                    .icon(IconName::Thread)
2382                                    .icon_color(Color::Muted)
2383                                    .action(NewThread::default().boxed_clone())
2384                                    .handler({
2385                                        let workspace = workspace.clone();
2386                                        move |window, cx| {
2387                                            if let Some(workspace) = workspace.upgrade() {
2388                                                workspace.update(cx, |workspace, cx| {
2389                                                    if let Some(panel) =
2390                                                        workspace.panel::<AgentPanel>(cx)
2391                                                    {
2392                                                        panel.update(cx, |panel, cx| {
2393                                                            panel.set_selected_agent(
2394                                                                AgentType::Zed,
2395                                                                window,
2396                                                                cx,
2397                                                            );
2398                                                        });
2399                                                    }
2400                                                });
2401                                            }
2402                                        }
2403                                    }),
2404                            )
2405                            .item(
2406                                ContextMenuEntry::new("New Text Thread")
2407                                    .icon(IconName::TextThread)
2408                                    .icon_color(Color::Muted)
2409                                    .action(NewTextThread.boxed_clone())
2410                                    .handler({
2411                                        let workspace = workspace.clone();
2412                                        move |window, cx| {
2413                                            if let Some(workspace) = workspace.upgrade() {
2414                                                workspace.update(cx, |workspace, cx| {
2415                                                    if let Some(panel) =
2416                                                        workspace.panel::<AgentPanel>(cx)
2417                                                    {
2418                                                        panel.update(cx, |panel, cx| {
2419                                                            panel.set_selected_agent(
2420                                                                AgentType::TextThread,
2421                                                                window,
2422                                                                cx,
2423                                                            );
2424                                                        });
2425                                                    }
2426                                                });
2427                                            }
2428                                        }
2429                                    }),
2430                            )
2431                            .item(
2432                                ContextMenuEntry::new("New Native Agent Thread")
2433                                    .icon(IconName::ZedAssistant)
2434                                    .icon_color(Color::Muted)
2435                                    .handler({
2436                                        let workspace = workspace.clone();
2437                                        move |window, cx| {
2438                                            if let Some(workspace) = workspace.upgrade() {
2439                                                workspace.update(cx, |workspace, cx| {
2440                                                    if let Some(panel) =
2441                                                        workspace.panel::<AgentPanel>(cx)
2442                                                    {
2443                                                        panel.update(cx, |panel, cx| {
2444                                                            panel.set_selected_agent(
2445                                                                AgentType::NativeAgent,
2446                                                                window,
2447                                                                cx,
2448                                                            );
2449                                                        });
2450                                                    }
2451                                                });
2452                                            }
2453                                        }
2454                                    }),
2455                            )
2456                            .separator()
2457                            .header("External Agents")
2458                            .when(cx.has_flag::<AcpFeatureFlag>(), |menu| {
2459                                menu.item(
2460                                    ContextMenuEntry::new("New Gemini Thread")
2461                                        .icon(IconName::AiGemini)
2462                                        .icon_color(Color::Muted)
2463                                        .handler({
2464                                            let workspace = workspace.clone();
2465                                            move |window, cx| {
2466                                                if let Some(workspace) = workspace.upgrade() {
2467                                                    workspace.update(cx, |workspace, cx| {
2468                                                        if let Some(panel) =
2469                                                            workspace.panel::<AgentPanel>(cx)
2470                                                        {
2471                                                            panel.update(cx, |panel, cx| {
2472                                                                panel.set_selected_agent(
2473                                                                    AgentType::Gemini,
2474                                                                    window,
2475                                                                    cx,
2476                                                                );
2477                                                            });
2478                                                        }
2479                                                    });
2480                                                }
2481                                            }
2482                                        }),
2483                                )
2484                            })
2485                            .when(cx.has_flag::<ClaudeCodeFeatureFlag>(), |menu| {
2486                                menu.item(
2487                                    ContextMenuEntry::new("New Claude Code Thread")
2488                                        .icon(IconName::AiClaude)
2489                                        .icon_color(Color::Muted)
2490                                        .handler({
2491                                            let workspace = workspace.clone();
2492                                            move |window, cx| {
2493                                                if let Some(workspace) = workspace.upgrade() {
2494                                                    workspace.update(cx, |workspace, cx| {
2495                                                        if let Some(panel) =
2496                                                            workspace.panel::<AgentPanel>(cx)
2497                                                        {
2498                                                            panel.update(cx, |panel, cx| {
2499                                                                panel.set_selected_agent(
2500                                                                    AgentType::ClaudeCode,
2501                                                                    window,
2502                                                                    cx,
2503                                                                );
2504                                                            });
2505                                                        }
2506                                                    });
2507                                                }
2508                                            }
2509                                        }),
2510                                )
2511                            });
2512                        menu
2513                    }))
2514                }
2515            });
2516
2517        let selected_agent_label = self.selected_agent.label().into();
2518        let selected_agent = div()
2519            .id("selected_agent_icon")
2520            .px(DynamicSpacing::Base02.rems(cx))
2521            .child(Icon::new(self.selected_agent.icon()).color(Color::Muted))
2522            .tooltip(move |window, cx| {
2523                Tooltip::with_meta(
2524                    selected_agent_label.clone(),
2525                    None,
2526                    "Selected Agent",
2527                    window,
2528                    cx,
2529                )
2530            })
2531            .into_any_element();
2532
2533        h_flex()
2534            .id("agent-panel-toolbar")
2535            .h(Tab::container_height(cx))
2536            .max_w_full()
2537            .flex_none()
2538            .justify_between()
2539            .gap_2()
2540            .bg(cx.theme().colors().tab_bar_background)
2541            .border_b_1()
2542            .border_color(cx.theme().colors().border)
2543            .child(
2544                h_flex()
2545                    .size_full()
2546                    .gap(DynamicSpacing::Base04.rems(cx))
2547                    .pl(DynamicSpacing::Base04.rems(cx))
2548                    .child(match &self.active_view {
2549                        ActiveView::History | ActiveView::Configuration => {
2550                            self.render_toolbar_back_button(cx).into_any_element()
2551                        }
2552                        _ => h_flex()
2553                            .gap_1()
2554                            .child(self.render_recent_entries_menu(cx))
2555                            .child(Divider::vertical())
2556                            .child(selected_agent)
2557                            .into_any_element(),
2558                    })
2559                    .child(self.render_title_view(window, cx)),
2560            )
2561            .child(
2562                h_flex()
2563                    .h_full()
2564                    .gap_2()
2565                    .children(self.render_token_count(cx))
2566                    .child(
2567                        h_flex()
2568                            .h_full()
2569                            .gap(DynamicSpacing::Base02.rems(cx))
2570                            .pl(DynamicSpacing::Base04.rems(cx))
2571                            .pr(DynamicSpacing::Base06.rems(cx))
2572                            .border_l_1()
2573                            .border_color(cx.theme().colors().border)
2574                            .child(new_thread_menu)
2575                            .child(self.render_panel_options_menu(window, cx)),
2576                    ),
2577            )
2578    }
2579
2580    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2581        if cx.has_flag::<feature_flags::AcpFeatureFlag>()
2582            || cx.has_flag::<feature_flags::ClaudeCodeFeatureFlag>()
2583        {
2584            self.render_toolbar_new(window, cx).into_any_element()
2585        } else {
2586            self.render_toolbar_old(window, cx).into_any_element()
2587        }
2588    }
2589
2590    fn render_token_count(&self, cx: &App) -> Option<AnyElement> {
2591        match &self.active_view {
2592            ActiveView::Thread {
2593                thread,
2594                message_editor,
2595                ..
2596            } => {
2597                let active_thread = thread.read(cx);
2598                let message_editor = message_editor.read(cx);
2599
2600                let editor_empty = message_editor.is_editor_fully_empty(cx);
2601
2602                if active_thread.is_empty() && editor_empty {
2603                    return None;
2604                }
2605
2606                let thread = active_thread.thread().read(cx);
2607                let is_generating = thread.is_generating();
2608                let conversation_token_usage = thread.total_token_usage()?;
2609
2610                let (total_token_usage, is_estimating) =
2611                    if let Some((editing_message_id, unsent_tokens)) =
2612                        active_thread.editing_message_id()
2613                    {
2614                        let combined = thread
2615                            .token_usage_up_to_message(editing_message_id)
2616                            .add(unsent_tokens);
2617
2618                        (combined, unsent_tokens > 0)
2619                    } else {
2620                        let unsent_tokens =
2621                            message_editor.last_estimated_token_count().unwrap_or(0);
2622                        let combined = conversation_token_usage.add(unsent_tokens);
2623
2624                        (combined, unsent_tokens > 0)
2625                    };
2626
2627                let is_waiting_to_update_token_count =
2628                    message_editor.is_waiting_to_update_token_count();
2629
2630                if total_token_usage.total == 0 {
2631                    return None;
2632                }
2633
2634                let token_color = match total_token_usage.ratio() {
2635                    TokenUsageRatio::Normal if is_estimating => Color::Default,
2636                    TokenUsageRatio::Normal => Color::Muted,
2637                    TokenUsageRatio::Warning => Color::Warning,
2638                    TokenUsageRatio::Exceeded => Color::Error,
2639                };
2640
2641                let token_count = h_flex()
2642                    .id("token-count")
2643                    .flex_shrink_0()
2644                    .gap_0p5()
2645                    .when(!is_generating && is_estimating, |parent| {
2646                        parent
2647                            .child(
2648                                h_flex()
2649                                    .mr_1()
2650                                    .size_2p5()
2651                                    .justify_center()
2652                                    .rounded_full()
2653                                    .bg(cx.theme().colors().text.opacity(0.1))
2654                                    .child(
2655                                        div().size_1().rounded_full().bg(cx.theme().colors().text),
2656                                    ),
2657                            )
2658                            .tooltip(move |window, cx| {
2659                                Tooltip::with_meta(
2660                                    "Estimated New Token Count",
2661                                    None,
2662                                    format!(
2663                                        "Current Conversation Tokens: {}",
2664                                        humanize_token_count(conversation_token_usage.total)
2665                                    ),
2666                                    window,
2667                                    cx,
2668                                )
2669                            })
2670                    })
2671                    .child(
2672                        Label::new(humanize_token_count(total_token_usage.total))
2673                            .size(LabelSize::Small)
2674                            .color(token_color)
2675                            .map(|label| {
2676                                if is_generating || is_waiting_to_update_token_count {
2677                                    label
2678                                        .with_animation(
2679                                            "used-tokens-label",
2680                                            Animation::new(Duration::from_secs(2))
2681                                                .repeat()
2682                                                .with_easing(pulsating_between(0.6, 1.)),
2683                                            |label, delta| label.alpha(delta),
2684                                        )
2685                                        .into_any()
2686                                } else {
2687                                    label.into_any_element()
2688                                }
2689                            }),
2690                    )
2691                    .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2692                    .child(
2693                        Label::new(humanize_token_count(total_token_usage.max))
2694                            .size(LabelSize::Small)
2695                            .color(Color::Muted),
2696                    )
2697                    .into_any();
2698
2699                Some(token_count)
2700            }
2701            ActiveView::TextThread { context_editor, .. } => {
2702                let element = render_remaining_tokens(context_editor, cx)?;
2703
2704                Some(element.into_any_element())
2705            }
2706            ActiveView::ExternalAgentThread { .. }
2707            | ActiveView::History
2708            | ActiveView::Configuration => None,
2709        }
2710    }
2711
2712    fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2713        if TrialEndUpsell::dismissed() {
2714            return false;
2715        }
2716
2717        match &self.active_view {
2718            ActiveView::Thread { thread, .. } => {
2719                if thread
2720                    .read(cx)
2721                    .thread()
2722                    .read(cx)
2723                    .configured_model()
2724                    .is_some_and(|model| {
2725                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2726                    })
2727                {
2728                    return false;
2729                }
2730            }
2731            ActiveView::TextThread { .. } => {
2732                if LanguageModelRegistry::global(cx)
2733                    .read(cx)
2734                    .default_model()
2735                    .is_some_and(|model| {
2736                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2737                    })
2738                {
2739                    return false;
2740                }
2741            }
2742            ActiveView::ExternalAgentThread { .. }
2743            | ActiveView::History
2744            | ActiveView::Configuration => return false,
2745        }
2746
2747        let plan = self.user_store.read(cx).plan();
2748        let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2749
2750        matches!(plan, Some(Plan::ZedFree)) && has_previous_trial
2751    }
2752
2753    fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
2754        if OnboardingUpsell::dismissed() {
2755            return false;
2756        }
2757
2758        match &self.active_view {
2759            ActiveView::History | ActiveView::Configuration => false,
2760            ActiveView::ExternalAgentThread { thread_view, .. }
2761                if thread_view.read(cx).as_native_thread(cx).is_none() =>
2762            {
2763                false
2764            }
2765            _ => {
2766                let history_is_empty = self
2767                    .history_store
2768                    .update(cx, |store, cx| store.recent_entries(1, cx).is_empty());
2769
2770                let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
2771                    .providers()
2772                    .iter()
2773                    .any(|provider| {
2774                        provider.is_authenticated(cx)
2775                            && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
2776                    });
2777
2778                history_is_empty || !has_configured_non_zed_providers
2779            }
2780        }
2781    }
2782
2783    fn render_onboarding(
2784        &self,
2785        _window: &mut Window,
2786        cx: &mut Context<Self>,
2787    ) -> Option<impl IntoElement> {
2788        if !self.should_render_onboarding(cx) {
2789            return None;
2790        }
2791
2792        let thread_view = matches!(&self.active_view, ActiveView::Thread { .. });
2793        let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
2794
2795        Some(
2796            div()
2797                .when(thread_view, |this| {
2798                    this.size_full().bg(cx.theme().colors().panel_background)
2799                })
2800                .when(text_thread_view, |this| {
2801                    this.bg(cx.theme().colors().editor_background)
2802                })
2803                .child(self.onboarding.clone()),
2804        )
2805    }
2806
2807    fn render_backdrop(&self, cx: &mut Context<Self>) -> impl IntoElement {
2808        div()
2809            .size_full()
2810            .absolute()
2811            .inset_0()
2812            .bg(cx.theme().colors().panel_background)
2813            .opacity(0.8)
2814            .block_mouse_except_scroll()
2815    }
2816
2817    fn render_trial_end_upsell(
2818        &self,
2819        _window: &mut Window,
2820        cx: &mut Context<Self>,
2821    ) -> Option<impl IntoElement> {
2822        if !self.should_render_trial_end_upsell(cx) {
2823            return None;
2824        }
2825
2826        Some(
2827            v_flex()
2828                .absolute()
2829                .inset_0()
2830                .size_full()
2831                .bg(cx.theme().colors().panel_background)
2832                .opacity(0.85)
2833                .block_mouse_except_scroll()
2834                .child(EndTrialUpsell::new(Arc::new({
2835                    let this = cx.entity();
2836                    move |_, cx| {
2837                        this.update(cx, |_this, cx| {
2838                            TrialEndUpsell::set_dismissed(true, cx);
2839                            cx.notify();
2840                        });
2841                    }
2842                }))),
2843        )
2844    }
2845
2846    fn render_empty_state_section_header(
2847        &self,
2848        label: impl Into<SharedString>,
2849        action_slot: Option<AnyElement>,
2850        cx: &mut Context<Self>,
2851    ) -> impl IntoElement {
2852        div().pl_1().pr_1p5().child(
2853            h_flex()
2854                .mt_2()
2855                .pl_1p5()
2856                .pb_1()
2857                .w_full()
2858                .justify_between()
2859                .border_b_1()
2860                .border_color(cx.theme().colors().border_variant)
2861                .child(
2862                    Label::new(label.into())
2863                        .size(LabelSize::Small)
2864                        .color(Color::Muted),
2865                )
2866                .children(action_slot),
2867        )
2868    }
2869
2870    fn render_thread_empty_state(
2871        &self,
2872        window: &mut Window,
2873        cx: &mut Context<Self>,
2874    ) -> impl IntoElement {
2875        let recent_history = self
2876            .history_store
2877            .update(cx, |this, cx| this.recent_entries(6, cx));
2878
2879        let model_registry = LanguageModelRegistry::read_global(cx);
2880
2881        let configuration_error =
2882            model_registry.configuration_error(model_registry.default_model(), cx);
2883
2884        let no_error = configuration_error.is_none();
2885        let focus_handle = self.focus_handle(cx);
2886
2887        v_flex()
2888            .size_full()
2889            .bg(cx.theme().colors().panel_background)
2890            .when(recent_history.is_empty(), |this| {
2891                this.child(
2892                    v_flex()
2893                        .size_full()
2894                        .mx_auto()
2895                        .justify_center()
2896                        .items_center()
2897                        .gap_1()
2898                        .child(h_flex().child(Headline::new("Welcome to the Agent Panel")))
2899                        .when(no_error, |parent| {
2900                            parent
2901                                .child(h_flex().child(
2902                                    Label::new("Ask and build anything.").color(Color::Muted),
2903                                ))
2904                                .child(
2905                                    v_flex()
2906                                        .mt_2()
2907                                        .gap_1()
2908                                        .max_w_48()
2909                                        .child(
2910                                            Button::new("context", "Add Context")
2911                                                .label_size(LabelSize::Small)
2912                                                .icon(IconName::FileCode)
2913                                                .icon_position(IconPosition::Start)
2914                                                .icon_size(IconSize::Small)
2915                                                .icon_color(Color::Muted)
2916                                                .full_width()
2917                                                .key_binding(KeyBinding::for_action_in(
2918                                                    &ToggleContextPicker,
2919                                                    &focus_handle,
2920                                                    window,
2921                                                    cx,
2922                                                ))
2923                                                .on_click(|_event, window, cx| {
2924                                                    window.dispatch_action(
2925                                                        ToggleContextPicker.boxed_clone(),
2926                                                        cx,
2927                                                    )
2928                                                }),
2929                                        )
2930                                        .child(
2931                                            Button::new("mode", "Switch Model")
2932                                                .label_size(LabelSize::Small)
2933                                                .icon(IconName::DatabaseZap)
2934                                                .icon_position(IconPosition::Start)
2935                                                .icon_size(IconSize::Small)
2936                                                .icon_color(Color::Muted)
2937                                                .full_width()
2938                                                .key_binding(KeyBinding::for_action_in(
2939                                                    &ToggleModelSelector,
2940                                                    &focus_handle,
2941                                                    window,
2942                                                    cx,
2943                                                ))
2944                                                .on_click(|_event, window, cx| {
2945                                                    window.dispatch_action(
2946                                                        ToggleModelSelector.boxed_clone(),
2947                                                        cx,
2948                                                    )
2949                                                }),
2950                                        )
2951                                        .child(
2952                                            Button::new("settings", "View Settings")
2953                                                .label_size(LabelSize::Small)
2954                                                .icon(IconName::Settings)
2955                                                .icon_position(IconPosition::Start)
2956                                                .icon_size(IconSize::Small)
2957                                                .icon_color(Color::Muted)
2958                                                .full_width()
2959                                                .key_binding(KeyBinding::for_action_in(
2960                                                    &OpenSettings,
2961                                                    &focus_handle,
2962                                                    window,
2963                                                    cx,
2964                                                ))
2965                                                .on_click(|_event, window, cx| {
2966                                                    window.dispatch_action(
2967                                                        OpenSettings.boxed_clone(),
2968                                                        cx,
2969                                                    )
2970                                                }),
2971                                        ),
2972                                )
2973                        }),
2974                )
2975            })
2976            .when(!recent_history.is_empty(), |parent| {
2977                parent
2978                    .overflow_hidden()
2979                    .justify_end()
2980                    .gap_1()
2981                    .child(
2982                        self.render_empty_state_section_header(
2983                            "Recent",
2984                            Some(
2985                                Button::new("view-history", "View All")
2986                                    .style(ButtonStyle::Subtle)
2987                                    .label_size(LabelSize::Small)
2988                                    .key_binding(
2989                                        KeyBinding::for_action_in(
2990                                            &OpenHistory,
2991                                            &self.focus_handle(cx),
2992                                            window,
2993                                            cx,
2994                                        )
2995                                        .map(|kb| kb.size(rems_from_px(12.))),
2996                                    )
2997                                    .on_click(move |_event, window, cx| {
2998                                        window.dispatch_action(OpenHistory.boxed_clone(), cx);
2999                                    })
3000                                    .into_any_element(),
3001                            ),
3002                            cx,
3003                        ),
3004                    )
3005                    .child(
3006                        v_flex().p_1().pr_1p5().gap_1().children(
3007                            recent_history
3008                                .into_iter()
3009                                .enumerate()
3010                                .map(|(index, entry)| {
3011                                    // TODO: Add keyboard navigation.
3012                                    let is_hovered =
3013                                        self.hovered_recent_history_item == Some(index);
3014                                    HistoryEntryElement::new(entry.clone(), cx.entity().downgrade())
3015                                        .hovered(is_hovered)
3016                                        .on_hover(cx.listener(
3017                                            move |this, is_hovered, _window, cx| {
3018                                                if *is_hovered {
3019                                                    this.hovered_recent_history_item = Some(index);
3020                                                } else if this.hovered_recent_history_item
3021                                                    == Some(index)
3022                                                {
3023                                                    this.hovered_recent_history_item = None;
3024                                                }
3025                                                cx.notify();
3026                                            },
3027                                        ))
3028                                        .into_any_element()
3029                                }),
3030                        ),
3031                    )
3032            })
3033            .when_some(configuration_error.as_ref(), |this, err| {
3034                this.child(self.render_configuration_error(false, err, &focus_handle, window, cx))
3035            })
3036    }
3037
3038    fn render_configuration_error(
3039        &self,
3040        border_bottom: bool,
3041        configuration_error: &ConfigurationError,
3042        focus_handle: &FocusHandle,
3043        window: &mut Window,
3044        cx: &mut App,
3045    ) -> impl IntoElement {
3046        let zed_provider_configured = AgentSettings::get_global(cx)
3047            .default_model
3048            .as_ref()
3049            .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
3050
3051        let callout = if zed_provider_configured {
3052            Callout::new()
3053                .icon(IconName::Warning)
3054                .severity(Severity::Warning)
3055                .when(border_bottom, |this| {
3056                    this.border_position(ui::BorderPosition::Bottom)
3057                })
3058                .title("Sign in to continue using Zed as your LLM provider.")
3059                .actions_slot(
3060                    Button::new("sign_in", "Sign In")
3061                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3062                        .label_size(LabelSize::Small)
3063                        .on_click({
3064                            let workspace = self.workspace.clone();
3065                            move |_, _, cx| {
3066                                let Ok(client) =
3067                                    workspace.update(cx, |workspace, _| workspace.client().clone())
3068                                else {
3069                                    return;
3070                                };
3071
3072                                cx.spawn(async move |cx| {
3073                                    client.sign_in_with_optional_connect(true, cx).await
3074                                })
3075                                .detach_and_log_err(cx);
3076                            }
3077                        }),
3078                )
3079        } else {
3080            Callout::new()
3081                .icon(IconName::Warning)
3082                .severity(Severity::Warning)
3083                .when(border_bottom, |this| {
3084                    this.border_position(ui::BorderPosition::Bottom)
3085                })
3086                .title(configuration_error.to_string())
3087                .actions_slot(
3088                    Button::new("settings", "Configure")
3089                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3090                        .label_size(LabelSize::Small)
3091                        .key_binding(
3092                            KeyBinding::for_action_in(&OpenSettings, focus_handle, window, cx)
3093                                .map(|kb| kb.size(rems_from_px(12.))),
3094                        )
3095                        .on_click(|_event, window, cx| {
3096                            window.dispatch_action(OpenSettings.boxed_clone(), cx)
3097                        }),
3098                )
3099        };
3100
3101        match configuration_error {
3102            ConfigurationError::ModelNotFound
3103            | ConfigurationError::ProviderNotAuthenticated(_)
3104            | ConfigurationError::NoProvider => callout.into_any_element(),
3105            ConfigurationError::ProviderPendingTermsAcceptance(provider) => {
3106                Banner::new()
3107                    .severity(Severity::Warning)
3108                    .child(h_flex().w_full().children(
3109                        provider.render_accept_terms(
3110                            LanguageModelProviderTosView::ThreadEmptyState,
3111                            cx,
3112                        ),
3113                    ))
3114                    .into_any_element()
3115            }
3116        }
3117    }
3118
3119    fn render_tool_use_limit_reached(
3120        &self,
3121        window: &mut Window,
3122        cx: &mut Context<Self>,
3123    ) -> Option<AnyElement> {
3124        let active_thread = match &self.active_view {
3125            ActiveView::Thread { thread, .. } => thread,
3126            ActiveView::ExternalAgentThread { .. } => {
3127                return None;
3128            }
3129            ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {
3130                return None;
3131            }
3132        };
3133
3134        let thread = active_thread.read(cx).thread().read(cx);
3135
3136        let tool_use_limit_reached = thread.tool_use_limit_reached();
3137        if !tool_use_limit_reached {
3138            return None;
3139        }
3140
3141        let model = thread.configured_model()?.model;
3142
3143        let focus_handle = self.focus_handle(cx);
3144
3145        let banner = Banner::new()
3146            .severity(Severity::Info)
3147            .child(Label::new("Consecutive tool use limit reached.").size(LabelSize::Small))
3148            .action_slot(
3149                h_flex()
3150                    .gap_1()
3151                    .child(
3152                        Button::new("continue-conversation", "Continue")
3153                            .layer(ElevationIndex::ModalSurface)
3154                            .label_size(LabelSize::Small)
3155                            .key_binding(
3156                                KeyBinding::for_action_in(
3157                                    &ContinueThread,
3158                                    &focus_handle,
3159                                    window,
3160                                    cx,
3161                                )
3162                                .map(|kb| kb.size(rems_from_px(10.))),
3163                            )
3164                            .on_click(cx.listener(|this, _, window, cx| {
3165                                this.continue_conversation(window, cx);
3166                            })),
3167                    )
3168                    .when(model.supports_burn_mode(), |this| {
3169                        this.child(
3170                            Button::new("continue-burn-mode", "Continue with Burn Mode")
3171                                .style(ButtonStyle::Filled)
3172                                .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3173                                .layer(ElevationIndex::ModalSurface)
3174                                .label_size(LabelSize::Small)
3175                                .key_binding(
3176                                    KeyBinding::for_action_in(
3177                                        &ContinueWithBurnMode,
3178                                        &focus_handle,
3179                                        window,
3180                                        cx,
3181                                    )
3182                                    .map(|kb| kb.size(rems_from_px(10.))),
3183                                )
3184                                .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
3185                                .on_click({
3186                                    let active_thread = active_thread.clone();
3187                                    cx.listener(move |this, _, window, cx| {
3188                                        active_thread.update(cx, |active_thread, cx| {
3189                                            active_thread.thread().update(cx, |thread, _cx| {
3190                                                thread.set_completion_mode(CompletionMode::Burn);
3191                                            });
3192                                        });
3193                                        this.continue_conversation(window, cx);
3194                                    })
3195                                }),
3196                        )
3197                    }),
3198            );
3199
3200        Some(div().px_2().pb_2().child(banner).into_any_element())
3201    }
3202
3203    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3204        let message = message.into();
3205
3206        IconButton::new("copy", IconName::Copy)
3207            .icon_size(IconSize::Small)
3208            .icon_color(Color::Muted)
3209            .tooltip(Tooltip::text("Copy Error Message"))
3210            .on_click(move |_, _, cx| {
3211                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3212            })
3213    }
3214
3215    fn dismiss_error_button(
3216        &self,
3217        thread: &Entity<ActiveThread>,
3218        cx: &mut Context<Self>,
3219    ) -> impl IntoElement {
3220        IconButton::new("dismiss", IconName::Close)
3221            .icon_size(IconSize::Small)
3222            .icon_color(Color::Muted)
3223            .tooltip(Tooltip::text("Dismiss Error"))
3224            .on_click(cx.listener({
3225                let thread = thread.clone();
3226                move |_, _, _, cx| {
3227                    thread.update(cx, |this, _cx| {
3228                        this.clear_last_error();
3229                    });
3230
3231                    cx.notify();
3232                }
3233            }))
3234    }
3235
3236    fn upgrade_button(
3237        &self,
3238        thread: &Entity<ActiveThread>,
3239        cx: &mut Context<Self>,
3240    ) -> impl IntoElement {
3241        Button::new("upgrade", "Upgrade")
3242            .label_size(LabelSize::Small)
3243            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3244            .on_click(cx.listener({
3245                let thread = thread.clone();
3246                move |_, _, _, cx| {
3247                    thread.update(cx, |this, _cx| {
3248                        this.clear_last_error();
3249                    });
3250
3251                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3252                    cx.notify();
3253                }
3254            }))
3255    }
3256
3257    fn render_payment_required_error(
3258        &self,
3259        thread: &Entity<ActiveThread>,
3260        cx: &mut Context<Self>,
3261    ) -> AnyElement {
3262        const ERROR_MESSAGE: &str =
3263            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3264
3265        Callout::new()
3266            .severity(Severity::Error)
3267            .icon(IconName::XCircle)
3268            .title("Free Usage Exceeded")
3269            .description(ERROR_MESSAGE)
3270            .actions_slot(
3271                h_flex()
3272                    .gap_0p5()
3273                    .child(self.upgrade_button(thread, cx))
3274                    .child(self.create_copy_button(ERROR_MESSAGE)),
3275            )
3276            .dismiss_action(self.dismiss_error_button(thread, cx))
3277            .into_any_element()
3278    }
3279
3280    fn render_model_request_limit_reached_error(
3281        &self,
3282        plan: Plan,
3283        thread: &Entity<ActiveThread>,
3284        cx: &mut Context<Self>,
3285    ) -> AnyElement {
3286        let error_message = match plan {
3287            Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3288            Plan::ZedProTrial | Plan::ZedFree => "Upgrade to Zed Pro for more prompts.",
3289        };
3290
3291        Callout::new()
3292            .severity(Severity::Error)
3293            .title("Model Prompt Limit Reached")
3294            .description(error_message)
3295            .actions_slot(
3296                h_flex()
3297                    .gap_0p5()
3298                    .child(self.upgrade_button(thread, cx))
3299                    .child(self.create_copy_button(error_message)),
3300            )
3301            .dismiss_action(self.dismiss_error_button(thread, cx))
3302            .into_any_element()
3303    }
3304
3305    fn render_retry_button(&self, thread: &Entity<ActiveThread>) -> AnyElement {
3306        Button::new("retry", "Retry")
3307            .icon(IconName::RotateCw)
3308            .icon_position(IconPosition::Start)
3309            .icon_size(IconSize::Small)
3310            .label_size(LabelSize::Small)
3311            .on_click({
3312                let thread = thread.clone();
3313                move |_, window, cx| {
3314                    thread.update(cx, |thread, cx| {
3315                        thread.clear_last_error();
3316                        thread.thread().update(cx, |thread, cx| {
3317                            thread.retry_last_completion(Some(window.window_handle()), cx);
3318                        });
3319                    });
3320                }
3321            })
3322            .into_any_element()
3323    }
3324
3325    fn render_error_message(
3326        &self,
3327        header: SharedString,
3328        message: SharedString,
3329        thread: &Entity<ActiveThread>,
3330        cx: &mut Context<Self>,
3331    ) -> AnyElement {
3332        let message_with_header = format!("{}\n{}", header, message);
3333
3334        Callout::new()
3335            .severity(Severity::Error)
3336            .icon(IconName::XCircle)
3337            .title(header)
3338            .description(message.clone())
3339            .actions_slot(
3340                h_flex()
3341                    .gap_0p5()
3342                    .child(self.render_retry_button(thread))
3343                    .child(self.create_copy_button(message_with_header)),
3344            )
3345            .dismiss_action(self.dismiss_error_button(thread, cx))
3346            .into_any_element()
3347    }
3348
3349    fn render_retryable_error(
3350        &self,
3351        message: SharedString,
3352        can_enable_burn_mode: bool,
3353        thread: &Entity<ActiveThread>,
3354    ) -> AnyElement {
3355        Callout::new()
3356            .severity(Severity::Error)
3357            .title("Error")
3358            .description(message.clone())
3359            .actions_slot(
3360                h_flex()
3361                    .gap_0p5()
3362                    .when(can_enable_burn_mode, |this| {
3363                        this.child(
3364                            Button::new("enable_burn_retry", "Enable Burn Mode and Retry")
3365                                .icon(IconName::ZedBurnMode)
3366                                .icon_position(IconPosition::Start)
3367                                .icon_size(IconSize::Small)
3368                                .label_size(LabelSize::Small)
3369                                .on_click({
3370                                    let thread = thread.clone();
3371                                    move |_, window, cx| {
3372                                        thread.update(cx, |thread, cx| {
3373                                            thread.clear_last_error();
3374                                            thread.thread().update(cx, |thread, cx| {
3375                                                thread.enable_burn_mode_and_retry(
3376                                                    Some(window.window_handle()),
3377                                                    cx,
3378                                                );
3379                                            });
3380                                        });
3381                                    }
3382                                }),
3383                        )
3384                    })
3385                    .child(self.render_retry_button(thread)),
3386            )
3387            .into_any_element()
3388    }
3389
3390    fn render_prompt_editor(
3391        &self,
3392        context_editor: &Entity<TextThreadEditor>,
3393        buffer_search_bar: &Entity<BufferSearchBar>,
3394        window: &mut Window,
3395        cx: &mut Context<Self>,
3396    ) -> Div {
3397        let mut registrar = buffer_search::DivRegistrar::new(
3398            |this, _, _cx| match &this.active_view {
3399                ActiveView::TextThread {
3400                    buffer_search_bar, ..
3401                } => Some(buffer_search_bar.clone()),
3402                _ => None,
3403            },
3404            cx,
3405        );
3406        BufferSearchBar::register(&mut registrar);
3407        registrar
3408            .into_div()
3409            .size_full()
3410            .relative()
3411            .map(|parent| {
3412                buffer_search_bar.update(cx, |buffer_search_bar, cx| {
3413                    if buffer_search_bar.is_dismissed() {
3414                        return parent;
3415                    }
3416                    parent.child(
3417                        div()
3418                            .p(DynamicSpacing::Base08.rems(cx))
3419                            .border_b_1()
3420                            .border_color(cx.theme().colors().border_variant)
3421                            .bg(cx.theme().colors().editor_background)
3422                            .child(buffer_search_bar.render(window, cx)),
3423                    )
3424                })
3425            })
3426            .child(context_editor.clone())
3427            .child(self.render_drag_target(cx))
3428    }
3429
3430    fn render_drag_target(&self, cx: &Context<Self>) -> Div {
3431        let is_local = self.project.read(cx).is_local();
3432        div()
3433            .invisible()
3434            .absolute()
3435            .top_0()
3436            .right_0()
3437            .bottom_0()
3438            .left_0()
3439            .bg(cx.theme().colors().drop_target_background)
3440            .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
3441            .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
3442            .when(is_local, |this| {
3443                this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
3444            })
3445            .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
3446                let item = tab.pane.read(cx).item_for_index(tab.ix);
3447                let project_paths = item
3448                    .and_then(|item| item.project_path(cx))
3449                    .into_iter()
3450                    .collect::<Vec<_>>();
3451                this.handle_drop(project_paths, vec![], window, cx);
3452            }))
3453            .on_drop(
3454                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
3455                    let project_paths = selection
3456                        .items()
3457                        .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
3458                        .collect::<Vec<_>>();
3459                    this.handle_drop(project_paths, vec![], window, cx);
3460                }),
3461            )
3462            .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
3463                let tasks = paths
3464                    .paths()
3465                    .iter()
3466                    .map(|path| {
3467                        Workspace::project_path_for_path(this.project.clone(), path, false, cx)
3468                    })
3469                    .collect::<Vec<_>>();
3470                cx.spawn_in(window, async move |this, cx| {
3471                    let mut paths = vec![];
3472                    let mut added_worktrees = vec![];
3473                    let opened_paths = futures::future::join_all(tasks).await;
3474                    for entry in opened_paths {
3475                        if let Some((worktree, project_path)) = entry.log_err() {
3476                            added_worktrees.push(worktree);
3477                            paths.push(project_path);
3478                        }
3479                    }
3480                    this.update_in(cx, |this, window, cx| {
3481                        this.handle_drop(paths, added_worktrees, window, cx);
3482                    })
3483                    .ok();
3484                })
3485                .detach();
3486            }))
3487    }
3488
3489    fn handle_drop(
3490        &mut self,
3491        paths: Vec<ProjectPath>,
3492        added_worktrees: Vec<Entity<Worktree>>,
3493        window: &mut Window,
3494        cx: &mut Context<Self>,
3495    ) {
3496        match &self.active_view {
3497            ActiveView::Thread { thread, .. } => {
3498                let context_store = thread.read(cx).context_store().clone();
3499                context_store.update(cx, move |context_store, cx| {
3500                    let mut tasks = Vec::new();
3501                    for project_path in &paths {
3502                        tasks.push(context_store.add_file_from_path(
3503                            project_path.clone(),
3504                            false,
3505                            cx,
3506                        ));
3507                    }
3508                    cx.background_spawn(async move {
3509                        futures::future::join_all(tasks).await;
3510                        // Need to hold onto the worktrees until they have already been used when
3511                        // opening the buffers.
3512                        drop(added_worktrees);
3513                    })
3514                    .detach();
3515                });
3516            }
3517            ActiveView::ExternalAgentThread { thread_view } => {
3518                thread_view.update(cx, |thread_view, cx| {
3519                    thread_view.insert_dragged_files(paths, added_worktrees, window, cx);
3520                });
3521            }
3522            ActiveView::TextThread { context_editor, .. } => {
3523                context_editor.update(cx, |context_editor, cx| {
3524                    TextThreadEditor::insert_dragged_files(
3525                        context_editor,
3526                        paths,
3527                        added_worktrees,
3528                        window,
3529                        cx,
3530                    );
3531                });
3532            }
3533            ActiveView::History | ActiveView::Configuration => {}
3534        }
3535    }
3536
3537    fn key_context(&self) -> KeyContext {
3538        let mut key_context = KeyContext::new_with_defaults();
3539        key_context.add("AgentPanel");
3540        match &self.active_view {
3541            ActiveView::ExternalAgentThread { .. } => key_context.add("external_agent_thread"),
3542            ActiveView::TextThread { .. } => key_context.add("prompt_editor"),
3543            ActiveView::Thread { .. } | ActiveView::History | ActiveView::Configuration => {}
3544        }
3545        key_context
3546    }
3547}
3548
3549impl Render for AgentPanel {
3550    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3551        // WARNING: Changes to this element hierarchy can have
3552        // non-obvious implications to the layout of children.
3553        //
3554        // If you need to change it, please confirm:
3555        // - The message editor expands (cmd-option-esc) correctly
3556        // - When expanded, the buttons at the bottom of the panel are displayed correctly
3557        // - Font size works as expected and can be changed with cmd-+/cmd-
3558        // - Scrolling in all views works as expected
3559        // - Files can be dropped into the panel
3560        let content = v_flex()
3561            .relative()
3562            .size_full()
3563            .justify_between()
3564            .key_context(self.key_context())
3565            .on_action(cx.listener(Self::cancel))
3566            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
3567                this.new_thread(action, window, cx);
3568            }))
3569            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
3570                this.open_history(window, cx);
3571            }))
3572            .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
3573                this.open_configuration(window, cx);
3574            }))
3575            .on_action(cx.listener(Self::open_active_thread_as_markdown))
3576            .on_action(cx.listener(Self::deploy_rules_library))
3577            .on_action(cx.listener(Self::open_agent_diff))
3578            .on_action(cx.listener(Self::go_back))
3579            .on_action(cx.listener(Self::toggle_navigation_menu))
3580            .on_action(cx.listener(Self::toggle_options_menu))
3581            .on_action(cx.listener(Self::increase_font_size))
3582            .on_action(cx.listener(Self::decrease_font_size))
3583            .on_action(cx.listener(Self::reset_font_size))
3584            .on_action(cx.listener(Self::toggle_zoom))
3585            .on_action(cx.listener(|this, _: &ContinueThread, window, cx| {
3586                this.continue_conversation(window, cx);
3587            }))
3588            .on_action(cx.listener(|this, _: &ContinueWithBurnMode, window, cx| {
3589                match &this.active_view {
3590                    ActiveView::Thread { thread, .. } => {
3591                        thread.update(cx, |active_thread, cx| {
3592                            active_thread.thread().update(cx, |thread, _cx| {
3593                                thread.set_completion_mode(CompletionMode::Burn);
3594                            });
3595                        });
3596                        this.continue_conversation(window, cx);
3597                    }
3598                    ActiveView::ExternalAgentThread { .. } => {}
3599                    ActiveView::TextThread { .. }
3600                    | ActiveView::History
3601                    | ActiveView::Configuration => {}
3602                }
3603            }))
3604            .on_action(cx.listener(Self::toggle_burn_mode))
3605            .child(self.render_toolbar(window, cx))
3606            .children(self.render_onboarding(window, cx))
3607            .map(|parent| match &self.active_view {
3608                ActiveView::Thread {
3609                    thread,
3610                    message_editor,
3611                    ..
3612                } => parent
3613                    .child(
3614                        if thread.read(cx).is_empty() && !self.should_render_onboarding(cx) {
3615                            self.render_thread_empty_state(window, cx)
3616                                .into_any_element()
3617                        } else {
3618                            thread.clone().into_any_element()
3619                        },
3620                    )
3621                    .children(self.render_tool_use_limit_reached(window, cx))
3622                    .when_some(thread.read(cx).last_error(), |this, last_error| {
3623                        this.child(
3624                            div()
3625                                .child(match last_error {
3626                                    ThreadError::PaymentRequired => {
3627                                        self.render_payment_required_error(thread, cx)
3628                                    }
3629                                    ThreadError::ModelRequestLimitReached { plan } => self
3630                                        .render_model_request_limit_reached_error(plan, thread, cx),
3631                                    ThreadError::Message { header, message } => {
3632                                        self.render_error_message(header, message, thread, cx)
3633                                    }
3634                                    ThreadError::RetryableError {
3635                                        message,
3636                                        can_enable_burn_mode,
3637                                    } => self.render_retryable_error(
3638                                        message,
3639                                        can_enable_burn_mode,
3640                                        thread,
3641                                    ),
3642                                })
3643                                .into_any(),
3644                        )
3645                    })
3646                    .child(h_flex().relative().child(message_editor.clone()).when(
3647                        !LanguageModelRegistry::read_global(cx).has_authenticated_provider(cx),
3648                        |this| this.child(self.render_backdrop(cx)),
3649                    ))
3650                    .child(self.render_drag_target(cx)),
3651                ActiveView::ExternalAgentThread { thread_view, .. } => parent
3652                    .child(thread_view.clone())
3653                    .child(self.render_drag_target(cx)),
3654                ActiveView::History => {
3655                    if cx.has_flag::<feature_flags::AcpFeatureFlag>() {
3656                        parent.child(self.acp_history.clone())
3657                    } else {
3658                        parent.child(self.history.clone())
3659                    }
3660                }
3661                ActiveView::TextThread {
3662                    context_editor,
3663                    buffer_search_bar,
3664                    ..
3665                } => {
3666                    let model_registry = LanguageModelRegistry::read_global(cx);
3667                    let configuration_error =
3668                        model_registry.configuration_error(model_registry.default_model(), cx);
3669                    parent
3670                        .map(|this| {
3671                            if !self.should_render_onboarding(cx)
3672                                && let Some(err) = configuration_error.as_ref()
3673                            {
3674                                this.child(self.render_configuration_error(
3675                                    true,
3676                                    err,
3677                                    &self.focus_handle(cx),
3678                                    window,
3679                                    cx,
3680                                ))
3681                            } else {
3682                                this
3683                            }
3684                        })
3685                        .child(self.render_prompt_editor(
3686                            context_editor,
3687                            buffer_search_bar,
3688                            window,
3689                            cx,
3690                        ))
3691                }
3692                ActiveView::Configuration => parent.children(self.configuration.clone()),
3693            })
3694            .children(self.render_trial_end_upsell(window, cx));
3695
3696        match self.active_view.which_font_size_used() {
3697            WhichFontSize::AgentFont => {
3698                WithRemSize::new(ThemeSettings::get_global(cx).agent_font_size(cx))
3699                    .size_full()
3700                    .child(content)
3701                    .into_any()
3702            }
3703            _ => content.into_any(),
3704        }
3705    }
3706}
3707
3708struct PromptLibraryInlineAssist {
3709    workspace: WeakEntity<Workspace>,
3710}
3711
3712impl PromptLibraryInlineAssist {
3713    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
3714        Self { workspace }
3715    }
3716}
3717
3718impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
3719    fn assist(
3720        &self,
3721        prompt_editor: &Entity<Editor>,
3722        initial_prompt: Option<String>,
3723        window: &mut Window,
3724        cx: &mut Context<RulesLibrary>,
3725    ) {
3726        InlineAssistant::update_global(cx, |assistant, cx| {
3727            let Some(project) = self
3728                .workspace
3729                .upgrade()
3730                .map(|workspace| workspace.read(cx).project().downgrade())
3731            else {
3732                return;
3733            };
3734            let prompt_store = None;
3735            let thread_store = None;
3736            let text_thread_store = None;
3737            let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
3738            assistant.assist(
3739                prompt_editor,
3740                self.workspace.clone(),
3741                context_store,
3742                project,
3743                prompt_store,
3744                thread_store,
3745                text_thread_store,
3746                initial_prompt,
3747                window,
3748                cx,
3749            )
3750        })
3751    }
3752
3753    fn focus_agent_panel(
3754        &self,
3755        workspace: &mut Workspace,
3756        window: &mut Window,
3757        cx: &mut Context<Workspace>,
3758    ) -> bool {
3759        workspace.focus_panel::<AgentPanel>(window, cx).is_some()
3760    }
3761}
3762
3763pub struct ConcreteAssistantPanelDelegate;
3764
3765impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
3766    fn active_context_editor(
3767        &self,
3768        workspace: &mut Workspace,
3769        _window: &mut Window,
3770        cx: &mut Context<Workspace>,
3771    ) -> Option<Entity<TextThreadEditor>> {
3772        let panel = workspace.panel::<AgentPanel>(cx)?;
3773        panel.read(cx).active_context_editor()
3774    }
3775
3776    fn open_saved_context(
3777        &self,
3778        workspace: &mut Workspace,
3779        path: Arc<Path>,
3780        window: &mut Window,
3781        cx: &mut Context<Workspace>,
3782    ) -> Task<Result<()>> {
3783        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3784            return Task::ready(Err(anyhow!("Agent panel not found")));
3785        };
3786
3787        panel.update(cx, |panel, cx| {
3788            panel.open_saved_prompt_editor(path, window, cx)
3789        })
3790    }
3791
3792    fn open_remote_context(
3793        &self,
3794        _workspace: &mut Workspace,
3795        _context_id: assistant_context::ContextId,
3796        _window: &mut Window,
3797        _cx: &mut Context<Workspace>,
3798    ) -> Task<Result<Entity<TextThreadEditor>>> {
3799        Task::ready(Err(anyhow!("opening remote context not implemented")))
3800    }
3801
3802    fn quote_selection(
3803        &self,
3804        workspace: &mut Workspace,
3805        selection_ranges: Vec<Range<Anchor>>,
3806        buffer: Entity<MultiBuffer>,
3807        window: &mut Window,
3808        cx: &mut Context<Workspace>,
3809    ) {
3810        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3811            return;
3812        };
3813
3814        if !panel.focus_handle(cx).contains_focused(window, cx) {
3815            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
3816        }
3817
3818        panel.update(cx, |_, cx| {
3819            // Wait to create a new context until the workspace is no longer
3820            // being updated.
3821            cx.defer_in(window, move |panel, window, cx| {
3822                if let Some(message_editor) = panel.active_message_editor() {
3823                    message_editor.update(cx, |message_editor, cx| {
3824                        message_editor.context_store().update(cx, |store, cx| {
3825                            let buffer = buffer.read(cx);
3826                            let selection_ranges = selection_ranges
3827                                .into_iter()
3828                                .flat_map(|range| {
3829                                    let (start_buffer, start) =
3830                                        buffer.text_anchor_for_position(range.start, cx)?;
3831                                    let (end_buffer, end) =
3832                                        buffer.text_anchor_for_position(range.end, cx)?;
3833                                    if start_buffer != end_buffer {
3834                                        return None;
3835                                    }
3836                                    Some((start_buffer, start..end))
3837                                })
3838                                .collect::<Vec<_>>();
3839
3840                            for (buffer, range) in selection_ranges {
3841                                store.add_selection(buffer, range, cx);
3842                            }
3843                        })
3844                    })
3845                } else if let Some(context_editor) = panel.active_context_editor() {
3846                    let snapshot = buffer.read(cx).snapshot(cx);
3847                    let selection_ranges = selection_ranges
3848                        .into_iter()
3849                        .map(|range| range.to_point(&snapshot))
3850                        .collect::<Vec<_>>();
3851
3852                    context_editor.update(cx, |context_editor, cx| {
3853                        context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
3854                    });
3855                }
3856            });
3857        });
3858    }
3859}
3860
3861struct OnboardingUpsell;
3862
3863impl Dismissable for OnboardingUpsell {
3864    const KEY: &'static str = "dismissed-trial-upsell";
3865}
3866
3867struct TrialEndUpsell;
3868
3869impl Dismissable for TrialEndUpsell {
3870    const KEY: &'static str = "dismissed-trial-end-upsell";
3871}