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