agent_panel.rs

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