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