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