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