assistant_panel.rs

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