agent_panel.rs

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