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