1use std::ops::Range;
2use std::path::Path;
3use std::rc::Rc;
4use std::sync::Arc;
5use std::time::Duration;
6
7use agent2::{AcpAgent, Agent as _};
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, FontWeight,
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, 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_element: Entity<agent2::ThreadElement>,
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_element, .. } => {
757 thread_element.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 = AcpAgent::stdio(child, project, cx);
920 let thread = agent.create_thread(cx).await?;
921 let thread_element =
922 cx.new_window_entity(|window, cx| agent2::ThreadElement::new(thread, window, cx))?;
923 this.update_in(cx, |this, window, cx| {
924 this.set_active_view(ActiveView::AcpThread { thread_element }, 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_element, .. } => thread_element.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_element } => {
1682 Label::new(thread_element.read(cx).title(cx))
1683 .truncate()
1684 .into_any_element()
1685 }
1686 ActiveView::TextThread {
1687 title_editor,
1688 context_editor,
1689 ..
1690 } => {
1691 let summary = context_editor.read(cx).context().read(cx).summary();
1692
1693 match summary {
1694 ContextSummary::Pending => Label::new(ContextSummary::DEFAULT)
1695 .truncate()
1696 .into_any_element(),
1697 ContextSummary::Content(summary) => {
1698 if summary.done {
1699 div()
1700 .w_full()
1701 .child(title_editor.clone())
1702 .into_any_element()
1703 } else {
1704 Label::new(LOADING_SUMMARY_PLACEHOLDER)
1705 .truncate()
1706 .into_any_element()
1707 }
1708 }
1709 ContextSummary::Error => h_flex()
1710 .w_full()
1711 .child(title_editor.clone())
1712 .child(
1713 ui::IconButton::new("retry-summary-generation", IconName::RotateCcw)
1714 .on_click({
1715 let context_editor = context_editor.clone();
1716 move |_, _window, cx| {
1717 context_editor.update(cx, |context_editor, cx| {
1718 context_editor.regenerate_summary(cx);
1719 });
1720 }
1721 })
1722 .tooltip(move |_window, cx| {
1723 cx.new(|_| {
1724 Tooltip::new("Failed to generate title")
1725 .meta("Click to try again")
1726 })
1727 .into()
1728 }),
1729 )
1730 .into_any_element(),
1731 }
1732 }
1733 ActiveView::History => Label::new("History").truncate().into_any_element(),
1734 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
1735 };
1736
1737 h_flex()
1738 .key_context("TitleEditor")
1739 .id("TitleEditor")
1740 .flex_grow()
1741 .w_full()
1742 .max_w_full()
1743 .overflow_x_scroll()
1744 .child(content)
1745 .into_any()
1746 }
1747
1748 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1749 let user_store = self.user_store.read(cx);
1750 let usage = user_store.model_request_usage();
1751
1752 let account_url = zed_urls::account_url(cx);
1753
1754 let focus_handle = self.focus_handle(cx);
1755
1756 let go_back_button = div().child(
1757 IconButton::new("go-back", IconName::ArrowLeft)
1758 .icon_size(IconSize::Small)
1759 .on_click(cx.listener(|this, _, window, cx| {
1760 this.go_back(&workspace::GoBack, window, cx);
1761 }))
1762 .tooltip({
1763 let focus_handle = focus_handle.clone();
1764 move |window, cx| {
1765 Tooltip::for_action_in(
1766 "Go Back",
1767 &workspace::GoBack,
1768 &focus_handle,
1769 window,
1770 cx,
1771 )
1772 }
1773 }),
1774 );
1775
1776 let recent_entries_menu = div().child(
1777 PopoverMenu::new("agent-nav-menu")
1778 .trigger_with_tooltip(
1779 IconButton::new("agent-nav-menu", IconName::MenuAlt)
1780 .icon_size(IconSize::Small)
1781 .style(ui::ButtonStyle::Subtle),
1782 {
1783 let focus_handle = focus_handle.clone();
1784 move |window, cx| {
1785 Tooltip::for_action_in(
1786 "Toggle Panel Menu",
1787 &ToggleNavigationMenu,
1788 &focus_handle,
1789 window,
1790 cx,
1791 )
1792 }
1793 },
1794 )
1795 .anchor(Corner::TopLeft)
1796 .with_handle(self.assistant_navigation_menu_handle.clone())
1797 .menu({
1798 let menu = self.assistant_navigation_menu.clone();
1799 move |window, cx| {
1800 if let Some(menu) = menu.as_ref() {
1801 menu.update(cx, |_, cx| {
1802 cx.defer_in(window, |menu, window, cx| {
1803 menu.rebuild(window, cx);
1804 });
1805 })
1806 }
1807 menu.clone()
1808 }
1809 }),
1810 );
1811
1812 let zoom_in_label = if self.is_zoomed(window, cx) {
1813 "Zoom Out"
1814 } else {
1815 "Zoom In"
1816 };
1817
1818 let active_thread = match &self.active_view {
1819 ActiveView::Thread { thread, .. } => Some(thread.read(cx).thread().clone()),
1820 ActiveView::AcpThread { .. } => {
1821 // todo!
1822 None
1823 }
1824 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => None,
1825 };
1826
1827 let agent_extra_menu = PopoverMenu::new("agent-options-menu")
1828 .trigger_with_tooltip(
1829 IconButton::new("agent-options-menu", IconName::Ellipsis)
1830 .icon_size(IconSize::Small),
1831 {
1832 let focus_handle = focus_handle.clone();
1833 move |window, cx| {
1834 Tooltip::for_action_in(
1835 "Toggle Agent Menu",
1836 &ToggleOptionsMenu,
1837 &focus_handle,
1838 window,
1839 cx,
1840 )
1841 }
1842 },
1843 )
1844 .anchor(Corner::TopRight)
1845 .with_handle(self.assistant_dropdown_menu_handle.clone())
1846 .menu(move |window, cx| {
1847 let active_thread = active_thread.clone();
1848 Some(ContextMenu::build(window, cx, |mut menu, _window, cx| {
1849 menu = menu
1850 .action("New Thread", NewThread::default().boxed_clone())
1851 .action("New Text Thread", NewTextThread.boxed_clone())
1852 .action("New Gemini Thread", NewGeminiThread.boxed_clone())
1853 .when_some(active_thread, |this, active_thread| {
1854 let thread = active_thread.read(cx);
1855 if !thread.is_empty() {
1856 this.action(
1857 "New From Summary",
1858 Box::new(NewThread {
1859 from_thread_id: Some(thread.id().clone()),
1860 }),
1861 )
1862 } else {
1863 this
1864 }
1865 })
1866 .separator();
1867
1868 menu = menu
1869 .header("MCP Servers")
1870 .action(
1871 "View Server Extensions",
1872 Box::new(zed_actions::Extensions {
1873 category_filter: Some(
1874 zed_actions::ExtensionCategoryFilter::ContextServers,
1875 ),
1876 }),
1877 )
1878 .action("Add Custom Server…", Box::new(AddContextServer))
1879 .separator();
1880
1881 if let Some(usage) = usage {
1882 menu = menu
1883 .header_with_link("Prompt Usage", "Manage", account_url.clone())
1884 .custom_entry(
1885 move |_window, cx| {
1886 let used_percentage = match usage.limit {
1887 UsageLimit::Limited(limit) => {
1888 Some((usage.amount as f32 / limit as f32) * 100.)
1889 }
1890 UsageLimit::Unlimited => None,
1891 };
1892
1893 h_flex()
1894 .flex_1()
1895 .gap_1p5()
1896 .children(used_percentage.map(|percent| {
1897 ProgressBar::new("usage", percent, 100., cx)
1898 }))
1899 .child(
1900 Label::new(match usage.limit {
1901 UsageLimit::Limited(limit) => {
1902 format!("{} / {limit}", usage.amount)
1903 }
1904 UsageLimit::Unlimited => {
1905 format!("{} / ∞", usage.amount)
1906 }
1907 })
1908 .size(LabelSize::Small)
1909 .color(Color::Muted),
1910 )
1911 .into_any_element()
1912 },
1913 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
1914 )
1915 .separator()
1916 }
1917
1918 menu = menu
1919 .action("Rules…", Box::new(OpenRulesLibrary::default()))
1920 .action("Settings", Box::new(OpenConfiguration))
1921 .action(zoom_in_label, Box::new(ToggleZoom));
1922 menu
1923 }))
1924 });
1925
1926 h_flex()
1927 .id("assistant-toolbar")
1928 .h(Tab::container_height(cx))
1929 .max_w_full()
1930 .flex_none()
1931 .justify_between()
1932 .gap_2()
1933 .bg(cx.theme().colors().tab_bar_background)
1934 .border_b_1()
1935 .border_color(cx.theme().colors().border)
1936 .child(
1937 h_flex()
1938 .size_full()
1939 .pl_1()
1940 .gap_1()
1941 .child(match &self.active_view {
1942 ActiveView::History | ActiveView::Configuration => go_back_button,
1943 _ => recent_entries_menu,
1944 })
1945 .child(self.render_title_view(window, cx)),
1946 )
1947 .child(
1948 h_flex()
1949 .h_full()
1950 .gap_2()
1951 .children(self.render_token_count(cx))
1952 .child(
1953 h_flex()
1954 .h_full()
1955 .gap(DynamicSpacing::Base02.rems(cx))
1956 .px(DynamicSpacing::Base08.rems(cx))
1957 .border_l_1()
1958 .border_color(cx.theme().colors().border)
1959 .child(
1960 IconButton::new("new", IconName::Plus)
1961 .icon_size(IconSize::Small)
1962 .style(ButtonStyle::Subtle)
1963 .tooltip(move |window, cx| {
1964 Tooltip::for_action_in(
1965 "New Thread",
1966 &NewThread::default(),
1967 &focus_handle,
1968 window,
1969 cx,
1970 )
1971 })
1972 .on_click(move |_event, window, cx| {
1973 window.dispatch_action(
1974 NewThread::default().boxed_clone(),
1975 cx,
1976 );
1977 }),
1978 )
1979 .child(agent_extra_menu),
1980 ),
1981 )
1982 }
1983
1984 fn render_token_count(&self, cx: &App) -> Option<AnyElement> {
1985 let (active_thread, message_editor) = match &self.active_view {
1986 ActiveView::Thread {
1987 thread,
1988 message_editor,
1989 ..
1990 } => (thread.read(cx), message_editor.read(cx)),
1991 ActiveView::AcpThread { .. } => {
1992 // todo!
1993 return None;
1994 }
1995 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {
1996 return None;
1997 }
1998 };
1999
2000 let editor_empty = message_editor.is_editor_fully_empty(cx);
2001
2002 if active_thread.is_empty() && editor_empty {
2003 return None;
2004 }
2005
2006 let thread = active_thread.thread().read(cx);
2007 let is_generating = thread.is_generating();
2008 let conversation_token_usage = thread.total_token_usage()?;
2009
2010 let (total_token_usage, is_estimating) =
2011 if let Some((editing_message_id, unsent_tokens)) = active_thread.editing_message_id() {
2012 let combined = thread
2013 .token_usage_up_to_message(editing_message_id)
2014 .add(unsent_tokens);
2015
2016 (combined, unsent_tokens > 0)
2017 } else {
2018 let unsent_tokens = message_editor.last_estimated_token_count().unwrap_or(0);
2019 let combined = conversation_token_usage.add(unsent_tokens);
2020
2021 (combined, unsent_tokens > 0)
2022 };
2023
2024 let is_waiting_to_update_token_count = message_editor.is_waiting_to_update_token_count();
2025
2026 match &self.active_view {
2027 ActiveView::Thread { .. } => {
2028 if total_token_usage.total == 0 {
2029 return None;
2030 }
2031
2032 let token_color = match total_token_usage.ratio() {
2033 TokenUsageRatio::Normal if is_estimating => Color::Default,
2034 TokenUsageRatio::Normal => Color::Muted,
2035 TokenUsageRatio::Warning => Color::Warning,
2036 TokenUsageRatio::Exceeded => Color::Error,
2037 };
2038
2039 let token_count = h_flex()
2040 .id("token-count")
2041 .flex_shrink_0()
2042 .gap_0p5()
2043 .when(!is_generating && is_estimating, |parent| {
2044 parent
2045 .child(
2046 h_flex()
2047 .mr_1()
2048 .size_2p5()
2049 .justify_center()
2050 .rounded_full()
2051 .bg(cx.theme().colors().text.opacity(0.1))
2052 .child(
2053 div().size_1().rounded_full().bg(cx.theme().colors().text),
2054 ),
2055 )
2056 .tooltip(move |window, cx| {
2057 Tooltip::with_meta(
2058 "Estimated New Token Count",
2059 None,
2060 format!(
2061 "Current Conversation Tokens: {}",
2062 humanize_token_count(conversation_token_usage.total)
2063 ),
2064 window,
2065 cx,
2066 )
2067 })
2068 })
2069 .child(
2070 Label::new(humanize_token_count(total_token_usage.total))
2071 .size(LabelSize::Small)
2072 .color(token_color)
2073 .map(|label| {
2074 if is_generating || is_waiting_to_update_token_count {
2075 label
2076 .with_animation(
2077 "used-tokens-label",
2078 Animation::new(Duration::from_secs(2))
2079 .repeat()
2080 .with_easing(pulsating_between(0.6, 1.)),
2081 |label, delta| label.alpha(delta),
2082 )
2083 .into_any()
2084 } else {
2085 label.into_any_element()
2086 }
2087 }),
2088 )
2089 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2090 .child(
2091 Label::new(humanize_token_count(total_token_usage.max))
2092 .size(LabelSize::Small)
2093 .color(Color::Muted),
2094 )
2095 .into_any();
2096
2097 Some(token_count)
2098 }
2099 ActiveView::TextThread { context_editor, .. } => {
2100 let element = render_remaining_tokens(context_editor, cx)?;
2101
2102 Some(element.into_any_element())
2103 }
2104 _ => None,
2105 }
2106 }
2107
2108 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
2109 if TrialEndUpsell::dismissed() {
2110 return false;
2111 }
2112
2113 let plan = self.user_store.read(cx).current_plan();
2114 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2115
2116 matches!(plan, Some(Plan::Free)) && has_previous_trial
2117 }
2118
2119 fn should_render_upsell(&self, cx: &mut Context<Self>) -> bool {
2120 match &self.active_view {
2121 ActiveView::Thread { thread, .. } => {
2122 let is_using_zed_provider = thread
2123 .read(cx)
2124 .thread()
2125 .read(cx)
2126 .configured_model()
2127 .map_or(false, |model| {
2128 model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
2129 });
2130
2131 if !is_using_zed_provider {
2132 return false;
2133 }
2134 }
2135 ActiveView::AcpThread { .. } => {
2136 // todo!
2137 return false;
2138 }
2139 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {
2140 return false;
2141 }
2142 };
2143
2144 if self.hide_upsell || Upsell::dismissed() {
2145 return false;
2146 }
2147
2148 let plan = self.user_store.read(cx).current_plan();
2149 if matches!(plan, Some(Plan::ZedPro | Plan::ZedProTrial)) {
2150 return false;
2151 }
2152
2153 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
2154 if has_previous_trial {
2155 return false;
2156 }
2157
2158 true
2159 }
2160
2161 fn render_upsell(
2162 &self,
2163 _window: &mut Window,
2164 cx: &mut Context<Self>,
2165 ) -> Option<impl IntoElement> {
2166 if !self.should_render_upsell(cx) {
2167 return None;
2168 }
2169
2170 if self.user_store.read(cx).account_too_young() {
2171 Some(self.render_young_account_upsell(cx).into_any_element())
2172 } else {
2173 Some(self.render_trial_upsell(cx).into_any_element())
2174 }
2175 }
2176
2177 fn render_young_account_upsell(&self, cx: &mut Context<Self>) -> impl IntoElement {
2178 let checkbox = CheckboxWithLabel::new(
2179 "dont-show-again",
2180 Label::new("Don't show again").color(Color::Muted),
2181 ToggleState::Unselected,
2182 move |toggle_state, _window, cx| {
2183 let toggle_state_bool = toggle_state.selected();
2184
2185 Upsell::set_dismissed(toggle_state_bool, cx);
2186 },
2187 );
2188
2189 let contents = div()
2190 .size_full()
2191 .gap_2()
2192 .flex()
2193 .flex_col()
2194 .child(Headline::new("Build better with Zed Pro").size(HeadlineSize::Small))
2195 .child(
2196 Label::new("Your GitHub account was created less than 30 days ago, so we can't offer you a free trial.")
2197 .size(LabelSize::Small),
2198 )
2199 .child(
2200 Label::new(
2201 "Use your own API keys, upgrade to Zed Pro or send an email to billing-support@zed.dev.",
2202 )
2203 .color(Color::Muted),
2204 )
2205 .child(
2206 h_flex()
2207 .w_full()
2208 .px_neg_1()
2209 .justify_between()
2210 .items_center()
2211 .child(h_flex().items_center().gap_1().child(checkbox))
2212 .child(
2213 h_flex()
2214 .gap_2()
2215 .child(
2216 Button::new("dismiss-button", "Not Now")
2217 .style(ButtonStyle::Transparent)
2218 .color(Color::Muted)
2219 .on_click({
2220 let agent_panel = cx.entity();
2221 move |_, _, cx| {
2222 agent_panel.update(cx, |this, cx| {
2223 this.hide_upsell = true;
2224 cx.notify();
2225 });
2226 }
2227 }),
2228 )
2229 .child(
2230 Button::new("cta-button", "Upgrade to Zed Pro")
2231 .style(ButtonStyle::Transparent)
2232 .on_click(|_, _, cx| cx.open_url(&zed_urls::account_url(cx))),
2233 ),
2234 ),
2235 );
2236
2237 self.render_upsell_container(cx, contents)
2238 }
2239
2240 fn render_trial_upsell(&self, cx: &mut Context<Self>) -> impl IntoElement {
2241 let checkbox = CheckboxWithLabel::new(
2242 "dont-show-again",
2243 Label::new("Don't show again").color(Color::Muted),
2244 ToggleState::Unselected,
2245 move |toggle_state, _window, cx| {
2246 let toggle_state_bool = toggle_state.selected();
2247
2248 Upsell::set_dismissed(toggle_state_bool, cx);
2249 },
2250 );
2251
2252 let contents = div()
2253 .size_full()
2254 .gap_2()
2255 .flex()
2256 .flex_col()
2257 .child(Headline::new("Build better with Zed Pro").size(HeadlineSize::Small))
2258 .child(
2259 Label::new("Try Zed Pro for free for 14 days - no credit card required.")
2260 .size(LabelSize::Small),
2261 )
2262 .child(
2263 Label::new(
2264 "Use your own API keys or enable usage-based billing once you hit the cap.",
2265 )
2266 .color(Color::Muted),
2267 )
2268 .child(
2269 h_flex()
2270 .w_full()
2271 .px_neg_1()
2272 .justify_between()
2273 .items_center()
2274 .child(h_flex().items_center().gap_1().child(checkbox))
2275 .child(
2276 h_flex()
2277 .gap_2()
2278 .child(
2279 Button::new("dismiss-button", "Not Now")
2280 .style(ButtonStyle::Transparent)
2281 .color(Color::Muted)
2282 .on_click({
2283 let agent_panel = cx.entity();
2284 move |_, _, cx| {
2285 agent_panel.update(cx, |this, cx| {
2286 this.hide_upsell = true;
2287 cx.notify();
2288 });
2289 }
2290 }),
2291 )
2292 .child(
2293 Button::new("cta-button", "Start Trial")
2294 .style(ButtonStyle::Transparent)
2295 .on_click(|_, _, cx| cx.open_url(&zed_urls::account_url(cx))),
2296 ),
2297 ),
2298 );
2299
2300 self.render_upsell_container(cx, contents)
2301 }
2302
2303 fn render_trial_end_upsell(
2304 &self,
2305 _window: &mut Window,
2306 cx: &mut Context<Self>,
2307 ) -> Option<impl IntoElement> {
2308 if !self.should_render_trial_end_upsell(cx) {
2309 return None;
2310 }
2311
2312 Some(
2313 self.render_upsell_container(
2314 cx,
2315 div()
2316 .size_full()
2317 .gap_2()
2318 .flex()
2319 .flex_col()
2320 .child(
2321 Headline::new("Your Zed Pro trial has expired.").size(HeadlineSize::Small),
2322 )
2323 .child(
2324 Label::new("You've been automatically reset to the free plan.")
2325 .size(LabelSize::Small),
2326 )
2327 .child(
2328 h_flex()
2329 .w_full()
2330 .px_neg_1()
2331 .justify_between()
2332 .items_center()
2333 .child(div())
2334 .child(
2335 h_flex()
2336 .gap_2()
2337 .child(
2338 Button::new("dismiss-button", "Stay on Free")
2339 .style(ButtonStyle::Transparent)
2340 .color(Color::Muted)
2341 .on_click({
2342 let agent_panel = cx.entity();
2343 move |_, _, cx| {
2344 agent_panel.update(cx, |_this, cx| {
2345 TrialEndUpsell::set_dismissed(true, cx);
2346 cx.notify();
2347 });
2348 }
2349 }),
2350 )
2351 .child(
2352 Button::new("cta-button", "Upgrade to Zed Pro")
2353 .style(ButtonStyle::Transparent)
2354 .on_click(|_, _, cx| {
2355 cx.open_url(&zed_urls::account_url(cx))
2356 }),
2357 ),
2358 ),
2359 ),
2360 ),
2361 )
2362 }
2363
2364 fn render_upsell_container(&self, cx: &mut Context<Self>, content: Div) -> Div {
2365 div().p_2().child(
2366 v_flex()
2367 .w_full()
2368 .elevation_2(cx)
2369 .rounded(px(8.))
2370 .bg(cx.theme().colors().background.alpha(0.5))
2371 .p(px(3.))
2372 .child(
2373 div()
2374 .gap_2()
2375 .flex()
2376 .flex_col()
2377 .size_full()
2378 .border_1()
2379 .rounded(px(5.))
2380 .border_color(cx.theme().colors().text.alpha(0.1))
2381 .overflow_hidden()
2382 .relative()
2383 .bg(cx.theme().colors().panel_background)
2384 .px_4()
2385 .py_3()
2386 .child(
2387 div()
2388 .absolute()
2389 .top_0()
2390 .right(px(-1.0))
2391 .w(px(441.))
2392 .h(px(167.))
2393 .child(
2394 Vector::new(
2395 VectorName::Grid,
2396 rems_from_px(441.),
2397 rems_from_px(167.),
2398 )
2399 .color(ui::Color::Custom(cx.theme().colors().text.alpha(0.1))),
2400 ),
2401 )
2402 .child(
2403 div()
2404 .absolute()
2405 .top(px(-8.0))
2406 .right_0()
2407 .w(px(400.))
2408 .h(px(92.))
2409 .child(
2410 Vector::new(
2411 VectorName::AiGrid,
2412 rems_from_px(400.),
2413 rems_from_px(92.),
2414 )
2415 .color(ui::Color::Custom(cx.theme().colors().text.alpha(0.32))),
2416 ),
2417 )
2418 // .child(
2419 // div()
2420 // .absolute()
2421 // .top_0()
2422 // .right(px(360.))
2423 // .size(px(401.))
2424 // .overflow_hidden()
2425 // .bg(cx.theme().colors().panel_background)
2426 // )
2427 .child(
2428 div()
2429 .absolute()
2430 .top_0()
2431 .right_0()
2432 .w(px(660.))
2433 .h(px(401.))
2434 .overflow_hidden()
2435 .bg(linear_gradient(
2436 75.,
2437 linear_color_stop(
2438 cx.theme().colors().panel_background.alpha(0.01),
2439 1.0,
2440 ),
2441 linear_color_stop(cx.theme().colors().panel_background, 0.45),
2442 )),
2443 )
2444 .child(content),
2445 ),
2446 )
2447 }
2448
2449 fn render_thread_empty_state(
2450 &self,
2451 window: &mut Window,
2452 cx: &mut Context<Self>,
2453 ) -> impl IntoElement {
2454 let recent_history = self
2455 .history_store
2456 .update(cx, |this, cx| this.recent_entries(6, cx));
2457
2458 let model_registry = LanguageModelRegistry::read_global(cx);
2459 let configuration_error =
2460 model_registry.configuration_error(model_registry.default_model(), cx);
2461 let no_error = configuration_error.is_none();
2462 let focus_handle = self.focus_handle(cx);
2463
2464 v_flex()
2465 .size_full()
2466 .bg(cx.theme().colors().panel_background)
2467 .when(recent_history.is_empty(), |this| {
2468 let configuration_error_ref = &configuration_error;
2469 this.child(
2470 v_flex()
2471 .size_full()
2472 .max_w_80()
2473 .mx_auto()
2474 .justify_center()
2475 .items_center()
2476 .gap_1()
2477 .child(h_flex().child(Headline::new("Welcome to the Agent Panel")))
2478 .when(no_error, |parent| {
2479 parent
2480 .child(
2481 h_flex().child(
2482 Label::new("Ask and build anything.")
2483 .color(Color::Muted)
2484 .mb_2p5(),
2485 ),
2486 )
2487 .child(
2488 Button::new("new-thread", "Start New Thread")
2489 .icon(IconName::Plus)
2490 .icon_position(IconPosition::Start)
2491 .icon_size(IconSize::Small)
2492 .icon_color(Color::Muted)
2493 .full_width()
2494 .key_binding(KeyBinding::for_action_in(
2495 &NewThread::default(),
2496 &focus_handle,
2497 window,
2498 cx,
2499 ))
2500 .on_click(|_event, window, cx| {
2501 window.dispatch_action(
2502 NewThread::default().boxed_clone(),
2503 cx,
2504 )
2505 }),
2506 )
2507 .child(
2508 Button::new("context", "Add Context")
2509 .icon(IconName::FileCode)
2510 .icon_position(IconPosition::Start)
2511 .icon_size(IconSize::Small)
2512 .icon_color(Color::Muted)
2513 .full_width()
2514 .key_binding(KeyBinding::for_action_in(
2515 &ToggleContextPicker,
2516 &focus_handle,
2517 window,
2518 cx,
2519 ))
2520 .on_click(|_event, window, cx| {
2521 window.dispatch_action(
2522 ToggleContextPicker.boxed_clone(),
2523 cx,
2524 )
2525 }),
2526 )
2527 .child(
2528 Button::new("mode", "Switch Model")
2529 .icon(IconName::DatabaseZap)
2530 .icon_position(IconPosition::Start)
2531 .icon_size(IconSize::Small)
2532 .icon_color(Color::Muted)
2533 .full_width()
2534 .key_binding(KeyBinding::for_action_in(
2535 &ToggleModelSelector,
2536 &focus_handle,
2537 window,
2538 cx,
2539 ))
2540 .on_click(|_event, window, cx| {
2541 window.dispatch_action(
2542 ToggleModelSelector.boxed_clone(),
2543 cx,
2544 )
2545 }),
2546 )
2547 .child(
2548 Button::new("settings", "View Settings")
2549 .icon(IconName::Settings)
2550 .icon_position(IconPosition::Start)
2551 .icon_size(IconSize::Small)
2552 .icon_color(Color::Muted)
2553 .full_width()
2554 .key_binding(KeyBinding::for_action_in(
2555 &OpenConfiguration,
2556 &focus_handle,
2557 window,
2558 cx,
2559 ))
2560 .on_click(|_event, window, cx| {
2561 window.dispatch_action(
2562 OpenConfiguration.boxed_clone(),
2563 cx,
2564 )
2565 }),
2566 )
2567 })
2568 .map(|parent| match configuration_error_ref {
2569 Some(
2570 err @ (ConfigurationError::ModelNotFound
2571 | ConfigurationError::ProviderNotAuthenticated(_)
2572 | ConfigurationError::NoProvider),
2573 ) => parent
2574 .child(h_flex().child(
2575 Label::new(err.to_string()).color(Color::Muted).mb_2p5(),
2576 ))
2577 .child(
2578 Button::new("settings", "Configure a Provider")
2579 .icon(IconName::Settings)
2580 .icon_position(IconPosition::Start)
2581 .icon_size(IconSize::Small)
2582 .icon_color(Color::Muted)
2583 .full_width()
2584 .key_binding(KeyBinding::for_action_in(
2585 &OpenConfiguration,
2586 &focus_handle,
2587 window,
2588 cx,
2589 ))
2590 .on_click(|_event, window, cx| {
2591 window.dispatch_action(
2592 OpenConfiguration.boxed_clone(),
2593 cx,
2594 )
2595 }),
2596 ),
2597 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2598 parent.children(provider.render_accept_terms(
2599 LanguageModelProviderTosView::ThreadFreshStart,
2600 cx,
2601 ))
2602 }
2603 None => parent,
2604 }),
2605 )
2606 })
2607 .when(!recent_history.is_empty(), |parent| {
2608 let focus_handle = focus_handle.clone();
2609 let configuration_error_ref = &configuration_error;
2610
2611 parent
2612 .overflow_hidden()
2613 .p_1p5()
2614 .justify_end()
2615 .gap_1()
2616 .child(
2617 h_flex()
2618 .pl_1p5()
2619 .pb_1()
2620 .w_full()
2621 .justify_between()
2622 .border_b_1()
2623 .border_color(cx.theme().colors().border_variant)
2624 .child(
2625 Label::new("Recent")
2626 .size(LabelSize::Small)
2627 .color(Color::Muted),
2628 )
2629 .child(
2630 Button::new("view-history", "View All")
2631 .style(ButtonStyle::Subtle)
2632 .label_size(LabelSize::Small)
2633 .key_binding(
2634 KeyBinding::for_action_in(
2635 &OpenHistory,
2636 &self.focus_handle(cx),
2637 window,
2638 cx,
2639 )
2640 .map(|kb| kb.size(rems_from_px(12.))),
2641 )
2642 .on_click(move |_event, window, cx| {
2643 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2644 }),
2645 ),
2646 )
2647 .child(
2648 v_flex()
2649 .gap_1()
2650 .children(recent_history.into_iter().enumerate().map(
2651 |(index, entry)| {
2652 // TODO: Add keyboard navigation.
2653 let is_hovered =
2654 self.hovered_recent_history_item == Some(index);
2655 HistoryEntryElement::new(entry.clone(), cx.entity().downgrade())
2656 .hovered(is_hovered)
2657 .on_hover(cx.listener(
2658 move |this, is_hovered, _window, cx| {
2659 if *is_hovered {
2660 this.hovered_recent_history_item = Some(index);
2661 } else if this.hovered_recent_history_item
2662 == Some(index)
2663 {
2664 this.hovered_recent_history_item = None;
2665 }
2666 cx.notify();
2667 },
2668 ))
2669 .into_any_element()
2670 },
2671 )),
2672 )
2673 .map(|parent| match configuration_error_ref {
2674 Some(
2675 err @ (ConfigurationError::ModelNotFound
2676 | ConfigurationError::ProviderNotAuthenticated(_)
2677 | ConfigurationError::NoProvider),
2678 ) => parent.child(
2679 Banner::new()
2680 .severity(ui::Severity::Warning)
2681 .child(Label::new(err.to_string()).size(LabelSize::Small))
2682 .action_slot(
2683 Button::new("settings", "Configure Provider")
2684 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2685 .label_size(LabelSize::Small)
2686 .key_binding(
2687 KeyBinding::for_action_in(
2688 &OpenConfiguration,
2689 &focus_handle,
2690 window,
2691 cx,
2692 )
2693 .map(|kb| kb.size(rems_from_px(12.))),
2694 )
2695 .on_click(|_event, window, cx| {
2696 window.dispatch_action(
2697 OpenConfiguration.boxed_clone(),
2698 cx,
2699 )
2700 }),
2701 ),
2702 ),
2703 Some(ConfigurationError::ProviderPendingTermsAcceptance(provider)) => {
2704 parent.child(Banner::new().severity(ui::Severity::Warning).child(
2705 h_flex().w_full().children(provider.render_accept_terms(
2706 LanguageModelProviderTosView::ThreadtEmptyState,
2707 cx,
2708 )),
2709 ))
2710 }
2711 None => parent,
2712 })
2713 })
2714 }
2715
2716 fn render_tool_use_limit_reached(
2717 &self,
2718 window: &mut Window,
2719 cx: &mut Context<Self>,
2720 ) -> Option<AnyElement> {
2721 let active_thread = match &self.active_view {
2722 ActiveView::Thread { thread, .. } => thread,
2723 ActiveView::AcpThread { .. } => {
2724 // todo!
2725 return None;
2726 }
2727 ActiveView::TextThread { .. } | ActiveView::History | ActiveView::Configuration => {
2728 return None;
2729 }
2730 };
2731
2732 let thread = active_thread.read(cx).thread().read(cx);
2733
2734 let tool_use_limit_reached = thread.tool_use_limit_reached();
2735 if !tool_use_limit_reached {
2736 return None;
2737 }
2738
2739 let model = thread.configured_model()?.model;
2740
2741 let focus_handle = self.focus_handle(cx);
2742
2743 let banner = Banner::new()
2744 .severity(ui::Severity::Info)
2745 .child(Label::new("Consecutive tool use limit reached.").size(LabelSize::Small))
2746 .action_slot(
2747 h_flex()
2748 .gap_1()
2749 .child(
2750 Button::new("continue-conversation", "Continue")
2751 .layer(ElevationIndex::ModalSurface)
2752 .label_size(LabelSize::Small)
2753 .key_binding(
2754 KeyBinding::for_action_in(
2755 &ContinueThread,
2756 &focus_handle,
2757 window,
2758 cx,
2759 )
2760 .map(|kb| kb.size(rems_from_px(10.))),
2761 )
2762 .on_click(cx.listener(|this, _, window, cx| {
2763 this.continue_conversation(window, cx);
2764 })),
2765 )
2766 .when(model.supports_max_mode(), |this| {
2767 this.child(
2768 Button::new("continue-burn-mode", "Continue with Burn Mode")
2769 .style(ButtonStyle::Filled)
2770 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2771 .layer(ElevationIndex::ModalSurface)
2772 .label_size(LabelSize::Small)
2773 .key_binding(
2774 KeyBinding::for_action_in(
2775 &ContinueWithBurnMode,
2776 &focus_handle,
2777 window,
2778 cx,
2779 )
2780 .map(|kb| kb.size(rems_from_px(10.))),
2781 )
2782 .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
2783 .on_click({
2784 let active_thread = active_thread.clone();
2785 cx.listener(move |this, _, window, cx| {
2786 active_thread.update(cx, |active_thread, cx| {
2787 active_thread.thread().update(cx, |thread, _cx| {
2788 thread.set_completion_mode(CompletionMode::Burn);
2789 });
2790 });
2791 this.continue_conversation(window, cx);
2792 })
2793 }),
2794 )
2795 }),
2796 );
2797
2798 Some(div().px_2().pb_2().child(banner).into_any_element())
2799 }
2800
2801 fn render_payment_required_error(
2802 &self,
2803 thread: &Entity<ActiveThread>,
2804 cx: &mut Context<Self>,
2805 ) -> AnyElement {
2806 const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
2807
2808 v_flex()
2809 .gap_0p5()
2810 .child(
2811 h_flex()
2812 .gap_1p5()
2813 .items_center()
2814 .child(Icon::new(IconName::XCircle).color(Color::Error))
2815 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2816 )
2817 .child(
2818 div()
2819 .id("error-message")
2820 .max_h_24()
2821 .overflow_y_scroll()
2822 .child(Label::new(ERROR_MESSAGE)),
2823 )
2824 .child(
2825 h_flex()
2826 .justify_end()
2827 .mt_1()
2828 .gap_1()
2829 .child(self.create_copy_button(ERROR_MESSAGE))
2830 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener({
2831 let thread = thread.clone();
2832 move |_, _, _, cx| {
2833 thread.update(cx, |this, _cx| {
2834 this.clear_last_error();
2835 });
2836
2837 cx.open_url(&zed_urls::account_url(cx));
2838 cx.notify();
2839 }
2840 })))
2841 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener({
2842 let thread = thread.clone();
2843 move |_, _, _, cx| {
2844 thread.update(cx, |this, _cx| {
2845 this.clear_last_error();
2846 });
2847
2848 cx.notify();
2849 }
2850 }))),
2851 )
2852 .into_any()
2853 }
2854
2855 fn render_model_request_limit_reached_error(
2856 &self,
2857 plan: Plan,
2858 thread: &Entity<ActiveThread>,
2859 cx: &mut Context<Self>,
2860 ) -> AnyElement {
2861 let error_message = match plan {
2862 Plan::ZedPro => {
2863 "Model request limit reached. Upgrade to usage-based billing for more requests."
2864 }
2865 Plan::ZedProTrial => {
2866 "Model request limit reached. Upgrade to Zed Pro for more requests."
2867 }
2868 Plan::Free => "Model request limit reached. Upgrade to Zed Pro for more requests.",
2869 };
2870 let call_to_action = match plan {
2871 Plan::ZedPro => "Upgrade to usage-based billing",
2872 Plan::ZedProTrial => "Upgrade to Zed Pro",
2873 Plan::Free => "Upgrade to Zed Pro",
2874 };
2875
2876 v_flex()
2877 .gap_0p5()
2878 .child(
2879 h_flex()
2880 .gap_1p5()
2881 .items_center()
2882 .child(Icon::new(IconName::XCircle).color(Color::Error))
2883 .child(Label::new("Model Request Limit Reached").weight(FontWeight::MEDIUM)),
2884 )
2885 .child(
2886 div()
2887 .id("error-message")
2888 .max_h_24()
2889 .overflow_y_scroll()
2890 .child(Label::new(error_message)),
2891 )
2892 .child(
2893 h_flex()
2894 .justify_end()
2895 .mt_1()
2896 .gap_1()
2897 .child(self.create_copy_button(error_message))
2898 .child(
2899 Button::new("subscribe", call_to_action).on_click(cx.listener({
2900 let thread = thread.clone();
2901 move |_, _, _, cx| {
2902 thread.update(cx, |this, _cx| {
2903 this.clear_last_error();
2904 });
2905
2906 cx.open_url(&zed_urls::account_url(cx));
2907 cx.notify();
2908 }
2909 })),
2910 )
2911 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener({
2912 let thread = thread.clone();
2913 move |_, _, _, cx| {
2914 thread.update(cx, |this, _cx| {
2915 this.clear_last_error();
2916 });
2917
2918 cx.notify();
2919 }
2920 }))),
2921 )
2922 .into_any()
2923 }
2924
2925 fn render_error_message(
2926 &self,
2927 header: SharedString,
2928 message: SharedString,
2929 thread: &Entity<ActiveThread>,
2930 cx: &mut Context<Self>,
2931 ) -> AnyElement {
2932 let message_with_header = format!("{}\n{}", header, message);
2933 v_flex()
2934 .gap_0p5()
2935 .child(
2936 h_flex()
2937 .gap_1p5()
2938 .items_center()
2939 .child(Icon::new(IconName::XCircle).color(Color::Error))
2940 .child(Label::new(header).weight(FontWeight::MEDIUM)),
2941 )
2942 .child(
2943 div()
2944 .id("error-message")
2945 .max_h_32()
2946 .overflow_y_scroll()
2947 .child(Label::new(message.clone())),
2948 )
2949 .child(
2950 h_flex()
2951 .justify_end()
2952 .mt_1()
2953 .gap_1()
2954 .child(self.create_copy_button(message_with_header))
2955 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener({
2956 let thread = thread.clone();
2957 move |_, _, _, cx| {
2958 thread.update(cx, |this, _cx| {
2959 this.clear_last_error();
2960 });
2961
2962 cx.notify();
2963 }
2964 }))),
2965 )
2966 .into_any()
2967 }
2968
2969 fn render_prompt_editor(
2970 &self,
2971 context_editor: &Entity<TextThreadEditor>,
2972 buffer_search_bar: &Entity<BufferSearchBar>,
2973 window: &mut Window,
2974 cx: &mut Context<Self>,
2975 ) -> Div {
2976 let mut registrar = buffer_search::DivRegistrar::new(
2977 |this, _, _cx| match &this.active_view {
2978 ActiveView::TextThread {
2979 buffer_search_bar, ..
2980 } => Some(buffer_search_bar.clone()),
2981 _ => None,
2982 },
2983 cx,
2984 );
2985 BufferSearchBar::register(&mut registrar);
2986 registrar
2987 .into_div()
2988 .size_full()
2989 .relative()
2990 .map(|parent| {
2991 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
2992 if buffer_search_bar.is_dismissed() {
2993 return parent;
2994 }
2995 parent.child(
2996 div()
2997 .p(DynamicSpacing::Base08.rems(cx))
2998 .border_b_1()
2999 .border_color(cx.theme().colors().border_variant)
3000 .bg(cx.theme().colors().editor_background)
3001 .child(buffer_search_bar.render(window, cx)),
3002 )
3003 })
3004 })
3005 .child(context_editor.clone())
3006 .child(self.render_drag_target(cx))
3007 }
3008
3009 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
3010 let is_local = self.project.read(cx).is_local();
3011 div()
3012 .invisible()
3013 .absolute()
3014 .top_0()
3015 .right_0()
3016 .bottom_0()
3017 .left_0()
3018 .bg(cx.theme().colors().drop_target_background)
3019 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
3020 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
3021 .when(is_local, |this| {
3022 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
3023 })
3024 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
3025 let item = tab.pane.read(cx).item_for_index(tab.ix);
3026 let project_paths = item
3027 .and_then(|item| item.project_path(cx))
3028 .into_iter()
3029 .collect::<Vec<_>>();
3030 this.handle_drop(project_paths, vec![], window, cx);
3031 }))
3032 .on_drop(
3033 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
3034 let project_paths = selection
3035 .items()
3036 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
3037 .collect::<Vec<_>>();
3038 this.handle_drop(project_paths, vec![], window, cx);
3039 }),
3040 )
3041 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
3042 let tasks = paths
3043 .paths()
3044 .into_iter()
3045 .map(|path| {
3046 Workspace::project_path_for_path(this.project.clone(), &path, false, cx)
3047 })
3048 .collect::<Vec<_>>();
3049 cx.spawn_in(window, async move |this, cx| {
3050 let mut paths = vec![];
3051 let mut added_worktrees = vec![];
3052 let opened_paths = futures::future::join_all(tasks).await;
3053 for entry in opened_paths {
3054 if let Some((worktree, project_path)) = entry.log_err() {
3055 added_worktrees.push(worktree);
3056 paths.push(project_path);
3057 }
3058 }
3059 this.update_in(cx, |this, window, cx| {
3060 this.handle_drop(paths, added_worktrees, window, cx);
3061 })
3062 .ok();
3063 })
3064 .detach();
3065 }))
3066 }
3067
3068 fn handle_drop(
3069 &mut self,
3070 paths: Vec<ProjectPath>,
3071 added_worktrees: Vec<Entity<Worktree>>,
3072 window: &mut Window,
3073 cx: &mut Context<Self>,
3074 ) {
3075 match &self.active_view {
3076 ActiveView::Thread { thread, .. } => {
3077 let context_store = thread.read(cx).context_store().clone();
3078 context_store.update(cx, move |context_store, cx| {
3079 let mut tasks = Vec::new();
3080 for project_path in &paths {
3081 tasks.push(context_store.add_file_from_path(
3082 project_path.clone(),
3083 false,
3084 cx,
3085 ));
3086 }
3087 cx.background_spawn(async move {
3088 futures::future::join_all(tasks).await;
3089 // Need to hold onto the worktrees until they have already been used when
3090 // opening the buffers.
3091 drop(added_worktrees);
3092 })
3093 .detach();
3094 });
3095 }
3096 ActiveView::AcpThread { .. } => {
3097 unimplemented!()
3098 }
3099 ActiveView::TextThread { context_editor, .. } => {
3100 context_editor.update(cx, |context_editor, cx| {
3101 TextThreadEditor::insert_dragged_files(
3102 context_editor,
3103 paths,
3104 added_worktrees,
3105 window,
3106 cx,
3107 );
3108 });
3109 }
3110 ActiveView::History | ActiveView::Configuration => {}
3111 }
3112 }
3113
3114 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3115 let message = message.into();
3116 IconButton::new("copy", IconName::Copy)
3117 .on_click(move |_, _, cx| {
3118 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3119 })
3120 .tooltip(Tooltip::text("Copy Error Message"))
3121 }
3122
3123 fn key_context(&self) -> KeyContext {
3124 let mut key_context = KeyContext::new_with_defaults();
3125 key_context.add("AgentPanel");
3126 if matches!(self.active_view, ActiveView::TextThread { .. }) {
3127 key_context.add("prompt_editor");
3128 }
3129 key_context
3130 }
3131}
3132
3133impl Render for AgentPanel {
3134 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3135 // WARNING: Changes to this element hierarchy can have
3136 // non-obvious implications to the layout of children.
3137 //
3138 // If you need to change it, please confirm:
3139 // - The message editor expands (cmd-option-esc) correctly
3140 // - When expanded, the buttons at the bottom of the panel are displayed correctly
3141 // - Font size works as expected and can be changed with cmd-+/cmd-
3142 // - Scrolling in all views works as expected
3143 // - Files can be dropped into the panel
3144 let content = v_flex()
3145 .key_context(self.key_context())
3146 .justify_between()
3147 .size_full()
3148 .on_action(cx.listener(Self::cancel))
3149 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
3150 this.new_thread(action, window, cx);
3151 }))
3152 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
3153 this.open_history(window, cx);
3154 }))
3155 .on_action(cx.listener(|this, _: &OpenConfiguration, window, cx| {
3156 this.open_configuration(window, cx);
3157 }))
3158 .on_action(cx.listener(Self::open_active_thread_as_markdown))
3159 .on_action(cx.listener(Self::deploy_rules_library))
3160 .on_action(cx.listener(Self::open_agent_diff))
3161 .on_action(cx.listener(Self::go_back))
3162 .on_action(cx.listener(Self::toggle_navigation_menu))
3163 .on_action(cx.listener(Self::toggle_options_menu))
3164 .on_action(cx.listener(Self::increase_font_size))
3165 .on_action(cx.listener(Self::decrease_font_size))
3166 .on_action(cx.listener(Self::reset_font_size))
3167 .on_action(cx.listener(Self::toggle_zoom))
3168 .on_action(cx.listener(|this, _: &ContinueThread, window, cx| {
3169 this.continue_conversation(window, cx);
3170 }))
3171 .on_action(cx.listener(|this, _: &ContinueWithBurnMode, window, cx| {
3172 match &this.active_view {
3173 ActiveView::Thread { thread, .. } => {
3174 thread.update(cx, |active_thread, cx| {
3175 active_thread.thread().update(cx, |thread, _cx| {
3176 thread.set_completion_mode(CompletionMode::Burn);
3177 });
3178 });
3179 this.continue_conversation(window, cx);
3180 }
3181 ActiveView::AcpThread { .. } => {
3182 todo!()
3183 }
3184 ActiveView::TextThread { .. }
3185 | ActiveView::History
3186 | ActiveView::Configuration => {}
3187 }
3188 }))
3189 .on_action(cx.listener(Self::toggle_burn_mode))
3190 .child(self.render_toolbar(window, cx))
3191 .children(self.render_upsell(window, cx))
3192 .children(self.render_trial_end_upsell(window, cx))
3193 .map(|parent| match &self.active_view {
3194 ActiveView::Thread {
3195 thread,
3196 message_editor,
3197 ..
3198 } => parent
3199 .relative()
3200 .child(if thread.read(cx).is_empty() {
3201 self.render_thread_empty_state(window, cx)
3202 .into_any_element()
3203 } else {
3204 thread.clone().into_any_element()
3205 })
3206 .children(self.render_tool_use_limit_reached(window, cx))
3207 .child(h_flex().child(message_editor.clone()))
3208 .when_some(thread.read(cx).last_error(), |this, last_error| {
3209 this.child(
3210 div()
3211 .absolute()
3212 .right_3()
3213 .bottom_12()
3214 .max_w_96()
3215 .py_2()
3216 .px_3()
3217 .elevation_2(cx)
3218 .occlude()
3219 .child(match last_error {
3220 ThreadError::PaymentRequired => {
3221 self.render_payment_required_error(thread, cx)
3222 }
3223 ThreadError::ModelRequestLimitReached { plan } => self
3224 .render_model_request_limit_reached_error(plan, thread, cx),
3225 ThreadError::Message { header, message } => {
3226 self.render_error_message(header, message, thread, cx)
3227 }
3228 })
3229 .into_any(),
3230 )
3231 })
3232 .child(self.render_drag_target(cx)),
3233 ActiveView::AcpThread { thread_element, .. } => parent
3234 .relative()
3235 .child(thread_element.clone())
3236 // todo!
3237 // .child(h_flex().child(self.message_editor.clone()))
3238 .child(self.render_drag_target(cx)),
3239 ActiveView::History => parent.child(self.history.clone()),
3240 ActiveView::TextThread {
3241 context_editor,
3242 buffer_search_bar,
3243 ..
3244 } => parent.child(self.render_prompt_editor(
3245 context_editor,
3246 buffer_search_bar,
3247 window,
3248 cx,
3249 )),
3250 ActiveView::Configuration => parent.children(self.configuration.clone()),
3251 });
3252
3253 match self.active_view.which_font_size_used() {
3254 WhichFontSize::AgentFont => {
3255 WithRemSize::new(ThemeSettings::get_global(cx).agent_font_size(cx))
3256 .size_full()
3257 .child(content)
3258 .into_any()
3259 }
3260 _ => content.into_any(),
3261 }
3262 }
3263}
3264
3265struct PromptLibraryInlineAssist {
3266 workspace: WeakEntity<Workspace>,
3267}
3268
3269impl PromptLibraryInlineAssist {
3270 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
3271 Self { workspace }
3272 }
3273}
3274
3275impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
3276 fn assist(
3277 &self,
3278 prompt_editor: &Entity<Editor>,
3279 initial_prompt: Option<String>,
3280 window: &mut Window,
3281 cx: &mut Context<RulesLibrary>,
3282 ) {
3283 InlineAssistant::update_global(cx, |assistant, cx| {
3284 let Some(project) = self
3285 .workspace
3286 .upgrade()
3287 .map(|workspace| workspace.read(cx).project().downgrade())
3288 else {
3289 return;
3290 };
3291 let prompt_store = None;
3292 let thread_store = None;
3293 let text_thread_store = None;
3294 let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
3295 assistant.assist(
3296 &prompt_editor,
3297 self.workspace.clone(),
3298 context_store,
3299 project,
3300 prompt_store,
3301 thread_store,
3302 text_thread_store,
3303 initial_prompt,
3304 window,
3305 cx,
3306 )
3307 })
3308 }
3309
3310 fn focus_agent_panel(
3311 &self,
3312 workspace: &mut Workspace,
3313 window: &mut Window,
3314 cx: &mut Context<Workspace>,
3315 ) -> bool {
3316 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
3317 }
3318}
3319
3320pub struct ConcreteAssistantPanelDelegate;
3321
3322impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
3323 fn active_context_editor(
3324 &self,
3325 workspace: &mut Workspace,
3326 _window: &mut Window,
3327 cx: &mut Context<Workspace>,
3328 ) -> Option<Entity<TextThreadEditor>> {
3329 let panel = workspace.panel::<AgentPanel>(cx)?;
3330 panel.read(cx).active_context_editor()
3331 }
3332
3333 fn open_saved_context(
3334 &self,
3335 workspace: &mut Workspace,
3336 path: Arc<Path>,
3337 window: &mut Window,
3338 cx: &mut Context<Workspace>,
3339 ) -> Task<Result<()>> {
3340 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3341 return Task::ready(Err(anyhow!("Agent panel not found")));
3342 };
3343
3344 panel.update(cx, |panel, cx| {
3345 panel.open_saved_prompt_editor(path, window, cx)
3346 })
3347 }
3348
3349 fn open_remote_context(
3350 &self,
3351 _workspace: &mut Workspace,
3352 _context_id: assistant_context::ContextId,
3353 _window: &mut Window,
3354 _cx: &mut Context<Workspace>,
3355 ) -> Task<Result<Entity<TextThreadEditor>>> {
3356 Task::ready(Err(anyhow!("opening remote context not implemented")))
3357 }
3358
3359 fn quote_selection(
3360 &self,
3361 workspace: &mut Workspace,
3362 selection_ranges: Vec<Range<Anchor>>,
3363 buffer: Entity<MultiBuffer>,
3364 window: &mut Window,
3365 cx: &mut Context<Workspace>,
3366 ) {
3367 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
3368 return;
3369 };
3370
3371 if !panel.focus_handle(cx).contains_focused(window, cx) {
3372 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
3373 }
3374
3375 panel.update(cx, |_, cx| {
3376 // Wait to create a new context until the workspace is no longer
3377 // being updated.
3378 cx.defer_in(window, move |panel, window, cx| {
3379 if let Some(message_editor) = panel.active_message_editor() {
3380 message_editor.update(cx, |message_editor, cx| {
3381 message_editor.context_store().update(cx, |store, cx| {
3382 let buffer = buffer.read(cx);
3383 let selection_ranges = selection_ranges
3384 .into_iter()
3385 .flat_map(|range| {
3386 let (start_buffer, start) =
3387 buffer.text_anchor_for_position(range.start, cx)?;
3388 let (end_buffer, end) =
3389 buffer.text_anchor_for_position(range.end, cx)?;
3390 if start_buffer != end_buffer {
3391 return None;
3392 }
3393 Some((start_buffer, start..end))
3394 })
3395 .collect::<Vec<_>>();
3396
3397 for (buffer, range) in selection_ranges {
3398 store.add_selection(buffer, range, cx);
3399 }
3400 })
3401 })
3402 } else if let Some(context_editor) = panel.active_context_editor() {
3403 let snapshot = buffer.read(cx).snapshot(cx);
3404 let selection_ranges = selection_ranges
3405 .into_iter()
3406 .map(|range| range.to_point(&snapshot))
3407 .collect::<Vec<_>>();
3408
3409 context_editor.update(cx, |context_editor, cx| {
3410 context_editor.quote_ranges(selection_ranges, snapshot, window, cx)
3411 });
3412 }
3413 });
3414 });
3415 }
3416}
3417
3418struct Upsell;
3419
3420impl Dismissable for Upsell {
3421 const KEY: &'static str = "dismissed-trial-upsell";
3422}
3423
3424struct TrialEndUpsell;
3425
3426impl Dismissable for TrialEndUpsell {
3427 const KEY: &'static str = "dismissed-trial-end-upsell";
3428}