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