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