agent_panel.rs

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