agent_panel.rs

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