agent_panel.rs

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