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