assistant_panel.rs

   1use std::ops::Range;
   2use std::path::PathBuf;
   3use std::sync::Arc;
   4use std::time::Duration;
   5
   6use anyhow::{Result, anyhow};
   7use assistant_context_editor::{
   8    AssistantPanelDelegate, ConfigurationError, ContextEditor, SlashCommandCompletionProvider,
   9    humanize_token_count, make_lsp_adapter_delegate, render_remaining_tokens,
  10};
  11use assistant_settings::{AssistantDockPosition, AssistantSettings};
  12use assistant_slash_command::SlashCommandWorkingSet;
  13use assistant_tool::ToolWorkingSet;
  14
  15use client::zed_urls;
  16use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
  17use fs::Fs;
  18use gpui::{
  19    Action, Animation, AnimationExt as _, AnyElement, App, AsyncWindowContext, Corner, Entity,
  20    EventEmitter, FocusHandle, Focusable, FontWeight, KeyContext, Pixels, Subscription, Task,
  21    UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
  22};
  23use language::LanguageRegistry;
  24use language_model::{LanguageModelProviderTosView, LanguageModelRegistry};
  25use language_model_selector::ToggleModelSelector;
  26use project::Project;
  27use prompt_library::{PromptLibrary, open_prompt_library};
  28use prompt_store::{PromptBuilder, PromptId};
  29use proto::Plan;
  30use settings::{Settings, update_settings_file};
  31use time::UtcOffset;
  32use ui::{
  33    Banner, ContextMenu, KeyBinding, PopoverMenu, PopoverMenuHandle, Tab, Tooltip, prelude::*,
  34};
  35use util::ResultExt as _;
  36use workspace::Workspace;
  37use workspace::dock::{DockPosition, Panel, PanelEvent};
  38use zed_actions::agent::OpenConfiguration;
  39use zed_actions::assistant::{OpenPromptLibrary, ToggleFocus};
  40
  41use crate::active_thread::{ActiveThread, ActiveThreadEvent};
  42use crate::assistant_configuration::{AssistantConfiguration, AssistantConfigurationEvent};
  43use crate::history_store::{HistoryEntry, HistoryStore};
  44use crate::message_editor::{MessageEditor, MessageEditorEvent};
  45use crate::thread::{Thread, ThreadError, ThreadId, TokenUsageRatio};
  46use crate::thread_history::{PastContext, PastThread, ThreadHistory};
  47use crate::thread_store::ThreadStore;
  48use crate::ui::UsageBanner;
  49use crate::{
  50    AddContextServer, AgentDiff, ExpandMessageEditor, InlineAssistant, NewTextThread, NewThread,
  51    OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ThreadEvent, ToggleContextPicker,
  52};
  53
  54pub fn init(cx: &mut App) {
  55    cx.observe_new(
  56        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
  57            workspace
  58                .register_action(|workspace, action: &NewThread, window, cx| {
  59                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  60                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
  61                        workspace.focus_panel::<AssistantPanel>(window, cx);
  62                    }
  63                })
  64                .register_action(|workspace, _: &OpenHistory, window, cx| {
  65                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  66                        workspace.focus_panel::<AssistantPanel>(window, cx);
  67                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
  68                    }
  69                })
  70                .register_action(|workspace, _: &OpenConfiguration, window, cx| {
  71                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  72                        workspace.focus_panel::<AssistantPanel>(window, cx);
  73                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
  74                    }
  75                })
  76                .register_action(|workspace, _: &NewTextThread, window, cx| {
  77                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  78                        workspace.focus_panel::<AssistantPanel>(window, cx);
  79                        panel.update(cx, |panel, cx| panel.new_prompt_editor(window, cx));
  80                    }
  81                })
  82                .register_action(|workspace, _: &OpenPromptLibrary, window, cx| {
  83                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  84                        workspace.focus_panel::<AssistantPanel>(window, cx);
  85                        panel.update(cx, |panel, cx| {
  86                            panel.deploy_prompt_library(&OpenPromptLibrary::default(), window, cx)
  87                        });
  88                    }
  89                })
  90                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
  91                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  92                        workspace.focus_panel::<AssistantPanel>(window, cx);
  93                        let thread = panel.read(cx).thread.read(cx).thread().clone();
  94                        AgentDiff::deploy_in_workspace(thread, workspace, window, cx);
  95                    }
  96                })
  97                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
  98                    if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
  99                        workspace.focus_panel::<AssistantPanel>(window, cx);
 100                        panel.update(cx, |panel, cx| {
 101                            panel.message_editor.update(cx, |editor, cx| {
 102                                editor.expand_message_editor(&ExpandMessageEditor, window, cx);
 103                            });
 104                        });
 105                    }
 106                });
 107        },
 108    )
 109    .detach();
 110}
 111
 112enum ActiveView {
 113    Thread {
 114        change_title_editor: Entity<Editor>,
 115        _subscriptions: Vec<gpui::Subscription>,
 116    },
 117    PromptEditor {
 118        context_editor: Entity<ContextEditor>,
 119    },
 120    History,
 121    Configuration,
 122}
 123
 124impl ActiveView {
 125    pub fn thread(thread: Entity<Thread>, window: &mut Window, cx: &mut App) -> Self {
 126        let summary = thread.read(cx).summary_or_default();
 127
 128        let editor = cx.new(|cx| {
 129            let mut editor = Editor::single_line(window, cx);
 130            editor.set_text(summary, window, cx);
 131            editor
 132        });
 133
 134        let subscriptions = vec![
 135            window.subscribe(&editor, cx, {
 136                {
 137                    let thread = thread.clone();
 138                    move |editor, event, window, cx| match event {
 139                        EditorEvent::BufferEdited => {
 140                            let new_summary = editor.read(cx).text(cx);
 141
 142                            thread.update(cx, |thread, cx| {
 143                                thread.set_summary(new_summary, cx);
 144                            })
 145                        }
 146                        EditorEvent::Blurred => {
 147                            if editor.read(cx).text(cx).is_empty() {
 148                                let summary = thread.read(cx).summary_or_default();
 149
 150                                editor.update(cx, |editor, cx| {
 151                                    editor.set_text(summary, window, cx);
 152                                });
 153                            }
 154                        }
 155                        _ => {}
 156                    }
 157                }
 158            }),
 159            window.subscribe(&thread, cx, {
 160                let editor = editor.clone();
 161                move |thread, event, window, cx| match event {
 162                    ThreadEvent::SummaryGenerated => {
 163                        let summary = thread.read(cx).summary_or_default();
 164
 165                        editor.update(cx, |editor, cx| {
 166                            editor.set_text(summary, window, cx);
 167                        })
 168                    }
 169                    _ => {}
 170                }
 171            }),
 172        ];
 173
 174        Self::Thread {
 175            change_title_editor: editor,
 176            _subscriptions: subscriptions,
 177        }
 178    }
 179}
 180
 181pub struct AssistantPanel {
 182    workspace: WeakEntity<Workspace>,
 183    project: Entity<Project>,
 184    fs: Arc<dyn Fs>,
 185    language_registry: Arc<LanguageRegistry>,
 186    thread_store: Entity<ThreadStore>,
 187    thread: Entity<ActiveThread>,
 188    message_editor: Entity<MessageEditor>,
 189    _active_thread_subscriptions: Vec<Subscription>,
 190    context_store: Entity<assistant_context_editor::ContextStore>,
 191    configuration: Option<Entity<AssistantConfiguration>>,
 192    configuration_subscription: Option<Subscription>,
 193    local_timezone: UtcOffset,
 194    active_view: ActiveView,
 195    previous_view: Option<ActiveView>,
 196    history_store: Entity<HistoryStore>,
 197    history: Entity<ThreadHistory>,
 198    assistant_dropdown_menu_handle: PopoverMenuHandle<ContextMenu>,
 199    width: Option<Pixels>,
 200    height: Option<Pixels>,
 201}
 202
 203impl AssistantPanel {
 204    pub fn load(
 205        workspace: WeakEntity<Workspace>,
 206        prompt_builder: Arc<PromptBuilder>,
 207        cx: AsyncWindowContext,
 208    ) -> Task<Result<Entity<Self>>> {
 209        cx.spawn(async move |cx| {
 210            let tools = cx.new(|_| ToolWorkingSet::default())?;
 211            let thread_store = workspace
 212                .update(cx, |workspace, cx| {
 213                    let project = workspace.project().clone();
 214                    ThreadStore::load(project, tools.clone(), prompt_builder.clone(), cx)
 215                })?
 216                .await?;
 217
 218            let slash_commands = Arc::new(SlashCommandWorkingSet::default());
 219            let context_store = workspace
 220                .update(cx, |workspace, cx| {
 221                    let project = workspace.project().clone();
 222                    assistant_context_editor::ContextStore::new(
 223                        project,
 224                        prompt_builder.clone(),
 225                        slash_commands,
 226                        cx,
 227                    )
 228                })?
 229                .await?;
 230
 231            workspace.update_in(cx, |workspace, window, cx| {
 232                cx.new(|cx| Self::new(workspace, thread_store, context_store, window, cx))
 233            })
 234        })
 235    }
 236
 237    fn new(
 238        workspace: &Workspace,
 239        thread_store: Entity<ThreadStore>,
 240        context_store: Entity<assistant_context_editor::ContextStore>,
 241        window: &mut Window,
 242        cx: &mut Context<Self>,
 243    ) -> Self {
 244        let thread = thread_store.update(cx, |this, cx| this.create_thread(cx));
 245        let fs = workspace.app_state().fs.clone();
 246        let project = workspace.project();
 247        let language_registry = project.read(cx).languages().clone();
 248        let workspace = workspace.weak_handle();
 249        let weak_self = cx.entity().downgrade();
 250
 251        let message_editor_context_store = cx.new(|_cx| {
 252            crate::context_store::ContextStore::new(
 253                project.downgrade(),
 254                Some(thread_store.downgrade()),
 255            )
 256        });
 257
 258        let message_editor = cx.new(|cx| {
 259            MessageEditor::new(
 260                fs.clone(),
 261                workspace.clone(),
 262                message_editor_context_store.clone(),
 263                thread_store.downgrade(),
 264                thread.clone(),
 265                window,
 266                cx,
 267            )
 268        });
 269
 270        let message_editor_subscription =
 271            cx.subscribe(&message_editor, |_, _, event, cx| match event {
 272                MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
 273                    cx.notify();
 274                }
 275            });
 276
 277        let history_store =
 278            cx.new(|cx| HistoryStore::new(thread_store.clone(), context_store.clone(), cx));
 279
 280        cx.observe(&history_store, |_, _, cx| cx.notify()).detach();
 281
 282        let active_view = ActiveView::thread(thread.clone(), window, cx);
 283        let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
 284            if let ThreadEvent::MessageAdded(_) = &event {
 285                // needed to leave empty state
 286                cx.notify();
 287            }
 288        });
 289        let thread = cx.new(|cx| {
 290            ActiveThread::new(
 291                thread.clone(),
 292                thread_store.clone(),
 293                language_registry.clone(),
 294                message_editor_context_store.clone(),
 295                workspace.clone(),
 296                window,
 297                cx,
 298            )
 299        });
 300
 301        let active_thread_subscription = cx.subscribe(&thread, |_, _, event, cx| match &event {
 302            ActiveThreadEvent::EditingMessageTokenCountChanged => {
 303                cx.notify();
 304            }
 305        });
 306
 307        Self {
 308            active_view,
 309            workspace,
 310            project: project.clone(),
 311            fs: fs.clone(),
 312            language_registry,
 313            thread_store: thread_store.clone(),
 314            thread,
 315            message_editor,
 316            _active_thread_subscriptions: vec![
 317                thread_subscription,
 318                active_thread_subscription,
 319                message_editor_subscription,
 320            ],
 321            context_store,
 322            configuration: None,
 323            configuration_subscription: None,
 324            local_timezone: UtcOffset::from_whole_seconds(
 325                chrono::Local::now().offset().local_minus_utc(),
 326            )
 327            .unwrap(),
 328            previous_view: None,
 329            history_store: history_store.clone(),
 330            history: cx.new(|cx| ThreadHistory::new(weak_self, history_store, window, cx)),
 331            assistant_dropdown_menu_handle: PopoverMenuHandle::default(),
 332            width: None,
 333            height: None,
 334        }
 335    }
 336
 337    pub fn toggle_focus(
 338        workspace: &mut Workspace,
 339        _: &ToggleFocus,
 340        window: &mut Window,
 341        cx: &mut Context<Workspace>,
 342    ) {
 343        if workspace
 344            .panel::<Self>(cx)
 345            .is_some_and(|panel| panel.read(cx).enabled(cx))
 346        {
 347            workspace.toggle_panel_focus::<Self>(window, cx);
 348        }
 349    }
 350
 351    pub(crate) fn local_timezone(&self) -> UtcOffset {
 352        self.local_timezone
 353    }
 354
 355    pub(crate) fn thread_store(&self) -> &Entity<ThreadStore> {
 356        &self.thread_store
 357    }
 358
 359    fn cancel(
 360        &mut self,
 361        _: &editor::actions::Cancel,
 362        _window: &mut Window,
 363        cx: &mut Context<Self>,
 364    ) {
 365        self.thread
 366            .update(cx, |thread, cx| thread.cancel_last_completion(cx));
 367    }
 368
 369    fn new_thread(&mut self, action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
 370        let thread = self
 371            .thread_store
 372            .update(cx, |this, cx| this.create_thread(cx));
 373
 374        let thread_view = ActiveView::thread(thread.clone(), window, cx);
 375        self.set_active_view(thread_view, window, cx);
 376
 377        let message_editor_context_store = cx.new(|_cx| {
 378            crate::context_store::ContextStore::new(
 379                self.project.downgrade(),
 380                Some(self.thread_store.downgrade()),
 381            )
 382        });
 383
 384        if let Some(other_thread_id) = action.from_thread_id.clone() {
 385            let other_thread_task = self
 386                .thread_store
 387                .update(cx, |this, cx| this.open_thread(&other_thread_id, cx));
 388
 389            cx.spawn({
 390                let context_store = message_editor_context_store.clone();
 391
 392                async move |_panel, cx| {
 393                    let other_thread = other_thread_task.await?;
 394
 395                    context_store.update(cx, |this, cx| {
 396                        this.add_thread(other_thread, false, cx);
 397                    })?;
 398                    anyhow::Ok(())
 399                }
 400            })
 401            .detach_and_log_err(cx);
 402        }
 403
 404        let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
 405            if let ThreadEvent::MessageAdded(_) = &event {
 406                // needed to leave empty state
 407                cx.notify();
 408            }
 409        });
 410
 411        self.thread = cx.new(|cx| {
 412            ActiveThread::new(
 413                thread.clone(),
 414                self.thread_store.clone(),
 415                self.language_registry.clone(),
 416                message_editor_context_store.clone(),
 417                self.workspace.clone(),
 418                window,
 419                cx,
 420            )
 421        });
 422
 423        let active_thread_subscription =
 424            cx.subscribe(&self.thread, |_, _, event, cx| match &event {
 425                ActiveThreadEvent::EditingMessageTokenCountChanged => {
 426                    cx.notify();
 427                }
 428            });
 429
 430        self.message_editor = cx.new(|cx| {
 431            MessageEditor::new(
 432                self.fs.clone(),
 433                self.workspace.clone(),
 434                message_editor_context_store,
 435                self.thread_store.downgrade(),
 436                thread,
 437                window,
 438                cx,
 439            )
 440        });
 441        self.message_editor.focus_handle(cx).focus(window);
 442
 443        let message_editor_subscription =
 444            cx.subscribe(&self.message_editor, |_, _, event, cx| match event {
 445                MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
 446                    cx.notify();
 447                }
 448            });
 449
 450        self._active_thread_subscriptions = vec![
 451            thread_subscription,
 452            active_thread_subscription,
 453            message_editor_subscription,
 454        ];
 455    }
 456
 457    fn new_prompt_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 458        let context = self
 459            .context_store
 460            .update(cx, |context_store, cx| context_store.create(cx));
 461        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
 462            .log_err()
 463            .flatten();
 464
 465        let context_editor = cx.new(|cx| {
 466            let mut editor = ContextEditor::for_context(
 467                context,
 468                self.fs.clone(),
 469                self.workspace.clone(),
 470                self.project.clone(),
 471                lsp_adapter_delegate,
 472                window,
 473                cx,
 474            );
 475            editor.insert_default_prompt(window, cx);
 476            editor
 477        });
 478
 479        self.set_active_view(
 480            ActiveView::PromptEditor {
 481                context_editor: context_editor.clone(),
 482            },
 483            window,
 484            cx,
 485        );
 486        context_editor.focus_handle(cx).focus(window);
 487    }
 488
 489    fn deploy_prompt_library(
 490        &mut self,
 491        action: &OpenPromptLibrary,
 492        _window: &mut Window,
 493        cx: &mut Context<Self>,
 494    ) {
 495        open_prompt_library(
 496            self.language_registry.clone(),
 497            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
 498            Arc::new(|| {
 499                Box::new(SlashCommandCompletionProvider::new(
 500                    Arc::new(SlashCommandWorkingSet::default()),
 501                    None,
 502                    None,
 503                ))
 504            }),
 505            action.prompt_to_focus.map(|uuid| PromptId::User { uuid }),
 506            cx,
 507        )
 508        .detach_and_log_err(cx);
 509    }
 510
 511    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 512        if matches!(self.active_view, ActiveView::History) {
 513            if let Some(previous_view) = self.previous_view.take() {
 514                self.set_active_view(previous_view, window, cx);
 515            }
 516        } else {
 517            self.thread_store
 518                .update(cx, |thread_store, cx| thread_store.reload(cx))
 519                .detach_and_log_err(cx);
 520            self.set_active_view(ActiveView::History, window, cx);
 521        }
 522        cx.notify();
 523    }
 524
 525    pub(crate) fn open_saved_prompt_editor(
 526        &mut self,
 527        path: PathBuf,
 528        window: &mut Window,
 529        cx: &mut Context<Self>,
 530    ) -> Task<Result<()>> {
 531        let context = self
 532            .context_store
 533            .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
 534        let fs = self.fs.clone();
 535        let project = self.project.clone();
 536        let workspace = self.workspace.clone();
 537
 538        let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err().flatten();
 539
 540        cx.spawn_in(window, async move |this, cx| {
 541            let context = context.await?;
 542            this.update_in(cx, |this, window, cx| {
 543                let editor = cx.new(|cx| {
 544                    ContextEditor::for_context(
 545                        context,
 546                        fs,
 547                        workspace,
 548                        project,
 549                        lsp_adapter_delegate,
 550                        window,
 551                        cx,
 552                    )
 553                });
 554                this.set_active_view(
 555                    ActiveView::PromptEditor {
 556                        context_editor: editor,
 557                    },
 558                    window,
 559                    cx,
 560                );
 561
 562                anyhow::Ok(())
 563            })??;
 564            Ok(())
 565        })
 566    }
 567
 568    pub(crate) fn open_thread(
 569        &mut self,
 570        thread_id: &ThreadId,
 571        window: &mut Window,
 572        cx: &mut Context<Self>,
 573    ) -> Task<Result<()>> {
 574        let open_thread_task = self
 575            .thread_store
 576            .update(cx, |this, cx| this.open_thread(thread_id, cx));
 577
 578        cx.spawn_in(window, async move |this, cx| {
 579            let thread = open_thread_task.await?;
 580            this.update_in(cx, |this, window, cx| {
 581                let thread_view = ActiveView::thread(thread.clone(), window, cx);
 582                this.set_active_view(thread_view, window, cx);
 583                let message_editor_context_store = cx.new(|_cx| {
 584                    crate::context_store::ContextStore::new(
 585                        this.project.downgrade(),
 586                        Some(this.thread_store.downgrade()),
 587                    )
 588                });
 589                let thread_subscription = cx.subscribe(&thread, |_, _, event, cx| {
 590                    if let ThreadEvent::MessageAdded(_) = &event {
 591                        // needed to leave empty state
 592                        cx.notify();
 593                    }
 594                });
 595
 596                this.thread = cx.new(|cx| {
 597                    ActiveThread::new(
 598                        thread.clone(),
 599                        this.thread_store.clone(),
 600                        this.language_registry.clone(),
 601                        message_editor_context_store.clone(),
 602                        this.workspace.clone(),
 603                        window,
 604                        cx,
 605                    )
 606                });
 607
 608                let active_thread_subscription =
 609                    cx.subscribe(&this.thread, |_, _, event, cx| match &event {
 610                        ActiveThreadEvent::EditingMessageTokenCountChanged => {
 611                            cx.notify();
 612                        }
 613                    });
 614
 615                this.message_editor = cx.new(|cx| {
 616                    MessageEditor::new(
 617                        this.fs.clone(),
 618                        this.workspace.clone(),
 619                        message_editor_context_store,
 620                        this.thread_store.downgrade(),
 621                        thread,
 622                        window,
 623                        cx,
 624                    )
 625                });
 626                this.message_editor.focus_handle(cx).focus(window);
 627
 628                let message_editor_subscription =
 629                    cx.subscribe(&this.message_editor, |_, _, event, cx| match event {
 630                        MessageEditorEvent::Changed | MessageEditorEvent::EstimatedTokenCount => {
 631                            cx.notify();
 632                        }
 633                    });
 634
 635                this._active_thread_subscriptions = vec![
 636                    thread_subscription,
 637                    active_thread_subscription,
 638                    message_editor_subscription,
 639                ];
 640            })
 641        })
 642    }
 643
 644    pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
 645        match self.active_view {
 646            ActiveView::Configuration | ActiveView::History => {
 647                self.active_view =
 648                    ActiveView::thread(self.thread.read(cx).thread().clone(), window, cx);
 649                self.message_editor.focus_handle(cx).focus(window);
 650                cx.notify();
 651            }
 652            _ => {}
 653        }
 654    }
 655
 656    pub fn open_agent_diff(
 657        &mut self,
 658        _: &OpenAgentDiff,
 659        window: &mut Window,
 660        cx: &mut Context<Self>,
 661    ) {
 662        let thread = self.thread.read(cx).thread().clone();
 663        self.workspace
 664            .update(cx, |workspace, cx| {
 665                AgentDiff::deploy_in_workspace(thread, workspace, window, cx)
 666            })
 667            .log_err();
 668    }
 669
 670    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 671        let context_server_manager = self.thread_store.read(cx).context_server_manager();
 672        let tools = self.thread_store.read(cx).tools();
 673        let fs = self.fs.clone();
 674
 675        self.set_active_view(ActiveView::Configuration, window, cx);
 676        self.configuration =
 677            Some(cx.new(|cx| {
 678                AssistantConfiguration::new(fs, context_server_manager, tools, window, cx)
 679            }));
 680
 681        if let Some(configuration) = self.configuration.as_ref() {
 682            self.configuration_subscription = Some(cx.subscribe_in(
 683                configuration,
 684                window,
 685                Self::handle_assistant_configuration_event,
 686            ));
 687
 688            configuration.focus_handle(cx).focus(window);
 689        }
 690    }
 691
 692    pub(crate) fn open_active_thread_as_markdown(
 693        &mut self,
 694        _: &OpenActiveThreadAsMarkdown,
 695        window: &mut Window,
 696        cx: &mut Context<Self>,
 697    ) {
 698        let Some(workspace) = self
 699            .workspace
 700            .upgrade()
 701            .ok_or_else(|| anyhow!("workspace dropped"))
 702            .log_err()
 703        else {
 704            return;
 705        };
 706
 707        let markdown_language_task = workspace
 708            .read(cx)
 709            .app_state()
 710            .languages
 711            .language_for_name("Markdown");
 712        let thread = self.active_thread(cx);
 713        cx.spawn_in(window, async move |_this, cx| {
 714            let markdown_language = markdown_language_task.await?;
 715
 716            workspace.update_in(cx, |workspace, window, cx| {
 717                let thread = thread.read(cx);
 718                let markdown = thread.to_markdown(cx)?;
 719                let thread_summary = thread
 720                    .summary()
 721                    .map(|summary| summary.to_string())
 722                    .unwrap_or_else(|| "Thread".to_string());
 723
 724                let project = workspace.project().clone();
 725                let buffer = project.update(cx, |project, cx| {
 726                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
 727                });
 728                let buffer = cx.new(|cx| {
 729                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
 730                });
 731
 732                workspace.add_item_to_active_pane(
 733                    Box::new(cx.new(|cx| {
 734                        let mut editor =
 735                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
 736                        editor.set_breadcrumb_header(thread_summary);
 737                        editor
 738                    })),
 739                    None,
 740                    true,
 741                    window,
 742                    cx,
 743                );
 744
 745                anyhow::Ok(())
 746            })
 747        })
 748        .detach_and_log_err(cx);
 749    }
 750
 751    fn handle_assistant_configuration_event(
 752        &mut self,
 753        _entity: &Entity<AssistantConfiguration>,
 754        event: &AssistantConfigurationEvent,
 755        window: &mut Window,
 756        cx: &mut Context<Self>,
 757    ) {
 758        match event {
 759            AssistantConfigurationEvent::NewThread(provider) => {
 760                if LanguageModelRegistry::read_global(cx)
 761                    .default_model()
 762                    .map_or(true, |model| model.provider.id() != provider.id())
 763                {
 764                    if let Some(model) = provider.default_model(cx) {
 765                        update_settings_file::<AssistantSettings>(
 766                            self.fs.clone(),
 767                            cx,
 768                            move |settings, _| settings.set_model(model),
 769                        );
 770                    }
 771                }
 772
 773                self.new_thread(&NewThread::default(), window, cx);
 774            }
 775        }
 776    }
 777
 778    pub(crate) fn active_thread(&self, cx: &App) -> Entity<Thread> {
 779        self.thread.read(cx).thread().clone()
 780    }
 781
 782    pub(crate) fn delete_thread(
 783        &mut self,
 784        thread_id: &ThreadId,
 785        cx: &mut Context<Self>,
 786    ) -> Task<Result<()>> {
 787        self.thread_store
 788            .update(cx, |this, cx| this.delete_thread(thread_id, cx))
 789    }
 790
 791    pub(crate) fn has_active_thread(&self) -> bool {
 792        matches!(self.active_view, ActiveView::Thread { .. })
 793    }
 794
 795    pub(crate) fn active_context_editor(&self) -> Option<Entity<ContextEditor>> {
 796        match &self.active_view {
 797            ActiveView::PromptEditor { context_editor } => Some(context_editor.clone()),
 798            _ => None,
 799        }
 800    }
 801
 802    pub(crate) fn delete_context(
 803        &mut self,
 804        path: PathBuf,
 805        cx: &mut Context<Self>,
 806    ) -> Task<Result<()>> {
 807        self.context_store
 808            .update(cx, |this, cx| this.delete_local_context(path, cx))
 809    }
 810
 811    fn set_active_view(
 812        &mut self,
 813        new_view: ActiveView,
 814        window: &mut Window,
 815        cx: &mut Context<Self>,
 816    ) {
 817        let current_is_history = matches!(self.active_view, ActiveView::History);
 818        let new_is_history = matches!(new_view, ActiveView::History);
 819
 820        if current_is_history && !new_is_history {
 821            self.active_view = new_view;
 822        } else if !current_is_history && new_is_history {
 823            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
 824        } else {
 825            if !new_is_history {
 826                self.previous_view = None;
 827            }
 828            self.active_view = new_view;
 829        }
 830
 831        self.focus_handle(cx).focus(window);
 832    }
 833}
 834
 835impl Focusable for AssistantPanel {
 836    fn focus_handle(&self, cx: &App) -> FocusHandle {
 837        match &self.active_view {
 838            ActiveView::Thread { .. } => self.message_editor.focus_handle(cx),
 839            ActiveView::History => self.history.focus_handle(cx),
 840            ActiveView::PromptEditor { context_editor } => context_editor.focus_handle(cx),
 841            ActiveView::Configuration => {
 842                if let Some(configuration) = self.configuration.as_ref() {
 843                    configuration.focus_handle(cx)
 844                } else {
 845                    cx.focus_handle()
 846                }
 847            }
 848        }
 849    }
 850}
 851
 852impl EventEmitter<PanelEvent> for AssistantPanel {}
 853
 854impl Panel for AssistantPanel {
 855    fn persistent_name() -> &'static str {
 856        "AgentPanel"
 857    }
 858
 859    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
 860        match AssistantSettings::get_global(cx).dock {
 861            AssistantDockPosition::Left => DockPosition::Left,
 862            AssistantDockPosition::Bottom => DockPosition::Bottom,
 863            AssistantDockPosition::Right => DockPosition::Right,
 864        }
 865    }
 866
 867    fn position_is_valid(&self, _: DockPosition) -> bool {
 868        true
 869    }
 870
 871    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
 872        settings::update_settings_file::<AssistantSettings>(
 873            self.fs.clone(),
 874            cx,
 875            move |settings, _| {
 876                let dock = match position {
 877                    DockPosition::Left => AssistantDockPosition::Left,
 878                    DockPosition::Bottom => AssistantDockPosition::Bottom,
 879                    DockPosition::Right => AssistantDockPosition::Right,
 880                };
 881                settings.set_dock(dock);
 882            },
 883        );
 884    }
 885
 886    fn size(&self, window: &Window, cx: &App) -> Pixels {
 887        let settings = AssistantSettings::get_global(cx);
 888        match self.position(window, cx) {
 889            DockPosition::Left | DockPosition::Right => {
 890                self.width.unwrap_or(settings.default_width)
 891            }
 892            DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
 893        }
 894    }
 895
 896    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
 897        match self.position(window, cx) {
 898            DockPosition::Left | DockPosition::Right => self.width = size,
 899            DockPosition::Bottom => self.height = size,
 900        }
 901        cx.notify();
 902    }
 903
 904    fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
 905
 906    fn remote_id() -> Option<proto::PanelId> {
 907        Some(proto::PanelId::AssistantPanel)
 908    }
 909
 910    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
 911        (self.enabled(cx) && AssistantSettings::get_global(cx).button)
 912            .then_some(IconName::ZedAssistant)
 913    }
 914
 915    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
 916        Some("Agent Panel")
 917    }
 918
 919    fn toggle_action(&self) -> Box<dyn Action> {
 920        Box::new(ToggleFocus)
 921    }
 922
 923    fn activation_priority(&self) -> u32 {
 924        3
 925    }
 926
 927    fn enabled(&self, cx: &App) -> bool {
 928        AssistantSettings::get_global(cx).enabled
 929    }
 930}
 931
 932impl AssistantPanel {
 933    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
 934        const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
 935
 936        let content = match &self.active_view {
 937            ActiveView::Thread {
 938                change_title_editor,
 939                ..
 940            } => {
 941                let active_thread = self.thread.read(cx);
 942                let is_empty = active_thread.is_empty();
 943
 944                let summary = active_thread.summary(cx);
 945
 946                if is_empty {
 947                    Label::new(Thread::DEFAULT_SUMMARY.clone())
 948                        .truncate()
 949                        .ml_2()
 950                        .into_any_element()
 951                } else if summary.is_none() {
 952                    Label::new(LOADING_SUMMARY_PLACEHOLDER)
 953                        .ml_2()
 954                        .truncate()
 955                        .into_any_element()
 956                } else {
 957                    div()
 958                        .ml_2()
 959                        .w_full()
 960                        .child(change_title_editor.clone())
 961                        .into_any_element()
 962                }
 963            }
 964            ActiveView::PromptEditor { context_editor } => {
 965                let title = SharedString::from(context_editor.read(cx).title(cx).to_string());
 966                Label::new(title).ml_2().truncate().into_any_element()
 967            }
 968            ActiveView::History => Label::new("History").truncate().into_any_element(),
 969            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
 970        };
 971
 972        h_flex()
 973            .key_context("TitleEditor")
 974            .id("TitleEditor")
 975            .flex_grow()
 976            .w_full()
 977            .max_w_full()
 978            .overflow_x_scroll()
 979            .child(content)
 980            .into_any()
 981    }
 982
 983    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 984        let active_thread = self.thread.read(cx);
 985        let thread = active_thread.thread().read(cx);
 986        let thread_id = thread.id().clone();
 987        let is_empty = active_thread.is_empty();
 988        let is_history = matches!(self.active_view, ActiveView::History);
 989
 990        let show_token_count = match &self.active_view {
 991            ActiveView::Thread { .. } => !is_empty,
 992            ActiveView::PromptEditor { .. } => true,
 993            _ => false,
 994        };
 995
 996        let focus_handle = self.focus_handle(cx);
 997
 998        let go_back_button = match &self.active_view {
 999            ActiveView::History | ActiveView::Configuration => Some(
1000                div().pl_1().child(
1001                    IconButton::new("go-back", IconName::ArrowLeft)
1002                        .icon_size(IconSize::Small)
1003                        .on_click(cx.listener(|this, _, window, cx| {
1004                            this.go_back(&workspace::GoBack, window, cx);
1005                        }))
1006                        .tooltip({
1007                            let focus_handle = focus_handle.clone();
1008                            move |window, cx| {
1009                                Tooltip::for_action_in(
1010                                    "Go Back",
1011                                    &workspace::GoBack,
1012                                    &focus_handle,
1013                                    window,
1014                                    cx,
1015                                )
1016                            }
1017                        }),
1018                ),
1019            ),
1020            _ => None,
1021        };
1022
1023        h_flex()
1024            .id("assistant-toolbar")
1025            .h(Tab::container_height(cx))
1026            .max_w_full()
1027            .flex_none()
1028            .justify_between()
1029            .gap_2()
1030            .bg(cx.theme().colors().tab_bar_background)
1031            .border_b_1()
1032            .border_color(cx.theme().colors().border)
1033            .child(
1034                h_flex()
1035                    .w_full()
1036                    .gap_1()
1037                    .children(go_back_button)
1038                    .child(self.render_title_view(window, cx)),
1039            )
1040            .child(
1041                h_flex()
1042                    .h_full()
1043                    .gap_2()
1044                    .when(show_token_count, |parent|
1045                        parent.children(self.render_token_count(&thread, cx))
1046                    )
1047                    .child(
1048                        h_flex()
1049                            .h_full()
1050                            .gap(DynamicSpacing::Base02.rems(cx))
1051                            .px(DynamicSpacing::Base08.rems(cx))
1052                            .border_l_1()
1053                            .border_color(cx.theme().colors().border)
1054                            .child(
1055                                IconButton::new("new", IconName::Plus)
1056                                    .icon_size(IconSize::Small)
1057                                    .style(ButtonStyle::Subtle)
1058                                    .tooltip(move |window, cx| {
1059                                        Tooltip::for_action_in(
1060                                            "New Thread",
1061                                            &NewThread::default(),
1062                                            &focus_handle,
1063                                            window,
1064                                            cx,
1065                                        )
1066                                    })
1067                                    .on_click(move |_event, window, cx| {
1068                                        window.dispatch_action(
1069                                            NewThread::default().boxed_clone(),
1070                                            cx,
1071                                        );
1072                                    }),
1073                            )
1074                            .child(
1075                                IconButton::new("open-history", IconName::HistoryRerun)
1076                                    .icon_size(IconSize::Small)
1077                                    .toggle_state(is_history)
1078                                    .selected_icon_color(Color::Accent)
1079                                    .tooltip({
1080                                        let focus_handle = self.focus_handle(cx);
1081                                        move |window, cx| {
1082                                            Tooltip::for_action_in(
1083                                                "History",
1084                                                &OpenHistory,
1085                                                &focus_handle,
1086                                                window,
1087                                                cx,
1088                                            )
1089                                        }
1090                                    })
1091                                    .on_click(move |_event, window, cx| {
1092                                        window.dispatch_action(OpenHistory.boxed_clone(), cx);
1093                                    }),
1094                            )
1095                            .child(
1096                                PopoverMenu::new("assistant-menu")
1097                                    .trigger_with_tooltip(
1098                                        IconButton::new("new", IconName::Ellipsis)
1099                                            .icon_size(IconSize::Small)
1100                                            .style(ButtonStyle::Subtle),
1101                                        Tooltip::text("Toggle Agent Menu"),
1102                                    )
1103                                    .anchor(Corner::TopRight)
1104                                    .with_handle(self.assistant_dropdown_menu_handle.clone())
1105                                    .menu(move |window, cx| {
1106                                        Some(ContextMenu::build(
1107                                            window,
1108                                            cx,
1109                                            |menu, _window, _cx| {
1110                                                menu
1111                                                    .when(!is_empty, |menu| {
1112                                                        menu.action(
1113                                                            "Start New From Summary",
1114                                                            Box::new(NewThread {
1115                                                                from_thread_id: Some(thread_id.clone()),
1116                                                            }),
1117                                                        ).separator()
1118                                                    })
1119                                                    .action(
1120                                                    "New Text Thread",
1121                                                    NewTextThread.boxed_clone(),
1122                                                )
1123                                                .action("Prompt Library", Box::new(OpenPromptLibrary::default()))
1124                                                .action("Settings", Box::new(OpenConfiguration))
1125                                                .separator()
1126                                                .header("MCPs")
1127                                                .action(
1128                                                    "View Server Extensions",
1129                                                    Box::new(zed_actions::Extensions {
1130                                                        category_filter: Some(
1131                                                            zed_actions::ExtensionCategoryFilter::ContextServers,
1132                                                        ),
1133                                                        }),
1134                                                )
1135                                                .action("Add Custom Server", Box::new(AddContextServer))
1136                                            },
1137                                        ))
1138                                    }),
1139                            ),
1140                    ),
1141            )
1142    }
1143
1144    fn render_token_count(&self, thread: &Thread, cx: &App) -> Option<AnyElement> {
1145        let is_generating = thread.is_generating();
1146        let message_editor = self.message_editor.read(cx);
1147
1148        let conversation_token_usage = thread.total_token_usage(cx);
1149        let (total_token_usage, is_estimating) = if let Some((editing_message_id, unsent_tokens)) =
1150            self.thread.read(cx).editing_message_id()
1151        {
1152            let combined = thread
1153                .token_usage_up_to_message(editing_message_id, cx)
1154                .add(unsent_tokens);
1155
1156            (combined, unsent_tokens > 0)
1157        } else {
1158            let unsent_tokens = message_editor.last_estimated_token_count().unwrap_or(0);
1159            let combined = conversation_token_usage.add(unsent_tokens);
1160
1161            (combined, unsent_tokens > 0)
1162        };
1163
1164        let is_waiting_to_update_token_count = message_editor.is_waiting_to_update_token_count();
1165
1166        match &self.active_view {
1167            ActiveView::Thread { .. } => {
1168                if total_token_usage.total == 0 {
1169                    return None;
1170                }
1171
1172                let token_color = match total_token_usage.ratio() {
1173                    TokenUsageRatio::Normal if is_estimating => Color::Default,
1174                    TokenUsageRatio::Normal => Color::Muted,
1175                    TokenUsageRatio::Warning => Color::Warning,
1176                    TokenUsageRatio::Exceeded => Color::Error,
1177                };
1178
1179                let token_count = h_flex()
1180                    .id("token-count")
1181                    .flex_shrink_0()
1182                    .gap_0p5()
1183                    .when(!is_generating && is_estimating, |parent| {
1184                        parent
1185                            .child(
1186                                h_flex()
1187                                    .mr_1()
1188                                    .size_2p5()
1189                                    .justify_center()
1190                                    .rounded_full()
1191                                    .bg(cx.theme().colors().text.opacity(0.1))
1192                                    .child(
1193                                        div().size_1().rounded_full().bg(cx.theme().colors().text),
1194                                    ),
1195                            )
1196                            .tooltip(move |window, cx| {
1197                                Tooltip::with_meta(
1198                                    "Estimated New Token Count",
1199                                    None,
1200                                    format!(
1201                                        "Current Conversation Tokens: {}",
1202                                        humanize_token_count(conversation_token_usage.total)
1203                                    ),
1204                                    window,
1205                                    cx,
1206                                )
1207                            })
1208                    })
1209                    .child(
1210                        Label::new(humanize_token_count(total_token_usage.total))
1211                            .size(LabelSize::Small)
1212                            .color(token_color)
1213                            .map(|label| {
1214                                if is_generating || is_waiting_to_update_token_count {
1215                                    label
1216                                        .with_animation(
1217                                            "used-tokens-label",
1218                                            Animation::new(Duration::from_secs(2))
1219                                                .repeat()
1220                                                .with_easing(pulsating_between(0.6, 1.)),
1221                                            |label, delta| label.alpha(delta),
1222                                        )
1223                                        .into_any()
1224                                } else {
1225                                    label.into_any_element()
1226                                }
1227                            }),
1228                    )
1229                    .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1230                    .child(
1231                        Label::new(humanize_token_count(total_token_usage.max))
1232                            .size(LabelSize::Small)
1233                            .color(Color::Muted),
1234                    )
1235                    .into_any();
1236
1237                Some(token_count)
1238            }
1239            ActiveView::PromptEditor { context_editor } => {
1240                let element = render_remaining_tokens(context_editor, cx)?;
1241
1242                Some(element.into_any_element())
1243            }
1244            _ => None,
1245        }
1246    }
1247
1248    fn render_active_thread_or_empty_state(
1249        &self,
1250        window: &mut Window,
1251        cx: &mut Context<Self>,
1252    ) -> AnyElement {
1253        if self.thread.read(cx).is_empty() {
1254            return self
1255                .render_thread_empty_state(window, cx)
1256                .into_any_element();
1257        }
1258
1259        self.thread.clone().into_any_element()
1260    }
1261
1262    fn configuration_error(&self, cx: &App) -> Option<ConfigurationError> {
1263        let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1264            return Some(ConfigurationError::NoProvider);
1265        };
1266
1267        if !model.provider.is_authenticated(cx) {
1268            return Some(ConfigurationError::ProviderNotAuthenticated);
1269        }
1270
1271        if model.provider.must_accept_terms(cx) {
1272            return Some(ConfigurationError::ProviderPendingTermsAcceptance(
1273                model.provider,
1274            ));
1275        }
1276
1277        None
1278    }
1279
1280    fn render_thread_empty_state(
1281        &self,
1282        window: &mut Window,
1283        cx: &mut Context<Self>,
1284    ) -> impl IntoElement {
1285        let recent_history = self
1286            .history_store
1287            .update(cx, |this, cx| this.recent_entries(6, cx));
1288
1289        let configuration_error = self.configuration_error(cx);
1290        let no_error = configuration_error.is_none();
1291        let focus_handle = self.focus_handle(cx);
1292
1293        v_flex()
1294            .size_full()
1295            .when(recent_history.is_empty(), |this| {
1296                let configuration_error_ref = &configuration_error;
1297                this.child(
1298                    v_flex()
1299                        .size_full()
1300                        .max_w_80()
1301                        .mx_auto()
1302                        .justify_center()
1303                        .items_center()
1304                        .gap_1()
1305                        .child(
1306                            h_flex().child(
1307                                Headline::new("Welcome to the Agent Panel")
1308                            ),
1309                        )
1310                        .when(no_error, |parent| {
1311                            parent
1312                                .child(
1313                                    h_flex().child(
1314                                        Label::new("Ask and build anything.")
1315                                            .color(Color::Muted)
1316                                            .mb_2p5(),
1317                                    ),
1318                                )
1319                                .child(
1320                                    Button::new("new-thread", "Start New Thread")
1321                                        .icon(IconName::Plus)
1322                                        .icon_position(IconPosition::Start)
1323                                        .icon_size(IconSize::Small)
1324                                        .icon_color(Color::Muted)
1325                                        .full_width()
1326                                        .key_binding(KeyBinding::for_action_in(
1327                                            &NewThread::default(),
1328                                            &focus_handle,
1329                                            window,
1330                                            cx,
1331                                        ))
1332                                        .on_click(|_event, window, cx| {
1333                                            window.dispatch_action(NewThread::default().boxed_clone(), cx)
1334                                        }),
1335                                )
1336                                .child(
1337                                    Button::new("context", "Add Context")
1338                                        .icon(IconName::FileCode)
1339                                        .icon_position(IconPosition::Start)
1340                                        .icon_size(IconSize::Small)
1341                                        .icon_color(Color::Muted)
1342                                        .full_width()
1343                                        .key_binding(KeyBinding::for_action_in(
1344                                            &ToggleContextPicker,
1345                                            &focus_handle,
1346                                            window,
1347                                            cx,
1348                                        ))
1349                                        .on_click(|_event, window, cx| {
1350                                            window.dispatch_action(ToggleContextPicker.boxed_clone(), cx)
1351                                        }),
1352                                )
1353                                .child(
1354                                    Button::new("mode", "Switch Model")
1355                                        .icon(IconName::DatabaseZap)
1356                                        .icon_position(IconPosition::Start)
1357                                        .icon_size(IconSize::Small)
1358                                        .icon_color(Color::Muted)
1359                                        .full_width()
1360                                        .key_binding(KeyBinding::for_action_in(
1361                                            &ToggleModelSelector,
1362                                            &focus_handle,
1363                                            window,
1364                                            cx,
1365                                        ))
1366                                        .on_click(|_event, window, cx| {
1367                                            window.dispatch_action(ToggleModelSelector.boxed_clone(), cx)
1368                                        }),
1369                                )
1370                                .child(
1371                                    Button::new("settings", "View Settings")
1372                                        .icon(IconName::Settings)
1373                                        .icon_position(IconPosition::Start)
1374                                        .icon_size(IconSize::Small)
1375                                        .icon_color(Color::Muted)
1376                                        .full_width()
1377                                        .key_binding(KeyBinding::for_action_in(
1378                                            &OpenConfiguration,
1379                                            &focus_handle,
1380                                            window,
1381                                            cx,
1382                                        ))
1383                                        .on_click(|_event, window, cx| {
1384                                            window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
1385                                        }),
1386                                )
1387                        })
1388                        .map(|parent| {
1389                            match configuration_error_ref {
1390                                Some(ConfigurationError::ProviderNotAuthenticated)
1391                                | Some(ConfigurationError::NoProvider) => {
1392                                    parent
1393                                        .child(
1394                                            h_flex().child(
1395                                                Label::new("To start using the agent, configure at least one LLM provider.")
1396                                                    .color(Color::Muted)
1397                                                    .mb_2p5()
1398                                            )
1399                                        )
1400                                        .child(
1401                                            Button::new("settings", "Configure a Provider")
1402                                                .icon(IconName::Settings)
1403                                                .icon_position(IconPosition::Start)
1404                                                .icon_size(IconSize::Small)
1405                                                .icon_color(Color::Muted)
1406                                                .full_width()
1407                                                .key_binding(KeyBinding::for_action_in(
1408                                                    &OpenConfiguration,
1409                                                    &focus_handle,
1410                                                    window,
1411                                                    cx,
1412                                                ))
1413                                                .on_click(|_event, window, cx| {
1414                                                    window.dispatch_action(OpenConfiguration.boxed_clone(), cx)
1415                                                }),
1416                                        )
1417                                }
1418                                Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
1419                                    parent.children(
1420                                        provider.render_accept_terms(
1421                                            LanguageModelProviderTosView::ThreadFreshStart,
1422                                            cx,
1423                                        ),
1424                                    )
1425                                }
1426                                None => parent,
1427                            }
1428                        })
1429                )
1430            })
1431            .when(!recent_history.is_empty(), |parent| {
1432                let focus_handle = focus_handle.clone();
1433                let configuration_error_ref = &configuration_error;
1434
1435                parent
1436                    .overflow_hidden()
1437                    .p_1p5()
1438                    .justify_end()
1439                    .gap_1()
1440                    .child(
1441                        h_flex()
1442                            .pl_1p5()
1443                            .pb_1()
1444                            .w_full()
1445                            .justify_between()
1446                            .border_b_1()
1447                            .border_color(cx.theme().colors().border_variant)
1448                            .child(
1449                                Label::new("Past Interactions")
1450                                    .size(LabelSize::Small)
1451                                    .color(Color::Muted),
1452                            )
1453                            .child(
1454                                Button::new("view-history", "View All")
1455                                    .style(ButtonStyle::Subtle)
1456                                    .label_size(LabelSize::Small)
1457                                    .key_binding(
1458                                        KeyBinding::for_action_in(
1459                                            &OpenHistory,
1460                                            &self.focus_handle(cx),
1461                                            window,
1462                                            cx,
1463                                        ).map(|kb| kb.size(rems_from_px(12.))),
1464                                    )
1465                                    .on_click(move |_event, window, cx| {
1466                                        window.dispatch_action(OpenHistory.boxed_clone(), cx);
1467                                    }),
1468                            ),
1469                    )
1470                    .child(
1471                        v_flex()
1472                            .gap_1()
1473                            .children(
1474                                recent_history.into_iter().map(|entry| {
1475                                    // TODO: Add keyboard navigation.
1476                                    match entry {
1477                                        HistoryEntry::Thread(thread) => {
1478                                            PastThread::new(thread, cx.entity().downgrade(), false, vec![])
1479                                                .into_any_element()
1480                                        }
1481                                        HistoryEntry::Context(context) => {
1482                                            PastContext::new(context, cx.entity().downgrade(), false, vec![])
1483                                                .into_any_element()
1484                                        }
1485                                    }
1486                                }),
1487                            )
1488                    )
1489                    .map(|parent| {
1490                        match configuration_error_ref {
1491                            Some(ConfigurationError::ProviderNotAuthenticated)
1492                            | Some(ConfigurationError::NoProvider) => {
1493                                parent
1494                                    .child(
1495                                        Banner::new()
1496                                            .severity(ui::Severity::Warning)
1497                                            .children(
1498                                                Label::new(
1499                                                    "Configure at least one LLM provider to start using the panel.",
1500                                                )
1501                                                .size(LabelSize::Small),
1502                                            )
1503                                            .action_slot(
1504                                                Button::new("settings", "Configure Provider")
1505                                                    .style(ButtonStyle::Tinted(ui::TintColor::Warning))
1506                                                    .label_size(LabelSize::Small)
1507                                                    .key_binding(
1508                                                        KeyBinding::for_action_in(
1509                                                            &OpenConfiguration,
1510                                                            &focus_handle,
1511                                                            window,
1512                                                            cx,
1513                                                        )
1514                                                        .map(|kb| kb.size(rems_from_px(12.))),
1515                                                    )
1516                                                    .on_click(|_event, window, cx| {
1517                                                        window.dispatch_action(
1518                                                            OpenConfiguration.boxed_clone(),
1519                                                            cx,
1520                                                        )
1521                                                    }),
1522                                            ),
1523                                    )
1524                            }
1525                            Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
1526                                parent
1527                                    .child(
1528                                        Banner::new()
1529                                            .severity(ui::Severity::Warning)
1530                                            .children(
1531                                                h_flex()
1532                                                    .w_full()
1533                                                    .children(
1534                                                        provider.render_accept_terms(
1535                                                            LanguageModelProviderTosView::ThreadtEmptyState,
1536                                                            cx,
1537                                                        ),
1538                                                    ),
1539                                            ),
1540                                    )
1541                            }
1542                            None => parent,
1543                        }
1544                    })
1545            })
1546    }
1547
1548    fn render_usage_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1549        let usage = self.thread.read(cx).last_usage()?;
1550
1551        Some(UsageBanner::new(zed_llm_client::Plan::ZedProTrial, usage.amount).into_any_element())
1552    }
1553
1554    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1555        let last_error = self.thread.read(cx).last_error()?;
1556
1557        Some(
1558            div()
1559                .absolute()
1560                .right_3()
1561                .bottom_12()
1562                .max_w_96()
1563                .py_2()
1564                .px_3()
1565                .elevation_2(cx)
1566                .occlude()
1567                .child(match last_error {
1568                    ThreadError::PaymentRequired => self.render_payment_required_error(cx),
1569                    ThreadError::MaxMonthlySpendReached => {
1570                        self.render_max_monthly_spend_reached_error(cx)
1571                    }
1572                    ThreadError::ModelRequestLimitReached { plan } => {
1573                        self.render_model_request_limit_reached_error(plan, cx)
1574                    }
1575                    ThreadError::Message { header, message } => {
1576                        self.render_error_message(header, message, cx)
1577                    }
1578                })
1579                .into_any(),
1580        )
1581    }
1582
1583    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
1584        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.";
1585
1586        v_flex()
1587            .gap_0p5()
1588            .child(
1589                h_flex()
1590                    .gap_1p5()
1591                    .items_center()
1592                    .child(Icon::new(IconName::XCircle).color(Color::Error))
1593                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
1594            )
1595            .child(
1596                div()
1597                    .id("error-message")
1598                    .max_h_24()
1599                    .overflow_y_scroll()
1600                    .child(Label::new(ERROR_MESSAGE)),
1601            )
1602            .child(
1603                h_flex()
1604                    .justify_end()
1605                    .mt_1()
1606                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
1607                        |this, _, _, cx| {
1608                            this.thread.update(cx, |this, _cx| {
1609                                this.clear_last_error();
1610                            });
1611
1612                            cx.open_url(&zed_urls::account_url(cx));
1613                            cx.notify();
1614                        },
1615                    )))
1616                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1617                        |this, _, _, cx| {
1618                            this.thread.update(cx, |this, _cx| {
1619                                this.clear_last_error();
1620                            });
1621
1622                            cx.notify();
1623                        },
1624                    ))),
1625            )
1626            .into_any()
1627    }
1628
1629    fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
1630        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
1631
1632        v_flex()
1633            .gap_0p5()
1634            .child(
1635                h_flex()
1636                    .gap_1p5()
1637                    .items_center()
1638                    .child(Icon::new(IconName::XCircle).color(Color::Error))
1639                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
1640            )
1641            .child(
1642                div()
1643                    .id("error-message")
1644                    .max_h_24()
1645                    .overflow_y_scroll()
1646                    .child(Label::new(ERROR_MESSAGE)),
1647            )
1648            .child(
1649                h_flex()
1650                    .justify_end()
1651                    .mt_1()
1652                    .child(
1653                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
1654                            cx.listener(|this, _, _, cx| {
1655                                this.thread.update(cx, |this, _cx| {
1656                                    this.clear_last_error();
1657                                });
1658
1659                                cx.open_url(&zed_urls::account_url(cx));
1660                                cx.notify();
1661                            }),
1662                        ),
1663                    )
1664                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1665                        |this, _, _, cx| {
1666                            this.thread.update(cx, |this, _cx| {
1667                                this.clear_last_error();
1668                            });
1669
1670                            cx.notify();
1671                        },
1672                    ))),
1673            )
1674            .into_any()
1675    }
1676
1677    fn render_model_request_limit_reached_error(
1678        &self,
1679        plan: Plan,
1680        cx: &mut Context<Self>,
1681    ) -> AnyElement {
1682        let error_message = match plan {
1683            Plan::ZedPro => {
1684                "Model request limit reached. Upgrade to usage-based billing for more requests."
1685            }
1686            Plan::ZedProTrial => {
1687                "Model request limit reached. Upgrade to Zed Pro for more requests."
1688            }
1689            Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
1690        };
1691        let call_to_action = match plan {
1692            Plan::ZedPro => "Upgrade to usage-based billing",
1693            Plan::ZedProTrial => "Upgrade to Zed Pro",
1694            Plan::Free => "Upgrade to Zed Pro",
1695        };
1696
1697        v_flex()
1698            .gap_0p5()
1699            .child(
1700                h_flex()
1701                    .gap_1p5()
1702                    .items_center()
1703                    .child(Icon::new(IconName::XCircle).color(Color::Error))
1704                    .child(Label::new("Model Request Limit Reached").weight(FontWeight::MEDIUM)),
1705            )
1706            .child(
1707                div()
1708                    .id("error-message")
1709                    .max_h_24()
1710                    .overflow_y_scroll()
1711                    .child(Label::new(error_message)),
1712            )
1713            .child(
1714                h_flex()
1715                    .justify_end()
1716                    .mt_1()
1717                    .child(
1718                        Button::new("subscribe", call_to_action).on_click(cx.listener(
1719                            |this, _, _, cx| {
1720                                this.thread.update(cx, |this, _cx| {
1721                                    this.clear_last_error();
1722                                });
1723
1724                                cx.open_url(&zed_urls::account_url(cx));
1725                                cx.notify();
1726                            },
1727                        )),
1728                    )
1729                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1730                        |this, _, _, cx| {
1731                            this.thread.update(cx, |this, _cx| {
1732                                this.clear_last_error();
1733                            });
1734
1735                            cx.notify();
1736                        },
1737                    ))),
1738            )
1739            .into_any()
1740    }
1741
1742    fn render_error_message(
1743        &self,
1744        header: SharedString,
1745        message: SharedString,
1746        cx: &mut Context<Self>,
1747    ) -> AnyElement {
1748        v_flex()
1749            .gap_0p5()
1750            .child(
1751                h_flex()
1752                    .gap_1p5()
1753                    .items_center()
1754                    .child(Icon::new(IconName::XCircle).color(Color::Error))
1755                    .child(Label::new(header).weight(FontWeight::MEDIUM)),
1756            )
1757            .child(
1758                div()
1759                    .id("error-message")
1760                    .max_h_32()
1761                    .overflow_y_scroll()
1762                    .child(Label::new(message)),
1763            )
1764            .child(
1765                h_flex()
1766                    .justify_end()
1767                    .mt_1()
1768                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
1769                        |this, _, _, cx| {
1770                            this.thread.update(cx, |this, _cx| {
1771                                this.clear_last_error();
1772                            });
1773
1774                            cx.notify();
1775                        },
1776                    ))),
1777            )
1778            .into_any()
1779    }
1780
1781    fn key_context(&self) -> KeyContext {
1782        let mut key_context = KeyContext::new_with_defaults();
1783        key_context.add("AgentPanel");
1784        if matches!(self.active_view, ActiveView::PromptEditor { .. }) {
1785            key_context.add("prompt_editor");
1786        }
1787        key_context
1788    }
1789}
1790
1791impl Render for AssistantPanel {
1792    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1793        v_flex()
1794            .key_context(self.key_context())
1795            .justify_between()
1796            .size_full()
1797            .on_action(cx.listener(Self::cancel))
1798            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
1799                this.new_thread(action, window, cx);
1800            }))
1801            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
1802                this.open_history(window, cx);
1803            }))
1804            .on_action(cx.listener(|this, _: &OpenConfiguration, window, cx| {
1805                this.open_configuration(window, cx);
1806            }))
1807            .on_action(cx.listener(Self::open_active_thread_as_markdown))
1808            .on_action(cx.listener(Self::deploy_prompt_library))
1809            .on_action(cx.listener(Self::open_agent_diff))
1810            .on_action(cx.listener(Self::go_back))
1811            .child(self.render_toolbar(window, cx))
1812            .map(|parent| match &self.active_view {
1813                ActiveView::Thread { .. } => parent
1814                    .child(self.render_active_thread_or_empty_state(window, cx))
1815                    .children(self.render_usage_banner(cx))
1816                    .child(h_flex().child(self.message_editor.clone()))
1817                    .children(self.render_last_error(cx)),
1818                ActiveView::History => parent.child(self.history.clone()),
1819                ActiveView::PromptEditor { context_editor } => parent.child(context_editor.clone()),
1820                ActiveView::Configuration => parent.children(self.configuration.clone()),
1821            })
1822    }
1823}
1824
1825struct PromptLibraryInlineAssist {
1826    workspace: WeakEntity<Workspace>,
1827}
1828
1829impl PromptLibraryInlineAssist {
1830    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
1831        Self { workspace }
1832    }
1833}
1834
1835impl prompt_library::InlineAssistDelegate for PromptLibraryInlineAssist {
1836    fn assist(
1837        &self,
1838        prompt_editor: &Entity<Editor>,
1839        _initial_prompt: Option<String>,
1840        window: &mut Window,
1841        cx: &mut Context<PromptLibrary>,
1842    ) {
1843        InlineAssistant::update_global(cx, |assistant, cx| {
1844            let Some(project) = self
1845                .workspace
1846                .upgrade()
1847                .map(|workspace| workspace.read(cx).project().downgrade())
1848            else {
1849                return;
1850            };
1851            assistant.assist(
1852                &prompt_editor,
1853                self.workspace.clone(),
1854                project,
1855                None,
1856                window,
1857                cx,
1858            )
1859        })
1860    }
1861
1862    fn focus_assistant_panel(
1863        &self,
1864        workspace: &mut Workspace,
1865        window: &mut Window,
1866        cx: &mut Context<Workspace>,
1867    ) -> bool {
1868        workspace
1869            .focus_panel::<AssistantPanel>(window, cx)
1870            .is_some()
1871    }
1872}
1873
1874pub struct ConcreteAssistantPanelDelegate;
1875
1876impl AssistantPanelDelegate for ConcreteAssistantPanelDelegate {
1877    fn active_context_editor(
1878        &self,
1879        workspace: &mut Workspace,
1880        _window: &mut Window,
1881        cx: &mut Context<Workspace>,
1882    ) -> Option<Entity<ContextEditor>> {
1883        let panel = workspace.panel::<AssistantPanel>(cx)?;
1884        panel.read(cx).active_context_editor()
1885    }
1886
1887    fn open_saved_context(
1888        &self,
1889        workspace: &mut Workspace,
1890        path: std::path::PathBuf,
1891        window: &mut Window,
1892        cx: &mut Context<Workspace>,
1893    ) -> Task<Result<()>> {
1894        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1895            return Task::ready(Err(anyhow!("Agent panel not found")));
1896        };
1897
1898        panel.update(cx, |panel, cx| {
1899            panel.open_saved_prompt_editor(path, window, cx)
1900        })
1901    }
1902
1903    fn open_remote_context(
1904        &self,
1905        _workspace: &mut Workspace,
1906        _context_id: assistant_context_editor::ContextId,
1907        _window: &mut Window,
1908        _cx: &mut Context<Workspace>,
1909    ) -> Task<Result<Entity<ContextEditor>>> {
1910        Task::ready(Err(anyhow!("opening remote context not implemented")))
1911    }
1912
1913    fn quote_selection(
1914        &self,
1915        workspace: &mut Workspace,
1916        selection_ranges: Vec<Range<Anchor>>,
1917        buffer: Entity<MultiBuffer>,
1918        window: &mut Window,
1919        cx: &mut Context<Workspace>,
1920    ) {
1921        let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1922            return;
1923        };
1924
1925        if !panel.focus_handle(cx).contains_focused(window, cx) {
1926            workspace.toggle_panel_focus::<AssistantPanel>(window, cx);
1927        }
1928
1929        panel.update(cx, |_, cx| {
1930            // Wait to create a new context until the workspace is no longer
1931            // being updated.
1932            cx.defer_in(window, move |panel, window, cx| {
1933                if panel.has_active_thread() {
1934                    panel.thread.update(cx, |thread, cx| {
1935                        thread.context_store().update(cx, |store, cx| {
1936                            let buffer = buffer.read(cx);
1937                            let selection_ranges = selection_ranges
1938                                .into_iter()
1939                                .flat_map(|range| {
1940                                    let (start_buffer, start) =
1941                                        buffer.text_anchor_for_position(range.start, cx)?;
1942                                    let (end_buffer, end) =
1943                                        buffer.text_anchor_for_position(range.end, cx)?;
1944                                    if start_buffer != end_buffer {
1945                                        return None;
1946                                    }
1947                                    Some((start_buffer, start..end))
1948                                })
1949                                .collect::<Vec<_>>();
1950
1951                            for (buffer, range) in selection_ranges {
1952                                store.add_excerpt(range, buffer, cx).detach_and_log_err(cx);
1953                            }
1954                        })
1955                    })
1956                } else if let Some(context_editor) = panel.active_context_editor() {
1957                    let snapshot = buffer.read(cx).snapshot(cx);
1958                    let selection_ranges = selection_ranges
1959                        .into_iter()
1960                        .map(|range| range.to_point(&snapshot))
1961                        .collect::<Vec<_>>();
1962
1963                    context_editor.update(cx, |context_editor, cx| {
1964                        context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
1965                    });
1966                }
1967            });
1968        });
1969    }
1970}