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