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