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