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