1use crate::{
2 assistant_settings::{AssistantDockPosition, AssistantSettings},
3 humanize_token_count,
4 prompt_library::open_prompt_library,
5 prompts::PromptBuilder,
6 slash_command::{
7 default_command::DefaultSlashCommand,
8 docs_command::{DocsSlashCommand, DocsSlashCommandArgs},
9 file_command::{self, codeblock_fence_for_path},
10 SlashCommandCompletionProvider, SlashCommandRegistry,
11 },
12 slash_command_picker,
13 terminal_inline_assistant::TerminalInlineAssistant,
14 Assist, AssistantPatch, AssistantPatchStatus, CacheStatus, ConfirmCommand, Content, Context,
15 ContextEvent, ContextId, ContextStore, ContextStoreEvent, CopyCode, CycleMessageRole,
16 DeployHistory, DeployPromptLibrary, Edit, InlineAssistant, InsertDraggedFiles,
17 InsertIntoEditor, Message, MessageId, MessageMetadata, MessageStatus, ModelPickerDelegate,
18 ModelSelector, NewContext, PendingSlashCommand, PendingSlashCommandStatus, QuoteSelection,
19 RemoteContextMetadata, RequestType, SavedContextMetadata, Split, ToggleFocus,
20 ToggleModelSelector,
21};
22use anyhow::Result;
23use assistant_slash_command::{SlashCommand, SlashCommandOutputSection};
24use assistant_tool::ToolRegistry;
25use client::{proto, zed_urls, Client, Status};
26use collections::{BTreeSet, HashMap, HashSet};
27use editor::{
28 actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
29 display_map::{
30 BlockContext, BlockId, BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata,
31 CustomBlockId, FoldId, RenderBlock, ToDisplayPoint,
32 },
33 scroll::{Autoscroll, AutoscrollStrategy},
34 Anchor, Editor, EditorEvent, ProposedChangeLocation, ProposedChangesEditor, RowExt,
35 ToOffset as _, ToPoint,
36};
37use editor::{display_map::CreaseId, FoldPlaceholder};
38use fs::Fs;
39use futures::FutureExt;
40use gpui::{
41 canvas, div, img, percentage, point, pulsating_between, size, Action, Animation, AnimationExt,
42 AnyElement, AnyView, AppContext, AsyncWindowContext, ClipboardEntry, ClipboardItem,
43 CursorStyle, Empty, Entity, EventEmitter, ExternalPaths, FocusHandle, FocusableView,
44 FontWeight, InteractiveElement, IntoElement, Model, ParentElement, Pixels, Render, RenderImage,
45 SharedString, Size, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
46 UpdateGlobal, View, VisualContext, WeakView, WindowContext,
47};
48use indexed_docs::IndexedDocsStore;
49use language::{
50 language_settings::SoftWrap, BufferSnapshot, LanguageRegistry, LspAdapterDelegate, ToOffset,
51};
52use language_model::{
53 provider::cloud::PROVIDER_ID, LanguageModelProvider, LanguageModelProviderId,
54 LanguageModelRegistry, Role,
55};
56use language_model::{LanguageModelImage, LanguageModelToolUse};
57use multi_buffer::MultiBufferRow;
58use picker::{Picker, PickerDelegate};
59use project::lsp_store::LocalLspAdapterDelegate;
60use project::{Project, Worktree};
61use rope::Point;
62use search::{buffer_search::DivRegistrar, BufferSearchBar};
63use serde::{Deserialize, Serialize};
64use settings::{update_settings_file, Settings};
65use smol::stream::StreamExt;
66use std::{
67 borrow::Cow,
68 cmp,
69 ops::{ControlFlow, Range},
70 path::PathBuf,
71 sync::Arc,
72 time::Duration,
73};
74use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
75use text::SelectionGoal;
76use ui::TintColor;
77use ui::{
78 prelude::*,
79 utils::{format_distance_from_now, DateTimeType},
80 Avatar, ButtonLike, ContextMenu, Disclosure, ElevationIndex, KeyBinding, ListItem,
81 ListItemSpacing, PopoverMenu, PopoverMenuHandle, Tooltip,
82};
83use util::{maybe, ResultExt};
84use workspace::{
85 dock::{DockPosition, Panel, PanelEvent},
86 item::{self, FollowableItem, Item, ItemHandle},
87 notifications::NotificationId,
88 pane::{self, SaveIntent},
89 searchable::{SearchEvent, SearchableItem},
90 DraggedSelection, Pane, Save, ShowConfiguration, Toast, ToggleZoom, ToolbarItemEvent,
91 ToolbarItemLocation, ToolbarItemView, Workspace,
92};
93use workspace::{searchable::SearchableItemHandle, DraggedTab};
94use zed_actions::InlineAssist;
95
96pub fn init(cx: &mut AppContext) {
97 workspace::FollowableViewRegistry::register::<ContextEditor>(cx);
98 cx.observe_new_views(
99 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
100 workspace
101 .register_action(|workspace, _: &ToggleFocus, cx| {
102 let settings = AssistantSettings::get_global(cx);
103 if !settings.enabled {
104 return;
105 }
106
107 workspace.toggle_panel_focus::<AssistantPanel>(cx);
108 })
109 .register_action(AssistantPanel::inline_assist)
110 .register_action(ContextEditor::quote_selection)
111 .register_action(ContextEditor::insert_selection)
112 .register_action(ContextEditor::copy_code)
113 .register_action(ContextEditor::insert_dragged_files)
114 .register_action(AssistantPanel::show_configuration)
115 .register_action(AssistantPanel::create_new_context);
116 },
117 )
118 .detach();
119
120 cx.observe_new_views(
121 |terminal_panel: &mut TerminalPanel, cx: &mut ViewContext<TerminalPanel>| {
122 let settings = AssistantSettings::get_global(cx);
123 terminal_panel.asssistant_enabled(settings.enabled, cx);
124 },
125 )
126 .detach();
127}
128
129pub enum AssistantPanelEvent {
130 ContextEdited,
131}
132
133pub struct AssistantPanel {
134 pane: View<Pane>,
135 workspace: WeakView<Workspace>,
136 width: Option<Pixels>,
137 height: Option<Pixels>,
138 project: Model<Project>,
139 context_store: Model<ContextStore>,
140 languages: Arc<LanguageRegistry>,
141 fs: Arc<dyn Fs>,
142 subscriptions: Vec<Subscription>,
143 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
144 model_summary_editor: View<Editor>,
145 authenticate_provider_task: Option<(LanguageModelProviderId, Task<()>)>,
146 configuration_subscription: Option<Subscription>,
147 client_status: Option<client::Status>,
148 watch_client_status: Option<Task<()>>,
149 show_zed_ai_notice: bool,
150}
151
152#[derive(Clone)]
153enum ContextMetadata {
154 Remote(RemoteContextMetadata),
155 Saved(SavedContextMetadata),
156}
157
158struct SavedContextPickerDelegate {
159 store: Model<ContextStore>,
160 project: Model<Project>,
161 matches: Vec<ContextMetadata>,
162 selected_index: usize,
163}
164
165enum SavedContextPickerEvent {
166 Confirmed(ContextMetadata),
167}
168
169enum InlineAssistTarget {
170 Editor(View<Editor>, bool),
171 Terminal(View<TerminalView>),
172}
173
174impl EventEmitter<SavedContextPickerEvent> for Picker<SavedContextPickerDelegate> {}
175
176impl SavedContextPickerDelegate {
177 fn new(project: Model<Project>, store: Model<ContextStore>) -> Self {
178 Self {
179 project,
180 store,
181 matches: Vec::new(),
182 selected_index: 0,
183 }
184 }
185}
186
187impl PickerDelegate for SavedContextPickerDelegate {
188 type ListItem = ListItem;
189
190 fn match_count(&self) -> usize {
191 self.matches.len()
192 }
193
194 fn selected_index(&self) -> usize {
195 self.selected_index
196 }
197
198 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
199 self.selected_index = ix;
200 }
201
202 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
203 "Search...".into()
204 }
205
206 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
207 let search = self.store.read(cx).search(query, cx);
208 cx.spawn(|this, mut cx| async move {
209 let matches = search.await;
210 this.update(&mut cx, |this, cx| {
211 let host_contexts = this.delegate.store.read(cx).host_contexts();
212 this.delegate.matches = host_contexts
213 .iter()
214 .cloned()
215 .map(ContextMetadata::Remote)
216 .chain(matches.into_iter().map(ContextMetadata::Saved))
217 .collect();
218 this.delegate.selected_index = 0;
219 cx.notify();
220 })
221 .ok();
222 })
223 }
224
225 fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
226 if let Some(metadata) = self.matches.get(self.selected_index) {
227 cx.emit(SavedContextPickerEvent::Confirmed(metadata.clone()));
228 }
229 }
230
231 fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
232
233 fn render_match(
234 &self,
235 ix: usize,
236 selected: bool,
237 cx: &mut ViewContext<Picker<Self>>,
238 ) -> Option<Self::ListItem> {
239 let context = self.matches.get(ix)?;
240 let item = match context {
241 ContextMetadata::Remote(context) => {
242 let host_user = self.project.read(cx).host().and_then(|collaborator| {
243 self.project
244 .read(cx)
245 .user_store()
246 .read(cx)
247 .get_cached_user(collaborator.user_id)
248 });
249 div()
250 .flex()
251 .w_full()
252 .justify_between()
253 .gap_2()
254 .child(
255 h_flex().flex_1().overflow_x_hidden().child(
256 Label::new(context.summary.clone().unwrap_or(DEFAULT_TAB_TITLE.into()))
257 .size(LabelSize::Small),
258 ),
259 )
260 .child(
261 h_flex()
262 .gap_2()
263 .children(if let Some(host_user) = host_user {
264 vec![
265 Avatar::new(host_user.avatar_uri.clone()).into_any_element(),
266 Label::new(format!("Shared by @{}", host_user.github_login))
267 .color(Color::Muted)
268 .size(LabelSize::Small)
269 .into_any_element(),
270 ]
271 } else {
272 vec![Label::new("Shared by host")
273 .color(Color::Muted)
274 .size(LabelSize::Small)
275 .into_any_element()]
276 }),
277 )
278 }
279 ContextMetadata::Saved(context) => div()
280 .flex()
281 .w_full()
282 .justify_between()
283 .gap_2()
284 .child(
285 h_flex()
286 .flex_1()
287 .child(Label::new(context.title.clone()).size(LabelSize::Small))
288 .overflow_x_hidden(),
289 )
290 .child(
291 Label::new(format_distance_from_now(
292 DateTimeType::Local(context.mtime),
293 false,
294 true,
295 true,
296 ))
297 .color(Color::Muted)
298 .size(LabelSize::Small),
299 ),
300 };
301 Some(
302 ListItem::new(ix)
303 .inset(true)
304 .spacing(ListItemSpacing::Sparse)
305 .selected(selected)
306 .child(item),
307 )
308 }
309}
310
311impl AssistantPanel {
312 pub fn load(
313 workspace: WeakView<Workspace>,
314 prompt_builder: Arc<PromptBuilder>,
315 cx: AsyncWindowContext,
316 ) -> Task<Result<View<Self>>> {
317 cx.spawn(|mut cx| async move {
318 let context_store = workspace
319 .update(&mut cx, |workspace, cx| {
320 let project = workspace.project().clone();
321 ContextStore::new(project, prompt_builder.clone(), cx)
322 })?
323 .await?;
324
325 workspace.update(&mut cx, |workspace, cx| {
326 // TODO: deserialize state.
327 cx.new_view(|cx| Self::new(workspace, context_store, cx))
328 })
329 })
330 }
331
332 fn new(
333 workspace: &Workspace,
334 context_store: Model<ContextStore>,
335 cx: &mut ViewContext<Self>,
336 ) -> Self {
337 let model_selector_menu_handle = PopoverMenuHandle::default();
338 let model_summary_editor = cx.new_view(Editor::single_line);
339 let context_editor_toolbar = cx.new_view(|_| {
340 ContextEditorToolbarItem::new(
341 workspace,
342 model_selector_menu_handle.clone(),
343 model_summary_editor.clone(),
344 )
345 });
346
347 let pane = cx.new_view(|cx| {
348 let mut pane = Pane::new(
349 workspace.weak_handle(),
350 workspace.project().clone(),
351 Default::default(),
352 None,
353 NewContext.boxed_clone(),
354 cx,
355 );
356
357 let project = workspace.project().clone();
358 pane.set_custom_drop_handle(cx, move |_, dropped_item, cx| {
359 let action = maybe!({
360 if project.read(cx).is_local() {
361 if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
362 return Some(InsertDraggedFiles::ExternalFiles(paths.paths().to_vec()));
363 }
364 }
365
366 let project_paths = if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>()
367 {
368 if &tab.pane == cx.view() {
369 return None;
370 }
371 let item = tab.pane.read(cx).item_for_index(tab.ix);
372 Some(
373 item.and_then(|item| item.project_path(cx))
374 .into_iter()
375 .collect::<Vec<_>>(),
376 )
377 } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>()
378 {
379 Some(
380 selection
381 .items()
382 .filter_map(|item| {
383 project.read(cx).path_for_entry(item.entry_id, cx)
384 })
385 .collect::<Vec<_>>(),
386 )
387 } else {
388 None
389 }?;
390
391 let paths = project_paths
392 .into_iter()
393 .filter_map(|project_path| {
394 let worktree = project
395 .read(cx)
396 .worktree_for_id(project_path.worktree_id, cx)?;
397
398 let mut full_path = PathBuf::from(worktree.read(cx).root_name());
399 full_path.push(&project_path.path);
400 Some(full_path)
401 })
402 .collect::<Vec<_>>();
403
404 Some(InsertDraggedFiles::ProjectPaths(paths))
405 });
406
407 if let Some(action) = action {
408 cx.dispatch_action(action.boxed_clone());
409 }
410
411 ControlFlow::Break(())
412 });
413
414 pane.set_can_split(false, cx);
415 pane.set_can_navigate(true, cx);
416 pane.display_nav_history_buttons(None);
417 pane.set_should_display_tab_bar(|_| true);
418 pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
419 let focus_handle = pane.focus_handle(cx);
420 let left_children = IconButton::new("history", IconName::HistoryRerun)
421 .icon_size(IconSize::Small)
422 .on_click(cx.listener({
423 let focus_handle = focus_handle.clone();
424 move |_, _, cx| {
425 focus_handle.focus(cx);
426 cx.dispatch_action(DeployHistory.boxed_clone())
427 }
428 }))
429 .tooltip({
430 let focus_handle = focus_handle.clone();
431 move |cx| {
432 Tooltip::for_action_in(
433 "Open History",
434 &DeployHistory,
435 &focus_handle,
436 cx,
437 )
438 }
439 })
440 .selected(
441 pane.active_item()
442 .map_or(false, |item| item.downcast::<ContextHistory>().is_some()),
443 );
444 let _pane = cx.view().clone();
445 let right_children = h_flex()
446 .gap(Spacing::Small.rems(cx))
447 .child(
448 IconButton::new("new-context", IconName::Plus)
449 .on_click(
450 cx.listener(|_, _, cx| {
451 cx.dispatch_action(NewContext.boxed_clone())
452 }),
453 )
454 .tooltip(move |cx| {
455 Tooltip::for_action_in(
456 "New Context",
457 &NewContext,
458 &focus_handle,
459 cx,
460 )
461 }),
462 )
463 .child(
464 PopoverMenu::new("assistant-panel-popover-menu")
465 .trigger(
466 IconButton::new("menu", IconName::Menu).icon_size(IconSize::Small),
467 )
468 .menu(move |cx| {
469 let zoom_label = if _pane.read(cx).is_zoomed() {
470 "Zoom Out"
471 } else {
472 "Zoom In"
473 };
474 let focus_handle = _pane.focus_handle(cx);
475 Some(ContextMenu::build(cx, move |menu, _| {
476 menu.context(focus_handle.clone())
477 .action("New Context", Box::new(NewContext))
478 .action("History", Box::new(DeployHistory))
479 .action("Prompt Library", Box::new(DeployPromptLibrary))
480 .action("Configure", Box::new(ShowConfiguration))
481 .action(zoom_label, Box::new(ToggleZoom))
482 }))
483 }),
484 )
485 .into_any_element()
486 .into();
487
488 (Some(left_children.into_any_element()), right_children)
489 });
490 pane.toolbar().update(cx, |toolbar, cx| {
491 toolbar.add_item(context_editor_toolbar.clone(), cx);
492 toolbar.add_item(cx.new_view(BufferSearchBar::new), cx)
493 });
494 pane
495 });
496
497 let subscriptions = vec![
498 cx.observe(&pane, |_, _, cx| cx.notify()),
499 cx.subscribe(&pane, Self::handle_pane_event),
500 cx.subscribe(&context_editor_toolbar, Self::handle_toolbar_event),
501 cx.subscribe(&model_summary_editor, Self::handle_summary_editor_event),
502 cx.subscribe(&context_store, Self::handle_context_store_event),
503 cx.subscribe(
504 &LanguageModelRegistry::global(cx),
505 |this, _, event: &language_model::Event, cx| match event {
506 language_model::Event::ActiveModelChanged => {
507 this.completion_provider_changed(cx);
508 }
509 language_model::Event::ProviderStateChanged => {
510 this.ensure_authenticated(cx);
511 cx.notify()
512 }
513 language_model::Event::AddedProvider(_)
514 | language_model::Event::RemovedProvider(_) => {
515 this.ensure_authenticated(cx);
516 }
517 },
518 ),
519 ];
520
521 let watch_client_status = Self::watch_client_status(workspace.client().clone(), cx);
522
523 let mut this = Self {
524 pane,
525 workspace: workspace.weak_handle(),
526 width: None,
527 height: None,
528 project: workspace.project().clone(),
529 context_store,
530 languages: workspace.app_state().languages.clone(),
531 fs: workspace.app_state().fs.clone(),
532 subscriptions,
533 model_selector_menu_handle,
534 model_summary_editor,
535 authenticate_provider_task: None,
536 configuration_subscription: None,
537 client_status: None,
538 watch_client_status: Some(watch_client_status),
539 show_zed_ai_notice: false,
540 };
541 this.new_context(cx);
542 this
543 }
544
545 fn watch_client_status(client: Arc<Client>, cx: &mut ViewContext<Self>) -> Task<()> {
546 let mut status_rx = client.status();
547
548 cx.spawn(|this, mut cx| async move {
549 while let Some(status) = status_rx.next().await {
550 this.update(&mut cx, |this, cx| {
551 if this.client_status.is_none()
552 || this
553 .client_status
554 .map_or(false, |old_status| old_status != status)
555 {
556 this.update_zed_ai_notice_visibility(status, cx);
557 }
558 this.client_status = Some(status);
559 })
560 .log_err();
561 }
562 this.update(&mut cx, |this, _cx| this.watch_client_status = None)
563 .log_err();
564 })
565 }
566
567 fn handle_pane_event(
568 &mut self,
569 pane: View<Pane>,
570 event: &pane::Event,
571 cx: &mut ViewContext<Self>,
572 ) {
573 let update_model_summary = match event {
574 pane::Event::Remove { .. } => {
575 cx.emit(PanelEvent::Close);
576 false
577 }
578 pane::Event::ZoomIn => {
579 cx.emit(PanelEvent::ZoomIn);
580 false
581 }
582 pane::Event::ZoomOut => {
583 cx.emit(PanelEvent::ZoomOut);
584 false
585 }
586
587 pane::Event::AddItem { item } => {
588 self.workspace
589 .update(cx, |workspace, cx| {
590 item.added_to_pane(workspace, self.pane.clone(), cx)
591 })
592 .ok();
593 true
594 }
595
596 pane::Event::ActivateItem { local } => {
597 if *local {
598 self.workspace
599 .update(cx, |workspace, cx| {
600 workspace.unfollow_in_pane(&pane, cx);
601 })
602 .ok();
603 }
604 cx.emit(AssistantPanelEvent::ContextEdited);
605 true
606 }
607 pane::Event::RemovedItem { .. } => {
608 let has_configuration_view = self
609 .pane
610 .read(cx)
611 .items_of_type::<ConfigurationView>()
612 .next()
613 .is_some();
614
615 if !has_configuration_view {
616 self.configuration_subscription = None;
617 }
618
619 cx.emit(AssistantPanelEvent::ContextEdited);
620 true
621 }
622
623 _ => false,
624 };
625
626 if update_model_summary {
627 if let Some(editor) = self.active_context_editor(cx) {
628 self.show_updated_summary(&editor, cx)
629 }
630 }
631 }
632
633 fn handle_summary_editor_event(
634 &mut self,
635 model_summary_editor: View<Editor>,
636 event: &EditorEvent,
637 cx: &mut ViewContext<Self>,
638 ) {
639 if matches!(event, EditorEvent::Edited { .. }) {
640 if let Some(context_editor) = self.active_context_editor(cx) {
641 let new_summary = model_summary_editor.read(cx).text(cx);
642 context_editor.update(cx, |context_editor, cx| {
643 context_editor.context.update(cx, |context, cx| {
644 if context.summary().is_none()
645 && (new_summary == DEFAULT_TAB_TITLE || new_summary.trim().is_empty())
646 {
647 return;
648 }
649 context.custom_summary(new_summary, cx)
650 });
651 });
652 }
653 }
654 }
655
656 fn update_zed_ai_notice_visibility(
657 &mut self,
658 client_status: Status,
659 cx: &mut ViewContext<Self>,
660 ) {
661 let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
662
663 // If we're signed out and don't have a provider configured, or we're signed-out AND Zed.dev is
664 // the provider, we want to show a nudge to sign in.
665 let show_zed_ai_notice = client_status.is_signed_out()
666 && active_provider.map_or(true, |provider| provider.id().0 == PROVIDER_ID);
667
668 self.show_zed_ai_notice = show_zed_ai_notice;
669 cx.notify();
670 }
671
672 fn handle_toolbar_event(
673 &mut self,
674 _: View<ContextEditorToolbarItem>,
675 _: &ContextEditorToolbarItemEvent,
676 cx: &mut ViewContext<Self>,
677 ) {
678 if let Some(context_editor) = self.active_context_editor(cx) {
679 context_editor.update(cx, |context_editor, cx| {
680 context_editor.context.update(cx, |context, cx| {
681 context.summarize(true, cx);
682 })
683 })
684 }
685 }
686
687 fn handle_context_store_event(
688 &mut self,
689 _context_store: Model<ContextStore>,
690 event: &ContextStoreEvent,
691 cx: &mut ViewContext<Self>,
692 ) {
693 let ContextStoreEvent::ContextCreated(context_id) = event;
694 let Some(context) = self
695 .context_store
696 .read(cx)
697 .loaded_context_for_id(&context_id, cx)
698 else {
699 log::error!("no context found with ID: {}", context_id.to_proto());
700 return;
701 };
702 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
703 .log_err()
704 .flatten();
705
706 let assistant_panel = cx.view().downgrade();
707 let editor = cx.new_view(|cx| {
708 let mut editor = ContextEditor::for_context(
709 context,
710 self.fs.clone(),
711 self.workspace.clone(),
712 self.project.clone(),
713 lsp_adapter_delegate,
714 assistant_panel,
715 cx,
716 );
717 editor.insert_default_prompt(cx);
718 editor
719 });
720
721 self.show_context(editor.clone(), cx);
722 }
723
724 fn completion_provider_changed(&mut self, cx: &mut ViewContext<Self>) {
725 if let Some(editor) = self.active_context_editor(cx) {
726 editor.update(cx, |active_context, cx| {
727 active_context
728 .context
729 .update(cx, |context, cx| context.completion_provider_changed(cx))
730 })
731 }
732
733 let Some(new_provider_id) = LanguageModelRegistry::read_global(cx)
734 .active_provider()
735 .map(|p| p.id())
736 else {
737 return;
738 };
739
740 if self
741 .authenticate_provider_task
742 .as_ref()
743 .map_or(true, |(old_provider_id, _)| {
744 *old_provider_id != new_provider_id
745 })
746 {
747 self.authenticate_provider_task = None;
748 self.ensure_authenticated(cx);
749 }
750
751 if let Some(status) = self.client_status {
752 self.update_zed_ai_notice_visibility(status, cx);
753 }
754 }
755
756 fn ensure_authenticated(&mut self, cx: &mut ViewContext<Self>) {
757 if self.is_authenticated(cx) {
758 return;
759 }
760
761 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
762 return;
763 };
764
765 let load_credentials = self.authenticate(cx);
766
767 if self.authenticate_provider_task.is_none() {
768 self.authenticate_provider_task = Some((
769 provider.id(),
770 cx.spawn(|this, mut cx| async move {
771 if let Some(future) = load_credentials {
772 let _ = future.await;
773 }
774 this.update(&mut cx, |this, _cx| {
775 this.authenticate_provider_task = None;
776 })
777 .log_err();
778 }),
779 ));
780 }
781 }
782
783 pub fn inline_assist(
784 workspace: &mut Workspace,
785 action: &InlineAssist,
786 cx: &mut ViewContext<Workspace>,
787 ) {
788 let settings = AssistantSettings::get_global(cx);
789 if !settings.enabled {
790 return;
791 }
792
793 let Some(assistant_panel) = workspace.panel::<AssistantPanel>(cx) else {
794 return;
795 };
796
797 let Some(inline_assist_target) =
798 Self::resolve_inline_assist_target(workspace, &assistant_panel, cx)
799 else {
800 return;
801 };
802
803 let initial_prompt = action.prompt.clone();
804
805 if assistant_panel.update(cx, |assistant, cx| assistant.is_authenticated(cx)) {
806 match inline_assist_target {
807 InlineAssistTarget::Editor(active_editor, include_context) => {
808 InlineAssistant::update_global(cx, |assistant, cx| {
809 assistant.assist(
810 &active_editor,
811 Some(cx.view().downgrade()),
812 include_context.then_some(&assistant_panel),
813 initial_prompt,
814 cx,
815 )
816 })
817 }
818 InlineAssistTarget::Terminal(active_terminal) => {
819 TerminalInlineAssistant::update_global(cx, |assistant, cx| {
820 assistant.assist(
821 &active_terminal,
822 Some(cx.view().downgrade()),
823 Some(&assistant_panel),
824 initial_prompt,
825 cx,
826 )
827 })
828 }
829 }
830 } else {
831 let assistant_panel = assistant_panel.downgrade();
832 cx.spawn(|workspace, mut cx| async move {
833 let Some(task) =
834 assistant_panel.update(&mut cx, |assistant, cx| assistant.authenticate(cx))?
835 else {
836 let answer = cx
837 .prompt(
838 gpui::PromptLevel::Warning,
839 "No language model provider configured",
840 None,
841 &["Configure", "Cancel"],
842 )
843 .await
844 .ok();
845 if let Some(answer) = answer {
846 if answer == 0 {
847 cx.update(|cx| cx.dispatch_action(Box::new(ShowConfiguration)))
848 .ok();
849 }
850 }
851 return Ok(());
852 };
853 task.await?;
854 if assistant_panel.update(&mut cx, |panel, cx| panel.is_authenticated(cx))? {
855 cx.update(|cx| match inline_assist_target {
856 InlineAssistTarget::Editor(active_editor, include_context) => {
857 let assistant_panel = if include_context {
858 assistant_panel.upgrade()
859 } else {
860 None
861 };
862 InlineAssistant::update_global(cx, |assistant, cx| {
863 assistant.assist(
864 &active_editor,
865 Some(workspace),
866 assistant_panel.as_ref(),
867 initial_prompt,
868 cx,
869 )
870 })
871 }
872 InlineAssistTarget::Terminal(active_terminal) => {
873 TerminalInlineAssistant::update_global(cx, |assistant, cx| {
874 assistant.assist(
875 &active_terminal,
876 Some(workspace),
877 assistant_panel.upgrade().as_ref(),
878 initial_prompt,
879 cx,
880 )
881 })
882 }
883 })?
884 } else {
885 workspace.update(&mut cx, |workspace, cx| {
886 workspace.focus_panel::<AssistantPanel>(cx)
887 })?;
888 }
889
890 anyhow::Ok(())
891 })
892 .detach_and_log_err(cx)
893 }
894 }
895
896 fn resolve_inline_assist_target(
897 workspace: &mut Workspace,
898 assistant_panel: &View<AssistantPanel>,
899 cx: &mut WindowContext,
900 ) -> Option<InlineAssistTarget> {
901 if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
902 if terminal_panel
903 .read(cx)
904 .focus_handle(cx)
905 .contains_focused(cx)
906 {
907 if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
908 pane.read(cx)
909 .active_item()
910 .and_then(|t| t.downcast::<TerminalView>())
911 }) {
912 return Some(InlineAssistTarget::Terminal(terminal_view));
913 }
914 }
915 }
916 let context_editor =
917 assistant_panel
918 .read(cx)
919 .active_context_editor(cx)
920 .and_then(|editor| {
921 let editor = &editor.read(cx).editor;
922 if editor.read(cx).is_focused(cx) {
923 Some(editor.clone())
924 } else {
925 None
926 }
927 });
928
929 if let Some(context_editor) = context_editor {
930 Some(InlineAssistTarget::Editor(context_editor, false))
931 } else if let Some(workspace_editor) = workspace
932 .active_item(cx)
933 .and_then(|item| item.act_as::<Editor>(cx))
934 {
935 Some(InlineAssistTarget::Editor(workspace_editor, true))
936 } else if let Some(terminal_view) = workspace
937 .active_item(cx)
938 .and_then(|item| item.act_as::<TerminalView>(cx))
939 {
940 Some(InlineAssistTarget::Terminal(terminal_view))
941 } else {
942 None
943 }
944 }
945
946 pub fn create_new_context(
947 workspace: &mut Workspace,
948 _: &NewContext,
949 cx: &mut ViewContext<Workspace>,
950 ) {
951 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
952 let did_create_context = panel
953 .update(cx, |panel, cx| {
954 panel.new_context(cx)?;
955
956 Some(())
957 })
958 .is_some();
959 if did_create_context {
960 ContextEditor::quote_selection(workspace, &Default::default(), cx);
961 }
962 }
963 }
964
965 fn new_context(&mut self, cx: &mut ViewContext<Self>) -> Option<View<ContextEditor>> {
966 let project = self.project.read(cx);
967 if project.is_via_collab() {
968 let task = self
969 .context_store
970 .update(cx, |store, cx| store.create_remote_context(cx));
971
972 cx.spawn(|this, mut cx| async move {
973 let context = task.await?;
974
975 this.update(&mut cx, |this, cx| {
976 let workspace = this.workspace.clone();
977 let project = this.project.clone();
978 let lsp_adapter_delegate =
979 make_lsp_adapter_delegate(&project, cx).log_err().flatten();
980
981 let fs = this.fs.clone();
982 let project = this.project.clone();
983 let weak_assistant_panel = cx.view().downgrade();
984
985 let editor = cx.new_view(|cx| {
986 ContextEditor::for_context(
987 context,
988 fs,
989 workspace,
990 project,
991 lsp_adapter_delegate,
992 weak_assistant_panel,
993 cx,
994 )
995 });
996
997 this.show_context(editor, cx);
998
999 anyhow::Ok(())
1000 })??;
1001
1002 anyhow::Ok(())
1003 })
1004 .detach_and_log_err(cx);
1005
1006 None
1007 } else {
1008 let context = self.context_store.update(cx, |store, cx| store.create(cx));
1009 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1010 .log_err()
1011 .flatten();
1012
1013 let assistant_panel = cx.view().downgrade();
1014 let editor = cx.new_view(|cx| {
1015 let mut editor = ContextEditor::for_context(
1016 context,
1017 self.fs.clone(),
1018 self.workspace.clone(),
1019 self.project.clone(),
1020 lsp_adapter_delegate,
1021 assistant_panel,
1022 cx,
1023 );
1024 editor.insert_default_prompt(cx);
1025 editor
1026 });
1027
1028 self.show_context(editor.clone(), cx);
1029 let workspace = self.workspace.clone();
1030 cx.spawn(move |_, mut cx| async move {
1031 workspace
1032 .update(&mut cx, |workspace, cx| {
1033 workspace.focus_panel::<AssistantPanel>(cx);
1034 })
1035 .ok();
1036 })
1037 .detach();
1038 Some(editor)
1039 }
1040 }
1041
1042 fn show_context(&mut self, context_editor: View<ContextEditor>, cx: &mut ViewContext<Self>) {
1043 let focus = self.focus_handle(cx).contains_focused(cx);
1044 let prev_len = self.pane.read(cx).items_len();
1045 self.pane.update(cx, |pane, cx| {
1046 pane.add_item(Box::new(context_editor.clone()), focus, focus, None, cx)
1047 });
1048
1049 if prev_len != self.pane.read(cx).items_len() {
1050 self.subscriptions
1051 .push(cx.subscribe(&context_editor, Self::handle_context_editor_event));
1052 }
1053
1054 self.show_updated_summary(&context_editor, cx);
1055
1056 cx.emit(AssistantPanelEvent::ContextEdited);
1057 cx.notify();
1058 }
1059
1060 fn show_updated_summary(
1061 &self,
1062 context_editor: &View<ContextEditor>,
1063 cx: &mut ViewContext<Self>,
1064 ) {
1065 context_editor.update(cx, |context_editor, cx| {
1066 let new_summary = context_editor.title(cx).to_string();
1067 self.model_summary_editor.update(cx, |summary_editor, cx| {
1068 if summary_editor.text(cx) != new_summary {
1069 summary_editor.set_text(new_summary, cx);
1070 }
1071 });
1072 });
1073 }
1074
1075 fn handle_context_editor_event(
1076 &mut self,
1077 context_editor: View<ContextEditor>,
1078 event: &EditorEvent,
1079 cx: &mut ViewContext<Self>,
1080 ) {
1081 match event {
1082 EditorEvent::TitleChanged => {
1083 self.show_updated_summary(&context_editor, cx);
1084 cx.notify()
1085 }
1086 EditorEvent::Edited { .. } => cx.emit(AssistantPanelEvent::ContextEdited),
1087 _ => {}
1088 }
1089 }
1090
1091 fn show_configuration(
1092 workspace: &mut Workspace,
1093 _: &ShowConfiguration,
1094 cx: &mut ViewContext<Workspace>,
1095 ) {
1096 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
1097 return;
1098 };
1099
1100 if !panel.focus_handle(cx).contains_focused(cx) {
1101 workspace.toggle_panel_focus::<AssistantPanel>(cx);
1102 }
1103
1104 panel.update(cx, |this, cx| {
1105 this.show_configuration_tab(cx);
1106 })
1107 }
1108
1109 fn show_configuration_tab(&mut self, cx: &mut ViewContext<Self>) {
1110 let configuration_item_ix = self
1111 .pane
1112 .read(cx)
1113 .items()
1114 .position(|item| item.downcast::<ConfigurationView>().is_some());
1115
1116 if let Some(configuration_item_ix) = configuration_item_ix {
1117 self.pane.update(cx, |pane, cx| {
1118 pane.activate_item(configuration_item_ix, true, true, cx);
1119 });
1120 } else {
1121 let configuration = cx.new_view(ConfigurationView::new);
1122 self.configuration_subscription = Some(cx.subscribe(
1123 &configuration,
1124 |this, _, event: &ConfigurationViewEvent, cx| match event {
1125 ConfigurationViewEvent::NewProviderContextEditor(provider) => {
1126 if LanguageModelRegistry::read_global(cx)
1127 .active_provider()
1128 .map_or(true, |p| p.id() != provider.id())
1129 {
1130 if let Some(model) = provider.provided_models(cx).first().cloned() {
1131 update_settings_file::<AssistantSettings>(
1132 this.fs.clone(),
1133 cx,
1134 move |settings, _| settings.set_model(model),
1135 );
1136 }
1137 }
1138
1139 this.new_context(cx);
1140 }
1141 },
1142 ));
1143 self.pane.update(cx, |pane, cx| {
1144 pane.add_item(Box::new(configuration), true, true, None, cx);
1145 });
1146 }
1147 }
1148
1149 fn deploy_history(&mut self, _: &DeployHistory, cx: &mut ViewContext<Self>) {
1150 let history_item_ix = self
1151 .pane
1152 .read(cx)
1153 .items()
1154 .position(|item| item.downcast::<ContextHistory>().is_some());
1155
1156 if let Some(history_item_ix) = history_item_ix {
1157 self.pane.update(cx, |pane, cx| {
1158 pane.activate_item(history_item_ix, true, true, cx);
1159 });
1160 } else {
1161 let assistant_panel = cx.view().downgrade();
1162 let history = cx.new_view(|cx| {
1163 ContextHistory::new(
1164 self.project.clone(),
1165 self.context_store.clone(),
1166 assistant_panel,
1167 cx,
1168 )
1169 });
1170 self.pane.update(cx, |pane, cx| {
1171 pane.add_item(Box::new(history), true, true, None, cx);
1172 });
1173 }
1174 }
1175
1176 fn deploy_prompt_library(&mut self, _: &DeployPromptLibrary, cx: &mut ViewContext<Self>) {
1177 open_prompt_library(self.languages.clone(), cx).detach_and_log_err(cx);
1178 }
1179
1180 fn toggle_model_selector(&mut self, _: &ToggleModelSelector, cx: &mut ViewContext<Self>) {
1181 self.model_selector_menu_handle.toggle(cx);
1182 }
1183
1184 fn active_context_editor(&self, cx: &AppContext) -> Option<View<ContextEditor>> {
1185 self.pane
1186 .read(cx)
1187 .active_item()?
1188 .downcast::<ContextEditor>()
1189 }
1190
1191 pub fn active_context(&self, cx: &AppContext) -> Option<Model<Context>> {
1192 Some(self.active_context_editor(cx)?.read(cx).context.clone())
1193 }
1194
1195 fn open_saved_context(
1196 &mut self,
1197 path: PathBuf,
1198 cx: &mut ViewContext<Self>,
1199 ) -> Task<Result<()>> {
1200 let existing_context = self.pane.read(cx).items().find_map(|item| {
1201 item.downcast::<ContextEditor>()
1202 .filter(|editor| editor.read(cx).context.read(cx).path() == Some(&path))
1203 });
1204 if let Some(existing_context) = existing_context {
1205 return cx.spawn(|this, mut cx| async move {
1206 this.update(&mut cx, |this, cx| this.show_context(existing_context, cx))
1207 });
1208 }
1209
1210 let context = self
1211 .context_store
1212 .update(cx, |store, cx| store.open_local_context(path.clone(), cx));
1213 let fs = self.fs.clone();
1214 let project = self.project.clone();
1215 let workspace = self.workspace.clone();
1216
1217 let lsp_adapter_delegate = make_lsp_adapter_delegate(&project, cx).log_err().flatten();
1218
1219 cx.spawn(|this, mut cx| async move {
1220 let context = context.await?;
1221 let assistant_panel = this.clone();
1222 this.update(&mut cx, |this, cx| {
1223 let editor = cx.new_view(|cx| {
1224 ContextEditor::for_context(
1225 context,
1226 fs,
1227 workspace,
1228 project,
1229 lsp_adapter_delegate,
1230 assistant_panel,
1231 cx,
1232 )
1233 });
1234 this.show_context(editor, cx);
1235 anyhow::Ok(())
1236 })??;
1237 Ok(())
1238 })
1239 }
1240
1241 fn open_remote_context(
1242 &mut self,
1243 id: ContextId,
1244 cx: &mut ViewContext<Self>,
1245 ) -> Task<Result<View<ContextEditor>>> {
1246 let existing_context = self.pane.read(cx).items().find_map(|item| {
1247 item.downcast::<ContextEditor>()
1248 .filter(|editor| *editor.read(cx).context.read(cx).id() == id)
1249 });
1250 if let Some(existing_context) = existing_context {
1251 return cx.spawn(|this, mut cx| async move {
1252 this.update(&mut cx, |this, cx| {
1253 this.show_context(existing_context.clone(), cx)
1254 })?;
1255 Ok(existing_context)
1256 });
1257 }
1258
1259 let context = self
1260 .context_store
1261 .update(cx, |store, cx| store.open_remote_context(id, cx));
1262 let fs = self.fs.clone();
1263 let workspace = self.workspace.clone();
1264 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1265 .log_err()
1266 .flatten();
1267
1268 cx.spawn(|this, mut cx| async move {
1269 let context = context.await?;
1270 let assistant_panel = this.clone();
1271 this.update(&mut cx, |this, cx| {
1272 let editor = cx.new_view(|cx| {
1273 ContextEditor::for_context(
1274 context,
1275 fs,
1276 workspace,
1277 this.project.clone(),
1278 lsp_adapter_delegate,
1279 assistant_panel,
1280 cx,
1281 )
1282 });
1283 this.show_context(editor.clone(), cx);
1284 anyhow::Ok(editor)
1285 })?
1286 })
1287 }
1288
1289 fn is_authenticated(&mut self, cx: &mut ViewContext<Self>) -> bool {
1290 LanguageModelRegistry::read_global(cx)
1291 .active_provider()
1292 .map_or(false, |provider| provider.is_authenticated(cx))
1293 }
1294
1295 fn authenticate(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1296 LanguageModelRegistry::read_global(cx)
1297 .active_provider()
1298 .map_or(None, |provider| Some(provider.authenticate(cx)))
1299 }
1300}
1301
1302impl Render for AssistantPanel {
1303 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1304 let mut registrar = DivRegistrar::new(
1305 |panel, cx| {
1306 panel
1307 .pane
1308 .read(cx)
1309 .toolbar()
1310 .read(cx)
1311 .item_of_type::<BufferSearchBar>()
1312 },
1313 cx,
1314 );
1315 BufferSearchBar::register(&mut registrar);
1316 let registrar = registrar.into_div();
1317
1318 v_flex()
1319 .key_context("AssistantPanel")
1320 .size_full()
1321 .on_action(cx.listener(|this, _: &NewContext, cx| {
1322 this.new_context(cx);
1323 }))
1324 .on_action(
1325 cx.listener(|this, _: &ShowConfiguration, cx| this.show_configuration_tab(cx)),
1326 )
1327 .on_action(cx.listener(AssistantPanel::deploy_history))
1328 .on_action(cx.listener(AssistantPanel::deploy_prompt_library))
1329 .on_action(cx.listener(AssistantPanel::toggle_model_selector))
1330 .child(registrar.size_full().child(self.pane.clone()))
1331 .into_any_element()
1332 }
1333}
1334
1335impl Panel for AssistantPanel {
1336 fn persistent_name() -> &'static str {
1337 "AssistantPanel"
1338 }
1339
1340 fn position(&self, cx: &WindowContext) -> DockPosition {
1341 match AssistantSettings::get_global(cx).dock {
1342 AssistantDockPosition::Left => DockPosition::Left,
1343 AssistantDockPosition::Bottom => DockPosition::Bottom,
1344 AssistantDockPosition::Right => DockPosition::Right,
1345 }
1346 }
1347
1348 fn position_is_valid(&self, _: DockPosition) -> bool {
1349 true
1350 }
1351
1352 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1353 settings::update_settings_file::<AssistantSettings>(
1354 self.fs.clone(),
1355 cx,
1356 move |settings, _| {
1357 let dock = match position {
1358 DockPosition::Left => AssistantDockPosition::Left,
1359 DockPosition::Bottom => AssistantDockPosition::Bottom,
1360 DockPosition::Right => AssistantDockPosition::Right,
1361 };
1362 settings.set_dock(dock);
1363 },
1364 );
1365 }
1366
1367 fn size(&self, cx: &WindowContext) -> Pixels {
1368 let settings = AssistantSettings::get_global(cx);
1369 match self.position(cx) {
1370 DockPosition::Left | DockPosition::Right => {
1371 self.width.unwrap_or(settings.default_width)
1372 }
1373 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1374 }
1375 }
1376
1377 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1378 match self.position(cx) {
1379 DockPosition::Left | DockPosition::Right => self.width = size,
1380 DockPosition::Bottom => self.height = size,
1381 }
1382 cx.notify();
1383 }
1384
1385 fn is_zoomed(&self, cx: &WindowContext) -> bool {
1386 self.pane.read(cx).is_zoomed()
1387 }
1388
1389 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1390 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
1391 }
1392
1393 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1394 if active {
1395 if self.pane.read(cx).items_len() == 0 {
1396 self.new_context(cx);
1397 }
1398
1399 self.ensure_authenticated(cx);
1400 }
1401 }
1402
1403 fn pane(&self) -> Option<View<Pane>> {
1404 Some(self.pane.clone())
1405 }
1406
1407 fn remote_id() -> Option<proto::PanelId> {
1408 Some(proto::PanelId::AssistantPanel)
1409 }
1410
1411 fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1412 let settings = AssistantSettings::get_global(cx);
1413 if !settings.enabled || !settings.button {
1414 return None;
1415 }
1416
1417 Some(IconName::ZedAssistant)
1418 }
1419
1420 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1421 Some("Assistant Panel")
1422 }
1423
1424 fn toggle_action(&self) -> Box<dyn Action> {
1425 Box::new(ToggleFocus)
1426 }
1427}
1428
1429impl EventEmitter<PanelEvent> for AssistantPanel {}
1430impl EventEmitter<AssistantPanelEvent> for AssistantPanel {}
1431
1432impl FocusableView for AssistantPanel {
1433 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1434 self.pane.focus_handle(cx)
1435 }
1436}
1437
1438pub enum ContextEditorEvent {
1439 Edited,
1440 TabContentChanged,
1441}
1442
1443#[derive(Copy, Clone, Debug, PartialEq)]
1444struct ScrollPosition {
1445 offset_before_cursor: gpui::Point<f32>,
1446 cursor: Anchor,
1447}
1448
1449struct PatchViewState {
1450 footer_block_id: CustomBlockId,
1451 crease_id: CreaseId,
1452 editor: Option<PatchEditorState>,
1453 update_task: Option<Task<()>>,
1454}
1455
1456struct PatchEditorState {
1457 editor: WeakView<ProposedChangesEditor>,
1458 opened_patch: AssistantPatch,
1459}
1460
1461type MessageHeader = MessageMetadata;
1462
1463#[derive(Clone)]
1464enum AssistError {
1465 PaymentRequired,
1466 MaxMonthlySpendReached,
1467 Message(SharedString),
1468}
1469
1470pub struct ContextEditor {
1471 context: Model<Context>,
1472 fs: Arc<dyn Fs>,
1473 workspace: WeakView<Workspace>,
1474 project: Model<Project>,
1475 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1476 editor: View<Editor>,
1477 blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
1478 image_blocks: HashSet<CustomBlockId>,
1479 scroll_position: Option<ScrollPosition>,
1480 remote_id: Option<workspace::ViewId>,
1481 pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
1482 pending_slash_command_blocks: HashMap<Range<language::Anchor>, CustomBlockId>,
1483 pending_tool_use_creases: HashMap<Range<language::Anchor>, CreaseId>,
1484 _subscriptions: Vec<Subscription>,
1485 patches: HashMap<Range<language::Anchor>, PatchViewState>,
1486 active_patch: Option<Range<language::Anchor>>,
1487 assistant_panel: WeakView<AssistantPanel>,
1488 last_error: Option<AssistError>,
1489 show_accept_terms: bool,
1490 pub(crate) slash_menu_handle:
1491 PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
1492 // dragged_file_worktrees is used to keep references to worktrees that were added
1493 // when the user drag/dropped an external file onto the context editor. Since
1494 // the worktree is not part of the project panel, it would be dropped as soon as
1495 // the file is opened. In order to keep the worktree alive for the duration of the
1496 // context editor, we keep a reference here.
1497 dragged_file_worktrees: Vec<Model<Worktree>>,
1498}
1499
1500const DEFAULT_TAB_TITLE: &str = "New Context";
1501const MAX_TAB_TITLE_LEN: usize = 16;
1502
1503impl ContextEditor {
1504 fn for_context(
1505 context: Model<Context>,
1506 fs: Arc<dyn Fs>,
1507 workspace: WeakView<Workspace>,
1508 project: Model<Project>,
1509 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1510 assistant_panel: WeakView<AssistantPanel>,
1511 cx: &mut ViewContext<Self>,
1512 ) -> Self {
1513 let completion_provider = SlashCommandCompletionProvider::new(
1514 Some(cx.view().downgrade()),
1515 Some(workspace.clone()),
1516 );
1517
1518 let editor = cx.new_view(|cx| {
1519 let mut editor = Editor::for_buffer(context.read(cx).buffer().clone(), None, cx);
1520 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
1521 editor.set_show_line_numbers(false, cx);
1522 editor.set_show_git_diff_gutter(false, cx);
1523 editor.set_show_code_actions(false, cx);
1524 editor.set_show_runnables(false, cx);
1525 editor.set_show_wrap_guides(false, cx);
1526 editor.set_show_indent_guides(false, cx);
1527 editor.set_completion_provider(Some(Box::new(completion_provider)));
1528 editor.set_collaboration_hub(Box::new(project.clone()));
1529 editor
1530 });
1531
1532 let _subscriptions = vec![
1533 cx.observe(&context, |_, _, cx| cx.notify()),
1534 cx.subscribe(&context, Self::handle_context_event),
1535 cx.subscribe(&editor, Self::handle_editor_event),
1536 cx.subscribe(&editor, Self::handle_editor_search_event),
1537 ];
1538
1539 let sections = context.read(cx).slash_command_output_sections().to_vec();
1540 let patch_ranges = context.read(cx).patch_ranges().collect::<Vec<_>>();
1541 let mut this = Self {
1542 context,
1543 editor,
1544 lsp_adapter_delegate,
1545 blocks: Default::default(),
1546 image_blocks: Default::default(),
1547 scroll_position: None,
1548 remote_id: None,
1549 fs,
1550 workspace,
1551 project,
1552 pending_slash_command_creases: HashMap::default(),
1553 pending_slash_command_blocks: HashMap::default(),
1554 pending_tool_use_creases: HashMap::default(),
1555 _subscriptions,
1556 patches: HashMap::default(),
1557 active_patch: None,
1558 assistant_panel,
1559 last_error: None,
1560 show_accept_terms: false,
1561 slash_menu_handle: Default::default(),
1562 dragged_file_worktrees: Vec::new(),
1563 };
1564 this.update_message_headers(cx);
1565 this.update_image_blocks(cx);
1566 this.insert_slash_command_output_sections(sections, false, cx);
1567 this.patches_updated(&Vec::new(), &patch_ranges, cx);
1568 this
1569 }
1570
1571 fn insert_default_prompt(&mut self, cx: &mut ViewContext<Self>) {
1572 let command_name = DefaultSlashCommand.name();
1573 self.editor.update(cx, |editor, cx| {
1574 editor.insert(&format!("/{command_name}\n\n"), cx)
1575 });
1576 let command = self.context.update(cx, |context, cx| {
1577 context.reparse(cx);
1578 context.pending_slash_commands()[0].clone()
1579 });
1580 self.run_command(
1581 command.source_range,
1582 &command.name,
1583 &command.arguments,
1584 false,
1585 false,
1586 self.workspace.clone(),
1587 cx,
1588 );
1589 }
1590
1591 fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
1592 self.send_to_model(RequestType::Chat, cx);
1593 }
1594
1595 fn edit(&mut self, _: &Edit, cx: &mut ViewContext<Self>) {
1596 self.send_to_model(RequestType::SuggestEdits, cx);
1597 }
1598
1599 fn focus_active_patch(&mut self, cx: &mut ViewContext<Self>) -> bool {
1600 if let Some((_range, patch)) = self.active_patch() {
1601 if let Some(editor) = patch
1602 .editor
1603 .as_ref()
1604 .and_then(|state| state.editor.upgrade())
1605 {
1606 cx.focus_view(&editor);
1607 return true;
1608 }
1609 }
1610
1611 false
1612 }
1613
1614 fn send_to_model(&mut self, request_type: RequestType, cx: &mut ViewContext<Self>) {
1615 let provider = LanguageModelRegistry::read_global(cx).active_provider();
1616 if provider
1617 .as_ref()
1618 .map_or(false, |provider| provider.must_accept_terms(cx))
1619 {
1620 self.show_accept_terms = true;
1621 cx.notify();
1622 return;
1623 }
1624
1625 if self.focus_active_patch(cx) {
1626 return;
1627 }
1628
1629 self.last_error = None;
1630
1631 if let Some(user_message) = self
1632 .context
1633 .update(cx, |context, cx| context.assist(request_type, cx))
1634 {
1635 let new_selection = {
1636 let cursor = user_message
1637 .start
1638 .to_offset(self.context.read(cx).buffer().read(cx));
1639 cursor..cursor
1640 };
1641 self.editor.update(cx, |editor, cx| {
1642 editor.change_selections(
1643 Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
1644 cx,
1645 |selections| selections.select_ranges([new_selection]),
1646 );
1647 });
1648 // Avoid scrolling to the new cursor position so the assistant's output is stable.
1649 cx.defer(|this, _| this.scroll_position = None);
1650 }
1651
1652 cx.notify();
1653 }
1654
1655 fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1656 self.last_error = None;
1657
1658 if self
1659 .context
1660 .update(cx, |context, cx| context.cancel_last_assist(cx))
1661 {
1662 return;
1663 }
1664
1665 cx.propagate();
1666 }
1667
1668 fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
1669 let cursors = self.cursors(cx);
1670 self.context.update(cx, |context, cx| {
1671 let messages = context
1672 .messages_for_offsets(cursors, cx)
1673 .into_iter()
1674 .map(|message| message.id)
1675 .collect();
1676 context.cycle_message_roles(messages, cx)
1677 });
1678 }
1679
1680 fn cursors(&self, cx: &mut WindowContext) -> Vec<usize> {
1681 let selections = self
1682 .editor
1683 .update(cx, |editor, cx| editor.selections.all::<usize>(cx));
1684 selections
1685 .into_iter()
1686 .map(|selection| selection.head())
1687 .collect()
1688 }
1689
1690 pub fn insert_command(&mut self, name: &str, cx: &mut ViewContext<Self>) {
1691 if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1692 self.editor.update(cx, |editor, cx| {
1693 editor.transact(cx, |editor, cx| {
1694 editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel());
1695 let snapshot = editor.buffer().read(cx).snapshot(cx);
1696 let newest_cursor = editor.selections.newest::<Point>(cx).head();
1697 if newest_cursor.column > 0
1698 || snapshot
1699 .chars_at(newest_cursor)
1700 .next()
1701 .map_or(false, |ch| ch != '\n')
1702 {
1703 editor.move_to_end_of_line(
1704 &MoveToEndOfLine {
1705 stop_at_soft_wraps: false,
1706 },
1707 cx,
1708 );
1709 editor.newline(&Newline, cx);
1710 }
1711
1712 editor.insert(&format!("/{name}"), cx);
1713 if command.accepts_arguments() {
1714 editor.insert(" ", cx);
1715 editor.show_completions(&ShowCompletions::default(), cx);
1716 }
1717 });
1718 });
1719 if !command.requires_argument() {
1720 self.confirm_command(&ConfirmCommand, cx);
1721 }
1722 }
1723 }
1724
1725 pub fn confirm_command(&mut self, _: &ConfirmCommand, cx: &mut ViewContext<Self>) {
1726 if self.editor.read(cx).has_active_completions_menu() {
1727 return;
1728 }
1729
1730 let selections = self.editor.read(cx).selections.disjoint_anchors();
1731 let mut commands_by_range = HashMap::default();
1732 let workspace = self.workspace.clone();
1733 self.context.update(cx, |context, cx| {
1734 context.reparse(cx);
1735 for selection in selections.iter() {
1736 if let Some(command) =
1737 context.pending_command_for_position(selection.head().text_anchor, cx)
1738 {
1739 commands_by_range
1740 .entry(command.source_range.clone())
1741 .or_insert_with(|| command.clone());
1742 }
1743 }
1744 });
1745
1746 if commands_by_range.is_empty() {
1747 cx.propagate();
1748 } else {
1749 for command in commands_by_range.into_values() {
1750 self.run_command(
1751 command.source_range,
1752 &command.name,
1753 &command.arguments,
1754 true,
1755 false,
1756 workspace.clone(),
1757 cx,
1758 );
1759 }
1760 cx.stop_propagation();
1761 }
1762 }
1763
1764 #[allow(clippy::too_many_arguments)]
1765 pub fn run_command(
1766 &mut self,
1767 command_range: Range<language::Anchor>,
1768 name: &str,
1769 arguments: &[String],
1770 ensure_trailing_newline: bool,
1771 expand_result: bool,
1772 workspace: WeakView<Workspace>,
1773 cx: &mut ViewContext<Self>,
1774 ) {
1775 if let Some(command) = SlashCommandRegistry::global(cx).command(name) {
1776 let context = self.context.read(cx);
1777 let sections = context
1778 .slash_command_output_sections()
1779 .into_iter()
1780 .filter(|section| section.is_valid(context.buffer().read(cx)))
1781 .cloned()
1782 .collect::<Vec<_>>();
1783 let snapshot = context.buffer().read(cx).snapshot();
1784 let output = command.run(
1785 arguments,
1786 §ions,
1787 snapshot,
1788 workspace,
1789 self.lsp_adapter_delegate.clone(),
1790 cx,
1791 );
1792 self.context.update(cx, |context, cx| {
1793 context.insert_command_output(
1794 command_range,
1795 output,
1796 ensure_trailing_newline,
1797 expand_result,
1798 cx,
1799 )
1800 });
1801 }
1802 }
1803
1804 fn handle_context_event(
1805 &mut self,
1806 _: Model<Context>,
1807 event: &ContextEvent,
1808 cx: &mut ViewContext<Self>,
1809 ) {
1810 let context_editor = cx.view().downgrade();
1811
1812 match event {
1813 ContextEvent::MessagesEdited => {
1814 self.update_message_headers(cx);
1815 self.update_image_blocks(cx);
1816 self.context.update(cx, |context, cx| {
1817 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1818 });
1819 }
1820 ContextEvent::SummaryChanged => {
1821 cx.emit(EditorEvent::TitleChanged);
1822 self.context.update(cx, |context, cx| {
1823 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1824 });
1825 }
1826 ContextEvent::StreamedCompletion => {
1827 self.editor.update(cx, |editor, cx| {
1828 if let Some(scroll_position) = self.scroll_position {
1829 let snapshot = editor.snapshot(cx);
1830 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
1831 let scroll_top =
1832 cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
1833 editor.set_scroll_position(
1834 point(scroll_position.offset_before_cursor.x, scroll_top),
1835 cx,
1836 );
1837 }
1838
1839 let new_tool_uses = self
1840 .context
1841 .read(cx)
1842 .pending_tool_uses()
1843 .into_iter()
1844 .filter(|tool_use| {
1845 !self
1846 .pending_tool_use_creases
1847 .contains_key(&tool_use.source_range)
1848 })
1849 .cloned()
1850 .collect::<Vec<_>>();
1851
1852 let buffer = editor.buffer().read(cx).snapshot(cx);
1853 let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
1854 let excerpt_id = *excerpt_id;
1855
1856 let mut buffer_rows_to_fold = BTreeSet::new();
1857
1858 let creases = new_tool_uses
1859 .iter()
1860 .map(|tool_use| {
1861 let placeholder = FoldPlaceholder {
1862 render: render_fold_icon_button(
1863 cx.view().downgrade(),
1864 IconName::PocketKnife,
1865 tool_use.name.clone().into(),
1866 ),
1867 constrain_width: false,
1868 merge_adjacent: false,
1869 };
1870 let render_trailer =
1871 move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
1872
1873 let start = buffer
1874 .anchor_in_excerpt(excerpt_id, tool_use.source_range.start)
1875 .unwrap();
1876 let end = buffer
1877 .anchor_in_excerpt(excerpt_id, tool_use.source_range.end)
1878 .unwrap();
1879
1880 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1881 buffer_rows_to_fold.insert(buffer_row);
1882
1883 self.context.update(cx, |context, cx| {
1884 context.insert_content(
1885 Content::ToolUse {
1886 range: tool_use.source_range.clone(),
1887 tool_use: LanguageModelToolUse {
1888 id: tool_use.id.to_string(),
1889 name: tool_use.name.clone(),
1890 input: tool_use.input.clone(),
1891 },
1892 },
1893 cx,
1894 );
1895 });
1896
1897 Crease::new(
1898 start..end,
1899 placeholder,
1900 fold_toggle("tool-use"),
1901 render_trailer,
1902 )
1903 })
1904 .collect::<Vec<_>>();
1905
1906 let crease_ids = editor.insert_creases(creases, cx);
1907
1908 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1909 editor.fold_at(&FoldAt { buffer_row }, cx);
1910 }
1911
1912 self.pending_tool_use_creases.extend(
1913 new_tool_uses
1914 .iter()
1915 .map(|tool_use| tool_use.source_range.clone())
1916 .zip(crease_ids),
1917 );
1918 });
1919 }
1920 ContextEvent::PatchesUpdated { removed, updated } => {
1921 self.patches_updated(removed, updated, cx);
1922 }
1923 ContextEvent::PendingSlashCommandsUpdated { removed, updated } => {
1924 self.editor.update(cx, |editor, cx| {
1925 let buffer = editor.buffer().read(cx).snapshot(cx);
1926 let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
1927 let excerpt_id = *excerpt_id;
1928
1929 editor.remove_creases(
1930 removed
1931 .iter()
1932 .filter_map(|range| self.pending_slash_command_creases.remove(range)),
1933 cx,
1934 );
1935
1936 editor.remove_blocks(
1937 HashSet::from_iter(
1938 removed.iter().filter_map(|range| {
1939 self.pending_slash_command_blocks.remove(range)
1940 }),
1941 ),
1942 None,
1943 cx,
1944 );
1945
1946 let crease_ids = editor.insert_creases(
1947 updated.iter().map(|command| {
1948 let workspace = self.workspace.clone();
1949 let confirm_command = Arc::new({
1950 let context_editor = context_editor.clone();
1951 let command = command.clone();
1952 move |cx: &mut WindowContext| {
1953 context_editor
1954 .update(cx, |context_editor, cx| {
1955 context_editor.run_command(
1956 command.source_range.clone(),
1957 &command.name,
1958 &command.arguments,
1959 false,
1960 false,
1961 workspace.clone(),
1962 cx,
1963 );
1964 })
1965 .ok();
1966 }
1967 });
1968 let placeholder = FoldPlaceholder {
1969 render: Arc::new(move |_, _, _| Empty.into_any()),
1970 constrain_width: false,
1971 merge_adjacent: false,
1972 };
1973 let render_toggle = {
1974 let confirm_command = confirm_command.clone();
1975 let command = command.clone();
1976 move |row, _, _, _cx: &mut WindowContext| {
1977 render_pending_slash_command_gutter_decoration(
1978 row,
1979 &command.status,
1980 confirm_command.clone(),
1981 )
1982 }
1983 };
1984 let render_trailer = {
1985 let command = command.clone();
1986 move |row, _unfold, cx: &mut WindowContext| {
1987 // TODO: In the future we should investigate how we can expose
1988 // this as a hook on the `SlashCommand` trait so that we don't
1989 // need to special-case it here.
1990 if command.name == DocsSlashCommand::NAME {
1991 return render_docs_slash_command_trailer(
1992 row,
1993 command.clone(),
1994 cx,
1995 );
1996 }
1997
1998 Empty.into_any()
1999 }
2000 };
2001
2002 let start = buffer
2003 .anchor_in_excerpt(excerpt_id, command.source_range.start)
2004 .unwrap();
2005 let end = buffer
2006 .anchor_in_excerpt(excerpt_id, command.source_range.end)
2007 .unwrap();
2008 Crease::new(start..end, placeholder, render_toggle, render_trailer)
2009 }),
2010 cx,
2011 );
2012
2013 let block_ids = editor.insert_blocks(
2014 updated
2015 .iter()
2016 .filter_map(|command| match &command.status {
2017 PendingSlashCommandStatus::Error(error) => {
2018 Some((command, error.clone()))
2019 }
2020 _ => None,
2021 })
2022 .map(|(command, error_message)| BlockProperties {
2023 style: BlockStyle::Fixed,
2024 height: 1,
2025 placement: BlockPlacement::Below(Anchor {
2026 buffer_id: Some(buffer_id),
2027 excerpt_id,
2028 text_anchor: command.source_range.start,
2029 }),
2030 render: slash_command_error_block_renderer(error_message),
2031 priority: 0,
2032 }),
2033 None,
2034 cx,
2035 );
2036
2037 self.pending_slash_command_creases.extend(
2038 updated
2039 .iter()
2040 .map(|command| command.source_range.clone())
2041 .zip(crease_ids),
2042 );
2043
2044 self.pending_slash_command_blocks.extend(
2045 updated
2046 .iter()
2047 .map(|command| command.source_range.clone())
2048 .zip(block_ids),
2049 );
2050 })
2051 }
2052 ContextEvent::SlashCommandFinished {
2053 output_range,
2054 sections,
2055 run_commands_in_output,
2056 expand_result,
2057 } => {
2058 self.insert_slash_command_output_sections(
2059 sections.iter().cloned(),
2060 *expand_result,
2061 cx,
2062 );
2063
2064 if *run_commands_in_output {
2065 let commands = self.context.update(cx, |context, cx| {
2066 context.reparse(cx);
2067 context
2068 .pending_commands_for_range(output_range.clone(), cx)
2069 .to_vec()
2070 });
2071
2072 for command in commands {
2073 self.run_command(
2074 command.source_range,
2075 &command.name,
2076 &command.arguments,
2077 false,
2078 false,
2079 self.workspace.clone(),
2080 cx,
2081 );
2082 }
2083 }
2084 }
2085 ContextEvent::UsePendingTools => {
2086 let pending_tool_uses = self
2087 .context
2088 .read(cx)
2089 .pending_tool_uses()
2090 .into_iter()
2091 .filter(|tool_use| tool_use.status.is_idle())
2092 .cloned()
2093 .collect::<Vec<_>>();
2094
2095 for tool_use in pending_tool_uses {
2096 let tool_registry = ToolRegistry::global(cx);
2097 if let Some(tool) = tool_registry.tool(&tool_use.name) {
2098 let task = tool.run(tool_use.input, self.workspace.clone(), cx);
2099
2100 self.context.update(cx, |context, cx| {
2101 context.insert_tool_output(tool_use.id.clone(), task, cx);
2102 });
2103 }
2104 }
2105 }
2106 ContextEvent::ToolFinished {
2107 tool_use_id,
2108 output_range,
2109 } => {
2110 self.editor.update(cx, |editor, cx| {
2111 let buffer = editor.buffer().read(cx).snapshot(cx);
2112 let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
2113 let excerpt_id = *excerpt_id;
2114
2115 let placeholder = FoldPlaceholder {
2116 render: render_fold_icon_button(
2117 cx.view().downgrade(),
2118 IconName::PocketKnife,
2119 format!("Tool Result: {tool_use_id}").into(),
2120 ),
2121 constrain_width: false,
2122 merge_adjacent: false,
2123 };
2124 let render_trailer =
2125 move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
2126
2127 let start = buffer
2128 .anchor_in_excerpt(excerpt_id, output_range.start)
2129 .unwrap();
2130 let end = buffer
2131 .anchor_in_excerpt(excerpt_id, output_range.end)
2132 .unwrap();
2133
2134 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2135
2136 let crease = Crease::new(
2137 start..end,
2138 placeholder,
2139 fold_toggle("tool-use"),
2140 render_trailer,
2141 );
2142
2143 editor.insert_creases([crease], cx);
2144 editor.fold_at(&FoldAt { buffer_row }, cx);
2145 });
2146 }
2147 ContextEvent::Operation(_) => {}
2148 ContextEvent::ShowAssistError(error_message) => {
2149 self.last_error = Some(AssistError::Message(error_message.clone()));
2150 }
2151 ContextEvent::ShowPaymentRequiredError => {
2152 self.last_error = Some(AssistError::PaymentRequired);
2153 }
2154 ContextEvent::ShowMaxMonthlySpendReachedError => {
2155 self.last_error = Some(AssistError::MaxMonthlySpendReached);
2156 }
2157 }
2158 }
2159
2160 fn patches_updated(
2161 &mut self,
2162 removed: &Vec<Range<text::Anchor>>,
2163 updated: &Vec<Range<text::Anchor>>,
2164 cx: &mut ViewContext<ContextEditor>,
2165 ) {
2166 let this = cx.view().downgrade();
2167 let mut removed_crease_ids = Vec::new();
2168 let mut removed_block_ids = HashSet::default();
2169 let mut editors_to_close = Vec::new();
2170 for range in removed {
2171 if let Some(state) = self.patches.remove(range) {
2172 editors_to_close.extend(state.editor.and_then(|state| state.editor.upgrade()));
2173 removed_block_ids.insert(state.footer_block_id);
2174 removed_crease_ids.push(state.crease_id);
2175 }
2176 }
2177
2178 self.editor.update(cx, |editor, cx| {
2179 let snapshot = editor.snapshot(cx);
2180 let multibuffer = &snapshot.buffer_snapshot;
2181 let (&excerpt_id, _, _) = multibuffer.as_singleton().unwrap();
2182
2183 let mut replaced_blocks = HashMap::default();
2184 for range in updated {
2185 let Some(patch) = self.context.read(cx).patch_for_range(&range, cx).cloned() else {
2186 continue;
2187 };
2188
2189 let path_count = patch.path_count();
2190 let patch_start = multibuffer
2191 .anchor_in_excerpt(excerpt_id, patch.range.start)
2192 .unwrap();
2193 let patch_end = multibuffer
2194 .anchor_in_excerpt(excerpt_id, patch.range.end)
2195 .unwrap();
2196 let render_block: RenderBlock = Box::new({
2197 let this = this.clone();
2198 let patch_range = range.clone();
2199 move |cx: &mut BlockContext<'_, '_>| {
2200 let max_width = cx.max_width;
2201 let gutter_width = cx.gutter_dimensions.full_width();
2202 let block_id = cx.block_id;
2203 this.update(&mut **cx, |this, cx| {
2204 this.render_patch_footer(
2205 patch_range.clone(),
2206 max_width,
2207 gutter_width,
2208 block_id,
2209 cx,
2210 )
2211 })
2212 .ok()
2213 .flatten()
2214 .unwrap_or_else(|| Empty.into_any())
2215 }
2216 });
2217
2218 let header_placeholder = FoldPlaceholder {
2219 render: {
2220 let this = this.clone();
2221 let patch_range = range.clone();
2222 Arc::new(move |fold_id, _range, cx| {
2223 this.update(cx, |this, cx| {
2224 this.render_patch_header(patch_range.clone(), fold_id, cx)
2225 })
2226 .ok()
2227 .flatten()
2228 .unwrap_or_else(|| Empty.into_any())
2229 })
2230 },
2231 constrain_width: false,
2232 merge_adjacent: false,
2233 };
2234
2235 let should_refold;
2236 if let Some(state) = self.patches.get_mut(&range) {
2237 replaced_blocks.insert(state.footer_block_id, render_block);
2238 if let Some(editor_state) = &state.editor {
2239 if editor_state.opened_patch != patch {
2240 state.update_task = Some({
2241 let this = this.clone();
2242 cx.spawn(|_, cx| async move {
2243 Self::update_patch_editor(this.clone(), patch, cx)
2244 .await
2245 .log_err();
2246 })
2247 });
2248 }
2249 }
2250
2251 should_refold =
2252 snapshot.intersects_fold(patch_start.to_offset(&snapshot.buffer_snapshot));
2253 } else {
2254 let block_ids = editor.insert_blocks(
2255 [BlockProperties {
2256 height: path_count as u32 + 1,
2257 style: BlockStyle::Flex,
2258 render: render_block,
2259 placement: BlockPlacement::Below(patch_start),
2260 priority: 0,
2261 }],
2262 None,
2263 cx,
2264 );
2265
2266 let new_crease_ids = editor.insert_creases(
2267 [Crease::new(
2268 patch_start..patch_end,
2269 header_placeholder.clone(),
2270 fold_toggle("patch-header"),
2271 |_, _, _| Empty.into_any_element(),
2272 )],
2273 cx,
2274 );
2275
2276 self.patches.insert(
2277 range.clone(),
2278 PatchViewState {
2279 footer_block_id: block_ids[0],
2280 crease_id: new_crease_ids[0],
2281 editor: None,
2282 update_task: None,
2283 },
2284 );
2285
2286 should_refold = true;
2287 }
2288
2289 if should_refold {
2290 editor.unfold_ranges([patch_start..patch_end], true, false, cx);
2291 editor.fold_ranges([(patch_start..patch_end, header_placeholder)], false, cx);
2292 }
2293 }
2294
2295 editor.remove_creases(removed_crease_ids, cx);
2296 editor.remove_blocks(removed_block_ids, None, cx);
2297 editor.replace_blocks(replaced_blocks, None, cx);
2298 });
2299
2300 for editor in editors_to_close {
2301 self.close_patch_editor(editor, cx);
2302 }
2303
2304 self.update_active_patch(cx);
2305 }
2306
2307 fn insert_slash_command_output_sections(
2308 &mut self,
2309 sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
2310 expand_result: bool,
2311 cx: &mut ViewContext<Self>,
2312 ) {
2313 self.editor.update(cx, |editor, cx| {
2314 let buffer = editor.buffer().read(cx).snapshot(cx);
2315 let excerpt_id = *buffer.as_singleton().unwrap().0;
2316 let mut buffer_rows_to_fold = BTreeSet::new();
2317 let mut creases = Vec::new();
2318 for section in sections {
2319 let start = buffer
2320 .anchor_in_excerpt(excerpt_id, section.range.start)
2321 .unwrap();
2322 let end = buffer
2323 .anchor_in_excerpt(excerpt_id, section.range.end)
2324 .unwrap();
2325 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2326 buffer_rows_to_fold.insert(buffer_row);
2327 creases.push(
2328 Crease::new(
2329 start..end,
2330 FoldPlaceholder {
2331 render: render_fold_icon_button(
2332 cx.view().downgrade(),
2333 section.icon,
2334 section.label.clone(),
2335 ),
2336 constrain_width: false,
2337 merge_adjacent: false,
2338 },
2339 render_slash_command_output_toggle,
2340 |_, _, _| Empty.into_any_element(),
2341 )
2342 .with_metadata(CreaseMetadata {
2343 icon: section.icon,
2344 label: section.label,
2345 }),
2346 );
2347 }
2348
2349 editor.insert_creases(creases, cx);
2350
2351 if expand_result {
2352 buffer_rows_to_fold.clear();
2353 }
2354 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2355 editor.fold_at(&FoldAt { buffer_row }, cx);
2356 }
2357 });
2358 }
2359
2360 fn handle_editor_event(
2361 &mut self,
2362 _: View<Editor>,
2363 event: &EditorEvent,
2364 cx: &mut ViewContext<Self>,
2365 ) {
2366 match event {
2367 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2368 let cursor_scroll_position = self.cursor_scroll_position(cx);
2369 if *autoscroll {
2370 self.scroll_position = cursor_scroll_position;
2371 } else if self.scroll_position != cursor_scroll_position {
2372 self.scroll_position = None;
2373 }
2374 }
2375 EditorEvent::SelectionsChanged { .. } => {
2376 self.scroll_position = self.cursor_scroll_position(cx);
2377 self.update_active_patch(cx);
2378 }
2379 _ => {}
2380 }
2381 cx.emit(event.clone());
2382 }
2383
2384 fn active_patch(&self) -> Option<(Range<text::Anchor>, &PatchViewState)> {
2385 let patch = self.active_patch.as_ref()?;
2386 Some((patch.clone(), self.patches.get(&patch)?))
2387 }
2388
2389 fn update_active_patch(&mut self, cx: &mut ViewContext<Self>) {
2390 let newest_cursor = self.editor.update(cx, |editor, cx| {
2391 editor.selections.newest::<Point>(cx).head()
2392 });
2393 let context = self.context.read(cx);
2394
2395 let new_patch = context.patch_containing(newest_cursor, cx).cloned();
2396
2397 if new_patch.as_ref().map(|p| &p.range) == self.active_patch.as_ref() {
2398 return;
2399 }
2400
2401 if let Some(old_patch_range) = self.active_patch.take() {
2402 if let Some(patch_state) = self.patches.get_mut(&old_patch_range) {
2403 if let Some(state) = patch_state.editor.take() {
2404 if let Some(editor) = state.editor.upgrade() {
2405 self.close_patch_editor(editor, cx);
2406 }
2407 }
2408 }
2409 }
2410
2411 if let Some(new_patch) = new_patch {
2412 self.active_patch = Some(new_patch.range.clone());
2413
2414 if let Some(patch_state) = self.patches.get_mut(&new_patch.range) {
2415 let mut editor = None;
2416 if let Some(state) = &patch_state.editor {
2417 if let Some(opened_editor) = state.editor.upgrade() {
2418 editor = Some(opened_editor);
2419 }
2420 }
2421
2422 if let Some(editor) = editor {
2423 self.workspace
2424 .update(cx, |workspace, cx| {
2425 workspace.activate_item(&editor, true, false, cx);
2426 })
2427 .ok();
2428 } else {
2429 patch_state.update_task = Some(cx.spawn(move |this, cx| async move {
2430 Self::open_patch_editor(this, new_patch, cx).await.log_err();
2431 }));
2432 }
2433 }
2434 }
2435 }
2436
2437 fn close_patch_editor(
2438 &mut self,
2439 editor: View<ProposedChangesEditor>,
2440 cx: &mut ViewContext<ContextEditor>,
2441 ) {
2442 self.workspace
2443 .update(cx, |workspace, cx| {
2444 if let Some(pane) = workspace.pane_for(&editor) {
2445 pane.update(cx, |pane, cx| {
2446 let item_id = editor.entity_id();
2447 if !editor.read(cx).focus_handle(cx).is_focused(cx) {
2448 pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
2449 .detach_and_log_err(cx);
2450 }
2451 });
2452 }
2453 })
2454 .ok();
2455 }
2456
2457 async fn open_patch_editor(
2458 this: WeakView<Self>,
2459 patch: AssistantPatch,
2460 mut cx: AsyncWindowContext,
2461 ) -> Result<()> {
2462 let project = this.update(&mut cx, |this, _| this.project.clone())?;
2463 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2464
2465 let editor = cx.new_view(|cx| {
2466 let editor = ProposedChangesEditor::new(
2467 patch.title.clone(),
2468 resolved_patch
2469 .edit_groups
2470 .iter()
2471 .map(|(buffer, groups)| ProposedChangeLocation {
2472 buffer: buffer.clone(),
2473 ranges: groups
2474 .iter()
2475 .map(|group| group.context_range.clone())
2476 .collect(),
2477 })
2478 .collect(),
2479 Some(project.clone()),
2480 cx,
2481 );
2482 resolved_patch.apply(&editor, cx);
2483 editor
2484 })?;
2485
2486 this.update(&mut cx, |this, cx| {
2487 if let Some(patch_state) = this.patches.get_mut(&patch.range) {
2488 patch_state.editor = Some(PatchEditorState {
2489 editor: editor.downgrade(),
2490 opened_patch: patch,
2491 });
2492 patch_state.update_task.take();
2493 }
2494
2495 this.workspace
2496 .update(cx, |workspace, cx| {
2497 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2498 })
2499 .log_err();
2500 })?;
2501
2502 Ok(())
2503 }
2504
2505 async fn update_patch_editor(
2506 this: WeakView<Self>,
2507 patch: AssistantPatch,
2508 mut cx: AsyncWindowContext,
2509 ) -> Result<()> {
2510 let project = this.update(&mut cx, |this, _| this.project.clone())?;
2511 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2512 this.update(&mut cx, |this, cx| {
2513 let patch_state = this.patches.get_mut(&patch.range)?;
2514
2515 let locations = resolved_patch
2516 .edit_groups
2517 .iter()
2518 .map(|(buffer, groups)| ProposedChangeLocation {
2519 buffer: buffer.clone(),
2520 ranges: groups
2521 .iter()
2522 .map(|group| group.context_range.clone())
2523 .collect(),
2524 })
2525 .collect();
2526
2527 if let Some(state) = &mut patch_state.editor {
2528 if let Some(editor) = state.editor.upgrade() {
2529 editor.update(cx, |editor, cx| {
2530 editor.set_title(patch.title.clone(), cx);
2531 editor.reset_locations(locations, cx);
2532 resolved_patch.apply(editor, cx);
2533 });
2534
2535 state.opened_patch = patch;
2536 } else {
2537 patch_state.editor.take();
2538 }
2539 }
2540 patch_state.update_task.take();
2541
2542 Some(())
2543 })?;
2544 Ok(())
2545 }
2546
2547 fn handle_editor_search_event(
2548 &mut self,
2549 _: View<Editor>,
2550 event: &SearchEvent,
2551 cx: &mut ViewContext<Self>,
2552 ) {
2553 cx.emit(event.clone());
2554 }
2555
2556 fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2557 self.editor.update(cx, |editor, cx| {
2558 let snapshot = editor.snapshot(cx);
2559 let cursor = editor.selections.newest_anchor().head();
2560 let cursor_row = cursor
2561 .to_display_point(&snapshot.display_snapshot)
2562 .row()
2563 .as_f32();
2564 let scroll_position = editor
2565 .scroll_manager
2566 .anchor()
2567 .scroll_position(&snapshot.display_snapshot);
2568
2569 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2570 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2571 Some(ScrollPosition {
2572 cursor,
2573 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2574 })
2575 } else {
2576 None
2577 }
2578 })
2579 }
2580
2581 fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2582 self.editor.update(cx, |editor, cx| {
2583 let buffer = editor.buffer().read(cx).snapshot(cx);
2584
2585 let excerpt_id = *buffer.as_singleton().unwrap().0;
2586 let mut old_blocks = std::mem::take(&mut self.blocks);
2587 let mut blocks_to_remove: HashMap<_, _> = old_blocks
2588 .iter()
2589 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
2590 .collect();
2591 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
2592
2593 let render_block = |message: MessageMetadata| -> RenderBlock {
2594 Box::new({
2595 let context = self.context.clone();
2596 move |cx| {
2597 let message_id = MessageId(message.timestamp);
2598 let show_spinner = message.role == Role::Assistant
2599 && message.status == MessageStatus::Pending;
2600
2601 let label = match message.role {
2602 Role::User => {
2603 Label::new("You").color(Color::Default).into_any_element()
2604 }
2605 Role::Assistant => {
2606 let label = Label::new("Assistant").color(Color::Info);
2607 if show_spinner {
2608 label
2609 .with_animation(
2610 "pulsating-label",
2611 Animation::new(Duration::from_secs(2))
2612 .repeat()
2613 .with_easing(pulsating_between(0.4, 0.8)),
2614 |label, delta| label.alpha(delta),
2615 )
2616 .into_any_element()
2617 } else {
2618 label.into_any_element()
2619 }
2620 }
2621
2622 Role::System => Label::new("System")
2623 .color(Color::Warning)
2624 .into_any_element(),
2625 };
2626
2627 let sender = ButtonLike::new("role")
2628 .style(ButtonStyle::Filled)
2629 .child(label)
2630 .tooltip(|cx| {
2631 Tooltip::with_meta(
2632 "Toggle message role",
2633 None,
2634 "Available roles: You (User), Assistant, System",
2635 cx,
2636 )
2637 })
2638 .on_click({
2639 let context = context.clone();
2640 move |_, cx| {
2641 context.update(cx, |context, cx| {
2642 context.cycle_message_roles(
2643 HashSet::from_iter(Some(message_id)),
2644 cx,
2645 )
2646 })
2647 }
2648 });
2649
2650 h_flex()
2651 .id(("message_header", message_id.as_u64()))
2652 .pl(cx.gutter_dimensions.full_width())
2653 .h_11()
2654 .w_full()
2655 .relative()
2656 .gap_1()
2657 .child(sender)
2658 .children(match &message.cache {
2659 Some(cache) if cache.is_final_anchor => match cache.status {
2660 CacheStatus::Cached => Some(
2661 div()
2662 .id("cached")
2663 .child(
2664 Icon::new(IconName::DatabaseZap)
2665 .size(IconSize::XSmall)
2666 .color(Color::Hint),
2667 )
2668 .tooltip(|cx| {
2669 Tooltip::with_meta(
2670 "Context cached",
2671 None,
2672 "Large messages cached to optimize performance",
2673 cx,
2674 )
2675 })
2676 .into_any_element(),
2677 ),
2678 CacheStatus::Pending => Some(
2679 div()
2680 .child(
2681 Icon::new(IconName::Ellipsis)
2682 .size(IconSize::XSmall)
2683 .color(Color::Hint),
2684 )
2685 .into_any_element(),
2686 ),
2687 },
2688 _ => None,
2689 })
2690 .children(match &message.status {
2691 MessageStatus::Error(error) => Some(
2692 Button::new("show-error", "Error")
2693 .color(Color::Error)
2694 .selected_label_color(Color::Error)
2695 .selected_icon_color(Color::Error)
2696 .icon(IconName::XCircle)
2697 .icon_color(Color::Error)
2698 .icon_size(IconSize::Small)
2699 .icon_position(IconPosition::Start)
2700 .tooltip(move |cx| {
2701 Tooltip::with_meta(
2702 "Error interacting with language model",
2703 None,
2704 "Click for more details",
2705 cx,
2706 )
2707 })
2708 .on_click({
2709 let context = context.clone();
2710 let error = error.clone();
2711 move |_, cx| {
2712 context.update(cx, |_, cx| {
2713 cx.emit(ContextEvent::ShowAssistError(
2714 error.clone(),
2715 ));
2716 });
2717 }
2718 })
2719 .into_any_element(),
2720 ),
2721 MessageStatus::Canceled => Some(
2722 ButtonLike::new("canceled")
2723 .child(Icon::new(IconName::XCircle).color(Color::Disabled))
2724 .child(
2725 Label::new("Canceled")
2726 .size(LabelSize::Small)
2727 .color(Color::Disabled),
2728 )
2729 .tooltip(move |cx| {
2730 Tooltip::with_meta(
2731 "Canceled",
2732 None,
2733 "Interaction with the assistant was canceled",
2734 cx,
2735 )
2736 })
2737 .into_any_element(),
2738 ),
2739 _ => None,
2740 })
2741 .into_any_element()
2742 }
2743 })
2744 };
2745 let create_block_properties = |message: &Message| BlockProperties {
2746 height: 2,
2747 style: BlockStyle::Sticky,
2748 placement: BlockPlacement::Above(
2749 buffer
2750 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
2751 .unwrap(),
2752 ),
2753 priority: usize::MAX,
2754 render: render_block(MessageMetadata::from(message)),
2755 };
2756 let mut new_blocks = vec![];
2757 let mut block_index_to_message = vec![];
2758 for message in self.context.read(cx).messages(cx) {
2759 if let Some(_) = blocks_to_remove.remove(&message.id) {
2760 // This is an old message that we might modify.
2761 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
2762 debug_assert!(
2763 false,
2764 "old_blocks should contain a message_id we've just removed."
2765 );
2766 continue;
2767 };
2768 // Should we modify it?
2769 let message_meta = MessageMetadata::from(&message);
2770 if meta != &message_meta {
2771 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
2772 *meta = message_meta;
2773 }
2774 } else {
2775 // This is a new message.
2776 new_blocks.push(create_block_properties(&message));
2777 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
2778 }
2779 }
2780 editor.replace_blocks(blocks_to_replace, None, cx);
2781 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
2782
2783 let ids = editor.insert_blocks(new_blocks, None, cx);
2784 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
2785 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
2786 ));
2787 self.blocks = old_blocks;
2788 });
2789 }
2790
2791 /// Returns either the selected text, or the content of the Markdown code
2792 /// block surrounding the cursor.
2793 fn get_selection_or_code_block(
2794 context_editor_view: &View<ContextEditor>,
2795 cx: &mut ViewContext<Workspace>,
2796 ) -> Option<(String, bool)> {
2797 const CODE_FENCE_DELIMITER: &'static str = "```";
2798
2799 let context_editor = context_editor_view.read(cx).editor.clone();
2800 context_editor.update(cx, |context_editor, cx| {
2801 if context_editor.selections.newest::<Point>(cx).is_empty() {
2802 let snapshot = context_editor.buffer().read(cx).snapshot(cx);
2803 let (_, _, snapshot) = snapshot.as_singleton()?;
2804
2805 let head = context_editor.selections.newest::<Point>(cx).head();
2806 let offset = snapshot.point_to_offset(head);
2807
2808 let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
2809 let mut text = snapshot
2810 .text_for_range(surrounding_code_block_range)
2811 .collect::<String>();
2812
2813 // If there is no newline trailing the closing three-backticks, then
2814 // tree-sitter-md extends the range of the content node to include
2815 // the backticks.
2816 if text.ends_with(CODE_FENCE_DELIMITER) {
2817 text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
2818 }
2819
2820 (!text.is_empty()).then_some((text, true))
2821 } else {
2822 let anchor = context_editor.selections.newest_anchor();
2823 let text = context_editor
2824 .buffer()
2825 .read(cx)
2826 .read(cx)
2827 .text_for_range(anchor.range())
2828 .collect::<String>();
2829
2830 (!text.is_empty()).then_some((text, false))
2831 }
2832 })
2833 }
2834
2835 fn insert_selection(
2836 workspace: &mut Workspace,
2837 _: &InsertIntoEditor,
2838 cx: &mut ViewContext<Workspace>,
2839 ) {
2840 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2841 return;
2842 };
2843 let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2844 return;
2845 };
2846 let Some(active_editor_view) = workspace
2847 .active_item(cx)
2848 .and_then(|item| item.act_as::<Editor>(cx))
2849 else {
2850 return;
2851 };
2852
2853 if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
2854 active_editor_view.update(cx, |editor, cx| {
2855 editor.insert(&text, cx);
2856 editor.focus(cx);
2857 })
2858 }
2859 }
2860
2861 fn copy_code(workspace: &mut Workspace, _: &CopyCode, cx: &mut ViewContext<Workspace>) {
2862 let result = maybe!({
2863 let panel = workspace.panel::<AssistantPanel>(cx)?;
2864 let context_editor_view = panel.read(cx).active_context_editor(cx)?;
2865 Self::get_selection_or_code_block(&context_editor_view, cx)
2866 });
2867 let Some((text, is_code_block)) = result else {
2868 return;
2869 };
2870
2871 cx.write_to_clipboard(ClipboardItem::new_string(text));
2872
2873 struct CopyToClipboardToast;
2874 workspace.show_toast(
2875 Toast::new(
2876 NotificationId::unique::<CopyToClipboardToast>(),
2877 format!(
2878 "{} copied to clipboard.",
2879 if is_code_block {
2880 "Code block"
2881 } else {
2882 "Selection"
2883 }
2884 ),
2885 )
2886 .autohide(),
2887 cx,
2888 );
2889 }
2890
2891 fn insert_dragged_files(
2892 workspace: &mut Workspace,
2893 action: &InsertDraggedFiles,
2894 cx: &mut ViewContext<Workspace>,
2895 ) {
2896 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2897 return;
2898 };
2899 let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2900 return;
2901 };
2902
2903 let project = workspace.project().clone();
2904
2905 let paths = match action {
2906 InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
2907 InsertDraggedFiles::ExternalFiles(paths) => {
2908 let tasks = paths
2909 .clone()
2910 .into_iter()
2911 .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
2912 .collect::<Vec<_>>();
2913
2914 cx.spawn(move |_, cx| async move {
2915 let mut paths = vec![];
2916 let mut worktrees = vec![];
2917
2918 let opened_paths = futures::future::join_all(tasks).await;
2919 for (worktree, project_path) in opened_paths.into_iter().flatten() {
2920 let Ok(worktree_root_name) =
2921 worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
2922 else {
2923 continue;
2924 };
2925
2926 let mut full_path = PathBuf::from(worktree_root_name.clone());
2927 full_path.push(&project_path.path);
2928 paths.push(full_path);
2929 worktrees.push(worktree);
2930 }
2931
2932 (paths, worktrees)
2933 })
2934 }
2935 };
2936
2937 cx.spawn(|_, mut cx| async move {
2938 let (paths, dragged_file_worktrees) = paths.await;
2939 let cmd_name = file_command::FileSlashCommand.name();
2940
2941 context_editor_view
2942 .update(&mut cx, |context_editor, cx| {
2943 let file_argument = paths
2944 .into_iter()
2945 .map(|path| path.to_string_lossy().to_string())
2946 .collect::<Vec<_>>()
2947 .join(" ");
2948
2949 context_editor.editor.update(cx, |editor, cx| {
2950 editor.insert("\n", cx);
2951 editor.insert(&format!("/{} {}", cmd_name, file_argument), cx);
2952 });
2953
2954 context_editor.confirm_command(&ConfirmCommand, cx);
2955
2956 context_editor
2957 .dragged_file_worktrees
2958 .extend(dragged_file_worktrees);
2959 })
2960 .log_err();
2961 })
2962 .detach();
2963 }
2964
2965 fn quote_selection(
2966 workspace: &mut Workspace,
2967 _: &QuoteSelection,
2968 cx: &mut ViewContext<Workspace>,
2969 ) {
2970 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2971 return;
2972 };
2973 let Some(editor) = workspace
2974 .active_item(cx)
2975 .and_then(|item| item.act_as::<Editor>(cx))
2976 else {
2977 return;
2978 };
2979
2980 let mut creases = vec![];
2981 editor.update(cx, |editor, cx| {
2982 let selections = editor.selections.all_adjusted(cx);
2983 let buffer = editor.buffer().read(cx).snapshot(cx);
2984 for selection in selections {
2985 let range = editor::ToOffset::to_offset(&selection.start, &buffer)
2986 ..editor::ToOffset::to_offset(&selection.end, &buffer);
2987 let selected_text = buffer.text_for_range(range.clone()).collect::<String>();
2988 if selected_text.is_empty() {
2989 continue;
2990 }
2991 let start_language = buffer.language_at(range.start);
2992 let end_language = buffer.language_at(range.end);
2993 let language_name = if start_language == end_language {
2994 start_language.map(|language| language.code_fence_block_name())
2995 } else {
2996 None
2997 };
2998 let language_name = language_name.as_deref().unwrap_or("");
2999 let filename = buffer
3000 .file_at(selection.start)
3001 .map(|file| file.full_path(cx));
3002 let text = if language_name == "markdown" {
3003 selected_text
3004 .lines()
3005 .map(|line| format!("> {}", line))
3006 .collect::<Vec<_>>()
3007 .join("\n")
3008 } else {
3009 let start_symbols = buffer
3010 .symbols_containing(selection.start, None)
3011 .map(|(_, symbols)| symbols);
3012 let end_symbols = buffer
3013 .symbols_containing(selection.end, None)
3014 .map(|(_, symbols)| symbols);
3015
3016 let outline_text = if let Some((start_symbols, end_symbols)) =
3017 start_symbols.zip(end_symbols)
3018 {
3019 Some(
3020 start_symbols
3021 .into_iter()
3022 .zip(end_symbols)
3023 .take_while(|(a, b)| a == b)
3024 .map(|(a, _)| a.text)
3025 .collect::<Vec<_>>()
3026 .join(" > "),
3027 )
3028 } else {
3029 None
3030 };
3031
3032 let line_comment_prefix = start_language
3033 .and_then(|l| l.default_scope().line_comment_prefixes().first().cloned());
3034
3035 let fence = codeblock_fence_for_path(
3036 filename.as_deref(),
3037 Some(selection.start.row..=selection.end.row),
3038 );
3039
3040 if let Some((line_comment_prefix, outline_text)) =
3041 line_comment_prefix.zip(outline_text)
3042 {
3043 let breadcrumb =
3044 format!("{line_comment_prefix}Excerpt from: {outline_text}\n");
3045 format!("{fence}{breadcrumb}{selected_text}\n```")
3046 } else {
3047 format!("{fence}{selected_text}\n```")
3048 }
3049 };
3050 let crease_title = if let Some(path) = filename {
3051 let start_line = selection.start.row + 1;
3052 let end_line = selection.end.row + 1;
3053 if start_line == end_line {
3054 format!("{}, Line {}", path.display(), start_line)
3055 } else {
3056 format!("{}, Lines {} to {}", path.display(), start_line, end_line)
3057 }
3058 } else {
3059 "Quoted selection".to_string()
3060 };
3061 creases.push((text, crease_title));
3062 }
3063 });
3064 if creases.is_empty() {
3065 return;
3066 }
3067 // Activate the panel
3068 if !panel.focus_handle(cx).contains_focused(cx) {
3069 workspace.toggle_panel_focus::<AssistantPanel>(cx);
3070 }
3071
3072 panel.update(cx, |_, cx| {
3073 // Wait to create a new context until the workspace is no longer
3074 // being updated.
3075 cx.defer(move |panel, cx| {
3076 if let Some(context) = panel
3077 .active_context_editor(cx)
3078 .or_else(|| panel.new_context(cx))
3079 {
3080 context.update(cx, |context, cx| {
3081 context.editor.update(cx, |editor, cx| {
3082 editor.insert("\n", cx);
3083 for (text, crease_title) in creases {
3084 let point = editor.selections.newest::<Point>(cx).head();
3085 let start_row = MultiBufferRow(point.row);
3086
3087 editor.insert(&text, cx);
3088
3089 let snapshot = editor.buffer().read(cx).snapshot(cx);
3090 let anchor_before = snapshot.anchor_after(point);
3091 let anchor_after = editor
3092 .selections
3093 .newest_anchor()
3094 .head()
3095 .bias_left(&snapshot);
3096
3097 editor.insert("\n", cx);
3098
3099 let fold_placeholder = quote_selection_fold_placeholder(
3100 crease_title,
3101 cx.view().downgrade(),
3102 );
3103 let crease = Crease::new(
3104 anchor_before..anchor_after,
3105 fold_placeholder,
3106 render_quote_selection_output_toggle,
3107 |_, _, _| Empty.into_any(),
3108 );
3109 editor.insert_creases(vec![crease], cx);
3110 editor.fold_at(
3111 &FoldAt {
3112 buffer_row: start_row,
3113 },
3114 cx,
3115 );
3116 }
3117 })
3118 });
3119 };
3120 });
3121 });
3122 }
3123
3124 fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
3125 if self.editor.read(cx).selections.count() == 1 {
3126 let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
3127 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3128 copied_text,
3129 metadata,
3130 ));
3131 cx.stop_propagation();
3132 return;
3133 }
3134
3135 cx.propagate();
3136 }
3137
3138 fn cut(&mut self, _: &editor::actions::Cut, cx: &mut ViewContext<Self>) {
3139 if self.editor.read(cx).selections.count() == 1 {
3140 let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
3141
3142 self.editor.update(cx, |editor, cx| {
3143 editor.transact(cx, |this, cx| {
3144 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3145 s.select(selections);
3146 });
3147 this.insert("", cx);
3148 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3149 copied_text,
3150 metadata,
3151 ));
3152 });
3153 });
3154
3155 cx.stop_propagation();
3156 return;
3157 }
3158
3159 cx.propagate();
3160 }
3161
3162 fn get_clipboard_contents(
3163 &mut self,
3164 cx: &mut ViewContext<Self>,
3165 ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
3166 let (snapshot, selection, creases) = self.editor.update(cx, |editor, cx| {
3167 let mut selection = editor.selections.newest::<Point>(cx);
3168 let snapshot = editor.buffer().read(cx).snapshot(cx);
3169
3170 let is_entire_line = selection.is_empty() || editor.selections.line_mode;
3171 if is_entire_line {
3172 selection.start = Point::new(selection.start.row, 0);
3173 selection.end =
3174 cmp::min(snapshot.max_point(), Point::new(selection.start.row + 1, 0));
3175 selection.goal = SelectionGoal::None;
3176 }
3177
3178 let selection_start = snapshot.point_to_offset(selection.start);
3179
3180 (
3181 snapshot.clone(),
3182 selection.clone(),
3183 editor.display_map.update(cx, |display_map, cx| {
3184 display_map
3185 .snapshot(cx)
3186 .crease_snapshot
3187 .creases_in_range(
3188 MultiBufferRow(selection.start.row)
3189 ..MultiBufferRow(selection.end.row + 1),
3190 &snapshot,
3191 )
3192 .filter_map(|crease| {
3193 if let Some(metadata) = &crease.metadata {
3194 let start = crease
3195 .range
3196 .start
3197 .to_offset(&snapshot)
3198 .saturating_sub(selection_start);
3199 let end = crease
3200 .range
3201 .end
3202 .to_offset(&snapshot)
3203 .saturating_sub(selection_start);
3204
3205 let range_relative_to_selection = start..end;
3206
3207 if range_relative_to_selection.is_empty() {
3208 None
3209 } else {
3210 Some(SelectedCreaseMetadata {
3211 range_relative_to_selection,
3212 crease: metadata.clone(),
3213 })
3214 }
3215 } else {
3216 None
3217 }
3218 })
3219 .collect::<Vec<_>>()
3220 }),
3221 )
3222 });
3223
3224 let selection = selection.map(|point| snapshot.point_to_offset(point));
3225 let context = self.context.read(cx);
3226
3227 let mut text = String::new();
3228 for message in context.messages(cx) {
3229 if message.offset_range.start >= selection.range().end {
3230 break;
3231 } else if message.offset_range.end >= selection.range().start {
3232 let range = cmp::max(message.offset_range.start, selection.range().start)
3233 ..cmp::min(message.offset_range.end, selection.range().end);
3234 if !range.is_empty() {
3235 for chunk in context.buffer().read(cx).text_for_range(range) {
3236 text.push_str(chunk);
3237 }
3238 if message.offset_range.end < selection.range().end {
3239 text.push('\n');
3240 }
3241 }
3242 }
3243 }
3244
3245 (text, CopyMetadata { creases }, vec![selection])
3246 }
3247
3248 fn paste(&mut self, action: &editor::actions::Paste, cx: &mut ViewContext<Self>) {
3249 cx.stop_propagation();
3250
3251 let images = if let Some(item) = cx.read_from_clipboard() {
3252 item.into_entries()
3253 .filter_map(|entry| {
3254 if let ClipboardEntry::Image(image) = entry {
3255 Some(image)
3256 } else {
3257 None
3258 }
3259 })
3260 .collect()
3261 } else {
3262 Vec::new()
3263 };
3264
3265 let metadata = if let Some(item) = cx.read_from_clipboard() {
3266 item.entries().first().and_then(|entry| {
3267 if let ClipboardEntry::String(text) = entry {
3268 text.metadata_json::<CopyMetadata>()
3269 } else {
3270 None
3271 }
3272 })
3273 } else {
3274 None
3275 };
3276
3277 if images.is_empty() {
3278 self.editor.update(cx, |editor, cx| {
3279 let paste_position = editor.selections.newest::<usize>(cx).head();
3280 editor.paste(action, cx);
3281
3282 if let Some(metadata) = metadata {
3283 let buffer = editor.buffer().read(cx).snapshot(cx);
3284
3285 let mut buffer_rows_to_fold = BTreeSet::new();
3286 let weak_editor = cx.view().downgrade();
3287 editor.insert_creases(
3288 metadata.creases.into_iter().map(|metadata| {
3289 let start = buffer.anchor_after(
3290 paste_position + metadata.range_relative_to_selection.start,
3291 );
3292 let end = buffer.anchor_before(
3293 paste_position + metadata.range_relative_to_selection.end,
3294 );
3295
3296 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
3297 buffer_rows_to_fold.insert(buffer_row);
3298 Crease::new(
3299 start..end,
3300 FoldPlaceholder {
3301 constrain_width: false,
3302 render: render_fold_icon_button(
3303 weak_editor.clone(),
3304 metadata.crease.icon,
3305 metadata.crease.label.clone(),
3306 ),
3307 merge_adjacent: false,
3308 },
3309 render_slash_command_output_toggle,
3310 |_, _, _| Empty.into_any(),
3311 )
3312 .with_metadata(metadata.crease.clone())
3313 }),
3314 cx,
3315 );
3316 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
3317 editor.fold_at(&FoldAt { buffer_row }, cx);
3318 }
3319 }
3320 });
3321 } else {
3322 let mut image_positions = Vec::new();
3323 self.editor.update(cx, |editor, cx| {
3324 editor.transact(cx, |editor, cx| {
3325 let edits = editor
3326 .selections
3327 .all::<usize>(cx)
3328 .into_iter()
3329 .map(|selection| (selection.start..selection.end, "\n"));
3330 editor.edit(edits, cx);
3331
3332 let snapshot = editor.buffer().read(cx).snapshot(cx);
3333 for selection in editor.selections.all::<usize>(cx) {
3334 image_positions.push(snapshot.anchor_before(selection.end));
3335 }
3336 });
3337 });
3338
3339 self.context.update(cx, |context, cx| {
3340 for image in images {
3341 let Some(render_image) = image.to_image_data(cx).log_err() else {
3342 continue;
3343 };
3344 let image_id = image.id();
3345 let image_task = LanguageModelImage::from_image(image, cx).shared();
3346
3347 for image_position in image_positions.iter() {
3348 context.insert_content(
3349 Content::Image {
3350 anchor: image_position.text_anchor,
3351 image_id,
3352 image: image_task.clone(),
3353 render_image: render_image.clone(),
3354 },
3355 cx,
3356 );
3357 }
3358 }
3359 });
3360 }
3361 }
3362
3363 fn update_image_blocks(&mut self, cx: &mut ViewContext<Self>) {
3364 self.editor.update(cx, |editor, cx| {
3365 let buffer = editor.buffer().read(cx).snapshot(cx);
3366 let excerpt_id = *buffer.as_singleton().unwrap().0;
3367 let old_blocks = std::mem::take(&mut self.image_blocks);
3368 let new_blocks = self
3369 .context
3370 .read(cx)
3371 .contents(cx)
3372 .filter_map(|content| {
3373 if let Content::Image {
3374 anchor,
3375 render_image,
3376 ..
3377 } = content
3378 {
3379 Some((anchor, render_image))
3380 } else {
3381 None
3382 }
3383 })
3384 .filter_map(|(anchor, render_image)| {
3385 const MAX_HEIGHT_IN_LINES: u32 = 8;
3386 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
3387 let image = render_image.clone();
3388 anchor.is_valid(&buffer).then(|| BlockProperties {
3389 placement: BlockPlacement::Above(anchor),
3390 height: MAX_HEIGHT_IN_LINES,
3391 style: BlockStyle::Sticky,
3392 render: Box::new(move |cx| {
3393 let image_size = size_for_image(
3394 &image,
3395 size(
3396 cx.max_width - cx.gutter_dimensions.full_width(),
3397 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
3398 ),
3399 );
3400 h_flex()
3401 .pl(cx.gutter_dimensions.full_width())
3402 .child(
3403 img(image.clone())
3404 .object_fit(gpui::ObjectFit::ScaleDown)
3405 .w(image_size.width)
3406 .h(image_size.height),
3407 )
3408 .into_any_element()
3409 }),
3410 priority: 0,
3411 })
3412 })
3413 .collect::<Vec<_>>();
3414
3415 editor.remove_blocks(old_blocks, None, cx);
3416 let ids = editor.insert_blocks(new_blocks, None, cx);
3417 self.image_blocks = HashSet::from_iter(ids);
3418 });
3419 }
3420
3421 fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3422 self.context.update(cx, |context, cx| {
3423 let selections = self.editor.read(cx).selections.disjoint_anchors();
3424 for selection in selections.as_ref() {
3425 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3426 let range = selection
3427 .map(|endpoint| endpoint.to_offset(&buffer))
3428 .range();
3429 context.split_message(range, cx);
3430 }
3431 });
3432 }
3433
3434 fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3435 self.context.update(cx, |context, cx| {
3436 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3437 });
3438 }
3439
3440 fn title(&self, cx: &AppContext) -> Cow<str> {
3441 self.context
3442 .read(cx)
3443 .summary()
3444 .map(|summary| summary.text.clone())
3445 .map(Cow::Owned)
3446 .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3447 }
3448
3449 fn render_patch_header(
3450 &self,
3451 range: Range<text::Anchor>,
3452 _id: FoldId,
3453 cx: &mut ViewContext<Self>,
3454 ) -> Option<AnyElement> {
3455 let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3456 let theme = cx.theme().clone();
3457 Some(
3458 h_flex()
3459 .px_1()
3460 .py_0p5()
3461 .border_b_1()
3462 .border_color(theme.status().info_border)
3463 .gap_1()
3464 .child(Icon::new(IconName::Diff).size(IconSize::Small))
3465 .child(Label::new(patch.title.clone()).size(LabelSize::Small))
3466 .into_any(),
3467 )
3468 }
3469
3470 fn render_patch_footer(
3471 &mut self,
3472 range: Range<text::Anchor>,
3473 max_width: Pixels,
3474 gutter_width: Pixels,
3475 id: BlockId,
3476 cx: &mut ViewContext<Self>,
3477 ) -> Option<AnyElement> {
3478 let snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3479 let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
3480 let excerpt_id = *excerpt_id;
3481 let anchor = snapshot
3482 .buffer_snapshot
3483 .anchor_in_excerpt(excerpt_id, range.start)
3484 .unwrap();
3485
3486 if !snapshot.intersects_fold(anchor) {
3487 return None;
3488 }
3489
3490 let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3491 let paths = patch
3492 .paths()
3493 .map(|p| SharedString::from(p.to_string()))
3494 .collect::<BTreeSet<_>>();
3495
3496 Some(
3497 v_flex()
3498 .id(id)
3499 .pl(gutter_width)
3500 .w(max_width)
3501 .py_2()
3502 .cursor(CursorStyle::PointingHand)
3503 .on_click(cx.listener(move |this, _, cx| {
3504 this.editor.update(cx, |editor, cx| {
3505 editor.change_selections(None, cx, |selections| {
3506 selections.select_ranges(vec![anchor..anchor]);
3507 });
3508 });
3509 this.focus_active_patch(cx);
3510 }))
3511 .children(paths.into_iter().map(|path| {
3512 h_flex()
3513 .pl_1()
3514 .gap_1()
3515 .child(Icon::new(IconName::File).size(IconSize::Small))
3516 .child(Label::new(path).size(LabelSize::Small))
3517 }))
3518 .when(patch.status == AssistantPatchStatus::Pending, |div| {
3519 div.child(
3520 Label::new("Generating")
3521 .color(Color::Muted)
3522 .size(LabelSize::Small)
3523 .with_animation(
3524 "pulsating-label",
3525 Animation::new(Duration::from_secs(2))
3526 .repeat()
3527 .with_easing(pulsating_between(0.4, 1.)),
3528 |label, delta| label.alpha(delta),
3529 ),
3530 )
3531 })
3532 .into_any(),
3533 )
3534 }
3535
3536 fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3537 use feature_flags::FeatureFlagAppExt;
3538 let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
3539 assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
3540 });
3541
3542 if nudge.map_or(false, |value| value) {
3543 Some(
3544 h_flex()
3545 .p_3()
3546 .border_b_1()
3547 .border_color(cx.theme().colors().border_variant)
3548 .bg(cx.theme().colors().editor_background)
3549 .justify_between()
3550 .child(
3551 h_flex()
3552 .gap_3()
3553 .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
3554 .child(Label::new("Zed AI is here! Get started by signing in →")),
3555 )
3556 .child(
3557 Button::new("sign-in", "Sign in")
3558 .size(ButtonSize::Compact)
3559 .style(ButtonStyle::Filled)
3560 .on_click(cx.listener(|this, _event, cx| {
3561 let client = this
3562 .workspace
3563 .update(cx, |workspace, _| workspace.client().clone())
3564 .log_err();
3565
3566 if let Some(client) = client {
3567 cx.spawn(|this, mut cx| async move {
3568 client.authenticate_and_connect(true, &mut cx).await?;
3569 this.update(&mut cx, |_, cx| cx.notify())
3570 })
3571 .detach_and_log_err(cx)
3572 }
3573 })),
3574 )
3575 .into_any_element(),
3576 )
3577 } else if let Some(configuration_error) = configuration_error(cx) {
3578 let label = match configuration_error {
3579 ConfigurationError::NoProvider => "No LLM provider selected.",
3580 ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
3581 };
3582 Some(
3583 h_flex()
3584 .px_3()
3585 .py_2()
3586 .border_b_1()
3587 .border_color(cx.theme().colors().border_variant)
3588 .bg(cx.theme().colors().editor_background)
3589 .justify_between()
3590 .child(
3591 h_flex()
3592 .gap_3()
3593 .child(
3594 Icon::new(IconName::Warning)
3595 .size(IconSize::Small)
3596 .color(Color::Warning),
3597 )
3598 .child(Label::new(label)),
3599 )
3600 .child(
3601 Button::new("open-configuration", "Configure Providers")
3602 .size(ButtonSize::Compact)
3603 .icon(Some(IconName::SlidersVertical))
3604 .icon_size(IconSize::Small)
3605 .icon_position(IconPosition::Start)
3606 .style(ButtonStyle::Filled)
3607 .on_click({
3608 let focus_handle = self.focus_handle(cx).clone();
3609 move |_event, cx| {
3610 focus_handle.dispatch_action(&ShowConfiguration, cx);
3611 }
3612 }),
3613 )
3614 .into_any_element(),
3615 )
3616 } else {
3617 None
3618 }
3619 }
3620
3621 fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3622 let focus_handle = self.focus_handle(cx).clone();
3623
3624 let (style, tooltip) = match token_state(&self.context, cx) {
3625 Some(TokenState::NoTokensLeft { .. }) => (
3626 ButtonStyle::Tinted(TintColor::Negative),
3627 Some(Tooltip::text("Token limit reached", cx)),
3628 ),
3629 Some(TokenState::HasMoreTokens {
3630 over_warn_threshold,
3631 ..
3632 }) => {
3633 let (style, tooltip) = if over_warn_threshold {
3634 (
3635 ButtonStyle::Tinted(TintColor::Warning),
3636 Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3637 )
3638 } else {
3639 (ButtonStyle::Filled, None)
3640 };
3641 (style, tooltip)
3642 }
3643 None => (ButtonStyle::Filled, None),
3644 };
3645
3646 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3647
3648 let has_configuration_error = configuration_error(cx).is_some();
3649 let needs_to_accept_terms = self.show_accept_terms
3650 && provider
3651 .as_ref()
3652 .map_or(false, |provider| provider.must_accept_terms(cx));
3653 let disabled = has_configuration_error || needs_to_accept_terms;
3654
3655 ButtonLike::new("send_button")
3656 .disabled(disabled)
3657 .style(style)
3658 .when_some(tooltip, |button, tooltip| {
3659 button.tooltip(move |_| tooltip.clone())
3660 })
3661 .layer(ElevationIndex::ModalSurface)
3662 .child(Label::new(
3663 if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
3664 "Chat"
3665 } else {
3666 "Send"
3667 },
3668 ))
3669 .children(
3670 KeyBinding::for_action_in(&Assist, &focus_handle, cx)
3671 .map(|binding| binding.into_any_element()),
3672 )
3673 .on_click(move |_event, cx| {
3674 focus_handle.dispatch_action(&Assist, cx);
3675 })
3676 }
3677
3678 fn render_edit_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3679 let focus_handle = self.focus_handle(cx).clone();
3680
3681 let (style, tooltip) = match token_state(&self.context, cx) {
3682 Some(TokenState::NoTokensLeft { .. }) => (
3683 ButtonStyle::Tinted(TintColor::Negative),
3684 Some(Tooltip::text("Token limit reached", cx)),
3685 ),
3686 Some(TokenState::HasMoreTokens {
3687 over_warn_threshold,
3688 ..
3689 }) => {
3690 let (style, tooltip) = if over_warn_threshold {
3691 (
3692 ButtonStyle::Tinted(TintColor::Warning),
3693 Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3694 )
3695 } else {
3696 (ButtonStyle::Filled, None)
3697 };
3698 (style, tooltip)
3699 }
3700 None => (ButtonStyle::Filled, None),
3701 };
3702
3703 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3704
3705 let has_configuration_error = configuration_error(cx).is_some();
3706 let needs_to_accept_terms = self.show_accept_terms
3707 && provider
3708 .as_ref()
3709 .map_or(false, |provider| provider.must_accept_terms(cx));
3710 let disabled = has_configuration_error || needs_to_accept_terms;
3711
3712 ButtonLike::new("edit_button")
3713 .disabled(disabled)
3714 .style(style)
3715 .when_some(tooltip, |button, tooltip| {
3716 button.tooltip(move |_| tooltip.clone())
3717 })
3718 .layer(ElevationIndex::ModalSurface)
3719 .child(Label::new("Suggest Edits"))
3720 .children(
3721 KeyBinding::for_action_in(&Edit, &focus_handle, cx)
3722 .map(|binding| binding.into_any_element()),
3723 )
3724 .on_click(move |_event, cx| {
3725 focus_handle.dispatch_action(&Edit, cx);
3726 })
3727 }
3728
3729 fn render_last_error(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3730 let last_error = self.last_error.as_ref()?;
3731
3732 Some(
3733 div()
3734 .absolute()
3735 .right_3()
3736 .bottom_12()
3737 .max_w_96()
3738 .py_2()
3739 .px_3()
3740 .elevation_2(cx)
3741 .occlude()
3742 .child(match last_error {
3743 AssistError::PaymentRequired => self.render_payment_required_error(cx),
3744 AssistError::MaxMonthlySpendReached => {
3745 self.render_max_monthly_spend_reached_error(cx)
3746 }
3747 AssistError::Message(error_message) => {
3748 self.render_assist_error(error_message, cx)
3749 }
3750 })
3751 .into_any(),
3752 )
3753 }
3754
3755 fn render_payment_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3756 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.";
3757
3758 v_flex()
3759 .gap_0p5()
3760 .child(
3761 h_flex()
3762 .gap_1p5()
3763 .items_center()
3764 .child(Icon::new(IconName::XCircle).color(Color::Error))
3765 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
3766 )
3767 .child(
3768 div()
3769 .id("error-message")
3770 .max_h_24()
3771 .overflow_y_scroll()
3772 .child(Label::new(ERROR_MESSAGE)),
3773 )
3774 .child(
3775 h_flex()
3776 .justify_end()
3777 .mt_1()
3778 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
3779 |this, _, cx| {
3780 this.last_error = None;
3781 cx.open_url(&zed_urls::account_url(cx));
3782 cx.notify();
3783 },
3784 )))
3785 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3786 |this, _, cx| {
3787 this.last_error = None;
3788 cx.notify();
3789 },
3790 ))),
3791 )
3792 .into_any()
3793 }
3794
3795 fn render_max_monthly_spend_reached_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3796 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
3797
3798 v_flex()
3799 .gap_0p5()
3800 .child(
3801 h_flex()
3802 .gap_1p5()
3803 .items_center()
3804 .child(Icon::new(IconName::XCircle).color(Color::Error))
3805 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
3806 )
3807 .child(
3808 div()
3809 .id("error-message")
3810 .max_h_24()
3811 .overflow_y_scroll()
3812 .child(Label::new(ERROR_MESSAGE)),
3813 )
3814 .child(
3815 h_flex()
3816 .justify_end()
3817 .mt_1()
3818 .child(
3819 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
3820 cx.listener(|this, _, cx| {
3821 this.last_error = None;
3822 cx.open_url(&zed_urls::account_url(cx));
3823 cx.notify();
3824 }),
3825 ),
3826 )
3827 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3828 |this, _, cx| {
3829 this.last_error = None;
3830 cx.notify();
3831 },
3832 ))),
3833 )
3834 .into_any()
3835 }
3836
3837 fn render_assist_error(
3838 &self,
3839 error_message: &SharedString,
3840 cx: &mut ViewContext<Self>,
3841 ) -> AnyElement {
3842 v_flex()
3843 .gap_0p5()
3844 .child(
3845 h_flex()
3846 .gap_1p5()
3847 .items_center()
3848 .child(Icon::new(IconName::XCircle).color(Color::Error))
3849 .child(
3850 Label::new("Error interacting with language model")
3851 .weight(FontWeight::MEDIUM),
3852 ),
3853 )
3854 .child(
3855 div()
3856 .id("error-message")
3857 .max_h_24()
3858 .overflow_y_scroll()
3859 .child(Label::new(error_message.clone())),
3860 )
3861 .child(
3862 h_flex()
3863 .justify_end()
3864 .mt_1()
3865 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3866 |this, _, cx| {
3867 this.last_error = None;
3868 cx.notify();
3869 },
3870 ))),
3871 )
3872 .into_any()
3873 }
3874}
3875
3876/// Returns the contents of the *outermost* fenced code block that contains the given offset.
3877fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
3878 const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
3879 const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
3880
3881 let layer = snapshot.syntax_layers().next()?;
3882
3883 let root_node = layer.node();
3884 let mut cursor = root_node.walk();
3885
3886 // Go to the first child for the given offset
3887 while cursor.goto_first_child_for_byte(offset).is_some() {
3888 // If we're at the end of the node, go to the next one.
3889 // Example: if you have a fenced-code-block, and you're on the start of the line
3890 // right after the closing ```, you want to skip the fenced-code-block and
3891 // go to the next sibling.
3892 if cursor.node().end_byte() == offset {
3893 cursor.goto_next_sibling();
3894 }
3895
3896 if cursor.node().start_byte() > offset {
3897 break;
3898 }
3899
3900 // We found the fenced code block.
3901 if cursor.node().kind() == CODE_BLOCK_NODE {
3902 // Now we need to find the child node that contains the code.
3903 cursor.goto_first_child();
3904 loop {
3905 if cursor.node().kind() == CODE_BLOCK_CONTENT {
3906 return Some(cursor.node().byte_range());
3907 }
3908 if !cursor.goto_next_sibling() {
3909 break;
3910 }
3911 }
3912 }
3913 }
3914
3915 None
3916}
3917
3918fn render_fold_icon_button(
3919 editor: WeakView<Editor>,
3920 icon: IconName,
3921 label: SharedString,
3922) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut WindowContext) -> AnyElement> {
3923 Arc::new(move |fold_id, fold_range, _cx| {
3924 let editor = editor.clone();
3925 ButtonLike::new(fold_id)
3926 .style(ButtonStyle::Filled)
3927 .layer(ElevationIndex::ElevatedSurface)
3928 .child(Icon::new(icon))
3929 .child(Label::new(label.clone()).single_line())
3930 .on_click(move |_, cx| {
3931 editor
3932 .update(cx, |editor, cx| {
3933 let buffer_start = fold_range
3934 .start
3935 .to_point(&editor.buffer().read(cx).read(cx));
3936 let buffer_row = MultiBufferRow(buffer_start.row);
3937 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
3938 })
3939 .ok();
3940 })
3941 .into_any_element()
3942 })
3943}
3944
3945#[derive(Debug, Clone, Serialize, Deserialize)]
3946struct CopyMetadata {
3947 creases: Vec<SelectedCreaseMetadata>,
3948}
3949
3950#[derive(Debug, Clone, Serialize, Deserialize)]
3951struct SelectedCreaseMetadata {
3952 range_relative_to_selection: Range<usize>,
3953 crease: CreaseMetadata,
3954}
3955
3956impl EventEmitter<EditorEvent> for ContextEditor {}
3957impl EventEmitter<SearchEvent> for ContextEditor {}
3958
3959impl Render for ContextEditor {
3960 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3961 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3962 let accept_terms = if self.show_accept_terms {
3963 provider
3964 .as_ref()
3965 .and_then(|provider| provider.render_accept_terms(cx))
3966 } else {
3967 None
3968 };
3969 let focus_handle = self
3970 .workspace
3971 .update(cx, |workspace, cx| {
3972 Some(workspace.active_item_as::<Editor>(cx)?.focus_handle(cx))
3973 })
3974 .ok()
3975 .flatten();
3976 v_flex()
3977 .key_context("ContextEditor")
3978 .capture_action(cx.listener(ContextEditor::cancel))
3979 .capture_action(cx.listener(ContextEditor::save))
3980 .capture_action(cx.listener(ContextEditor::copy))
3981 .capture_action(cx.listener(ContextEditor::cut))
3982 .capture_action(cx.listener(ContextEditor::paste))
3983 .capture_action(cx.listener(ContextEditor::cycle_message_role))
3984 .capture_action(cx.listener(ContextEditor::confirm_command))
3985 .on_action(cx.listener(ContextEditor::edit))
3986 .on_action(cx.listener(ContextEditor::assist))
3987 .on_action(cx.listener(ContextEditor::split))
3988 .size_full()
3989 .children(self.render_notice(cx))
3990 .child(
3991 div()
3992 .flex_grow()
3993 .bg(cx.theme().colors().editor_background)
3994 .child(self.editor.clone()),
3995 )
3996 .when_some(accept_terms, |this, element| {
3997 this.child(
3998 div()
3999 .absolute()
4000 .right_3()
4001 .bottom_12()
4002 .max_w_96()
4003 .py_2()
4004 .px_3()
4005 .elevation_2(cx)
4006 .bg(cx.theme().colors().surface_background)
4007 .occlude()
4008 .child(element),
4009 )
4010 })
4011 .children(self.render_last_error(cx))
4012 .child(
4013 h_flex().w_full().relative().child(
4014 h_flex()
4015 .p_2()
4016 .w_full()
4017 .border_t_1()
4018 .border_color(cx.theme().colors().border_variant)
4019 .bg(cx.theme().colors().editor_background)
4020 .child(
4021 h_flex()
4022 .gap_1()
4023 .child(render_inject_context_menu(cx.view().downgrade(), cx))
4024 .child(
4025 IconButton::new("quote-button", IconName::Quote)
4026 .icon_size(IconSize::Small)
4027 .on_click(|_, cx| {
4028 cx.dispatch_action(QuoteSelection.boxed_clone());
4029 })
4030 .tooltip(move |cx| {
4031 cx.new_view(|cx| {
4032 Tooltip::new("Insert Selection").key_binding(
4033 focus_handle.as_ref().and_then(|handle| {
4034 KeyBinding::for_action_in(
4035 &QuoteSelection,
4036 &handle,
4037 cx,
4038 )
4039 }),
4040 )
4041 })
4042 .into()
4043 }),
4044 ),
4045 )
4046 .child(
4047 h_flex()
4048 .w_full()
4049 .justify_end()
4050 .when(
4051 AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
4052 |buttons| {
4053 buttons
4054 .items_center()
4055 .gap_1p5()
4056 .child(self.render_edit_button(cx))
4057 .child(
4058 Label::new("or")
4059 .size(LabelSize::Small)
4060 .color(Color::Muted),
4061 )
4062 },
4063 )
4064 .child(self.render_send_button(cx)),
4065 ),
4066 ),
4067 )
4068 }
4069}
4070
4071impl FocusableView for ContextEditor {
4072 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4073 self.editor.focus_handle(cx)
4074 }
4075}
4076
4077impl Item for ContextEditor {
4078 type Event = editor::EditorEvent;
4079
4080 fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
4081 Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
4082 }
4083
4084 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
4085 match event {
4086 EditorEvent::Edited { .. } => {
4087 f(item::ItemEvent::Edit);
4088 }
4089 EditorEvent::TitleChanged => {
4090 f(item::ItemEvent::UpdateTab);
4091 }
4092 _ => {}
4093 }
4094 }
4095
4096 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
4097 Some(self.title(cx).to_string().into())
4098 }
4099
4100 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
4101 Some(Box::new(handle.clone()))
4102 }
4103
4104 fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
4105 self.editor.update(cx, |editor, cx| {
4106 Item::set_nav_history(editor, nav_history, cx)
4107 })
4108 }
4109
4110 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
4111 self.editor
4112 .update(cx, |editor, cx| Item::navigate(editor, data, cx))
4113 }
4114
4115 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
4116 self.editor.update(cx, Item::deactivated)
4117 }
4118}
4119
4120impl SearchableItem for ContextEditor {
4121 type Match = <Editor as SearchableItem>::Match;
4122
4123 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
4124 self.editor.update(cx, |editor, cx| {
4125 editor.clear_matches(cx);
4126 });
4127 }
4128
4129 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4130 self.editor
4131 .update(cx, |editor, cx| editor.update_matches(matches, cx));
4132 }
4133
4134 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
4135 self.editor
4136 .update(cx, |editor, cx| editor.query_suggestion(cx))
4137 }
4138
4139 fn activate_match(
4140 &mut self,
4141 index: usize,
4142 matches: &[Self::Match],
4143 cx: &mut ViewContext<Self>,
4144 ) {
4145 self.editor.update(cx, |editor, cx| {
4146 editor.activate_match(index, matches, cx);
4147 });
4148 }
4149
4150 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4151 self.editor
4152 .update(cx, |editor, cx| editor.select_matches(matches, cx));
4153 }
4154
4155 fn replace(
4156 &mut self,
4157 identifier: &Self::Match,
4158 query: &project::search::SearchQuery,
4159 cx: &mut ViewContext<Self>,
4160 ) {
4161 self.editor
4162 .update(cx, |editor, cx| editor.replace(identifier, query, cx));
4163 }
4164
4165 fn find_matches(
4166 &mut self,
4167 query: Arc<project::search::SearchQuery>,
4168 cx: &mut ViewContext<Self>,
4169 ) -> Task<Vec<Self::Match>> {
4170 self.editor
4171 .update(cx, |editor, cx| editor.find_matches(query, cx))
4172 }
4173
4174 fn active_match_index(
4175 &mut self,
4176 matches: &[Self::Match],
4177 cx: &mut ViewContext<Self>,
4178 ) -> Option<usize> {
4179 self.editor
4180 .update(cx, |editor, cx| editor.active_match_index(matches, cx))
4181 }
4182}
4183
4184impl FollowableItem for ContextEditor {
4185 fn remote_id(&self) -> Option<workspace::ViewId> {
4186 self.remote_id
4187 }
4188
4189 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
4190 let context = self.context.read(cx);
4191 Some(proto::view::Variant::ContextEditor(
4192 proto::view::ContextEditor {
4193 context_id: context.id().to_proto(),
4194 editor: if let Some(proto::view::Variant::Editor(proto)) =
4195 self.editor.read(cx).to_state_proto(cx)
4196 {
4197 Some(proto)
4198 } else {
4199 None
4200 },
4201 },
4202 ))
4203 }
4204
4205 fn from_state_proto(
4206 workspace: View<Workspace>,
4207 id: workspace::ViewId,
4208 state: &mut Option<proto::view::Variant>,
4209 cx: &mut WindowContext,
4210 ) -> Option<Task<Result<View<Self>>>> {
4211 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
4212 return None;
4213 };
4214 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
4215 unreachable!()
4216 };
4217
4218 let context_id = ContextId::from_proto(state.context_id);
4219 let editor_state = state.editor?;
4220
4221 let (project, panel) = workspace.update(cx, |workspace, cx| {
4222 Some((
4223 workspace.project().clone(),
4224 workspace.panel::<AssistantPanel>(cx)?,
4225 ))
4226 })?;
4227
4228 let context_editor =
4229 panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
4230
4231 Some(cx.spawn(|mut cx| async move {
4232 let context_editor = context_editor.await?;
4233 context_editor
4234 .update(&mut cx, |context_editor, cx| {
4235 context_editor.remote_id = Some(id);
4236 context_editor.editor.update(cx, |editor, cx| {
4237 editor.apply_update_proto(
4238 &project,
4239 proto::update_view::Variant::Editor(proto::update_view::Editor {
4240 selections: editor_state.selections,
4241 pending_selection: editor_state.pending_selection,
4242 scroll_top_anchor: editor_state.scroll_top_anchor,
4243 scroll_x: editor_state.scroll_y,
4244 scroll_y: editor_state.scroll_y,
4245 ..Default::default()
4246 }),
4247 cx,
4248 )
4249 })
4250 })?
4251 .await?;
4252 Ok(context_editor)
4253 }))
4254 }
4255
4256 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
4257 Editor::to_follow_event(event)
4258 }
4259
4260 fn add_event_to_update_proto(
4261 &self,
4262 event: &Self::Event,
4263 update: &mut Option<proto::update_view::Variant>,
4264 cx: &WindowContext,
4265 ) -> bool {
4266 self.editor
4267 .read(cx)
4268 .add_event_to_update_proto(event, update, cx)
4269 }
4270
4271 fn apply_update_proto(
4272 &mut self,
4273 project: &Model<Project>,
4274 message: proto::update_view::Variant,
4275 cx: &mut ViewContext<Self>,
4276 ) -> Task<Result<()>> {
4277 self.editor.update(cx, |editor, cx| {
4278 editor.apply_update_proto(project, message, cx)
4279 })
4280 }
4281
4282 fn is_project_item(&self, _cx: &WindowContext) -> bool {
4283 true
4284 }
4285
4286 fn set_leader_peer_id(
4287 &mut self,
4288 leader_peer_id: Option<proto::PeerId>,
4289 cx: &mut ViewContext<Self>,
4290 ) {
4291 self.editor.update(cx, |editor, cx| {
4292 editor.set_leader_peer_id(leader_peer_id, cx)
4293 })
4294 }
4295
4296 fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
4297 if existing.context.read(cx).id() == self.context.read(cx).id() {
4298 Some(item::Dedup::KeepExisting)
4299 } else {
4300 None
4301 }
4302 }
4303}
4304
4305pub struct ContextEditorToolbarItem {
4306 fs: Arc<dyn Fs>,
4307 workspace: WeakView<Workspace>,
4308 active_context_editor: Option<WeakView<ContextEditor>>,
4309 model_summary_editor: View<Editor>,
4310 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4311}
4312
4313fn active_editor_focus_handle(
4314 workspace: &WeakView<Workspace>,
4315 cx: &WindowContext<'_>,
4316) -> Option<FocusHandle> {
4317 workspace.upgrade().and_then(|workspace| {
4318 Some(
4319 workspace
4320 .read(cx)
4321 .active_item_as::<Editor>(cx)?
4322 .focus_handle(cx),
4323 )
4324 })
4325}
4326
4327fn render_inject_context_menu(
4328 active_context_editor: WeakView<ContextEditor>,
4329 cx: &mut WindowContext<'_>,
4330) -> impl IntoElement {
4331 let commands = SlashCommandRegistry::global(cx);
4332
4333 slash_command_picker::SlashCommandSelector::new(
4334 commands.clone(),
4335 active_context_editor,
4336 Button::new("trigger", "Add Context")
4337 .icon(IconName::Plus)
4338 .icon_size(IconSize::Small)
4339 .icon_position(IconPosition::Start)
4340 .tooltip(|cx| Tooltip::text("Type / to insert via keyboard", cx)),
4341 )
4342}
4343
4344impl ContextEditorToolbarItem {
4345 pub fn new(
4346 workspace: &Workspace,
4347 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4348 model_summary_editor: View<Editor>,
4349 ) -> Self {
4350 Self {
4351 fs: workspace.app_state().fs.clone(),
4352 workspace: workspace.weak_handle(),
4353 active_context_editor: None,
4354 model_summary_editor,
4355 model_selector_menu_handle,
4356 }
4357 }
4358
4359 fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
4360 let context = &self
4361 .active_context_editor
4362 .as_ref()?
4363 .upgrade()?
4364 .read(cx)
4365 .context;
4366 let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
4367 TokenState::NoTokensLeft {
4368 max_token_count,
4369 token_count,
4370 } => (Color::Error, token_count, max_token_count),
4371 TokenState::HasMoreTokens {
4372 max_token_count,
4373 token_count,
4374 over_warn_threshold,
4375 } => {
4376 let color = if over_warn_threshold {
4377 Color::Warning
4378 } else {
4379 Color::Muted
4380 };
4381 (color, token_count, max_token_count)
4382 }
4383 };
4384 Some(
4385 h_flex()
4386 .gap_0p5()
4387 .child(
4388 Label::new(humanize_token_count(token_count))
4389 .size(LabelSize::Small)
4390 .color(token_count_color),
4391 )
4392 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
4393 .child(
4394 Label::new(humanize_token_count(max_token_count))
4395 .size(LabelSize::Small)
4396 .color(Color::Muted),
4397 ),
4398 )
4399 }
4400}
4401
4402impl Render for ContextEditorToolbarItem {
4403 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4404 let left_side = h_flex()
4405 .pl_1()
4406 .gap_2()
4407 .flex_1()
4408 .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
4409 .when(self.active_context_editor.is_some(), |left_side| {
4410 left_side.child(self.model_summary_editor.clone())
4411 });
4412 let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
4413 let active_model = LanguageModelRegistry::read_global(cx).active_model();
4414 let weak_self = cx.view().downgrade();
4415 let right_side = h_flex()
4416 .gap_2()
4417 // TODO display this in a nicer way, once we have a design for it.
4418 // .children({
4419 // let project = self
4420 // .workspace
4421 // .upgrade()
4422 // .map(|workspace| workspace.read(cx).project().downgrade());
4423 //
4424 // let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
4425 // project.and_then(|project| db.remaining_summaries(&project, cx))
4426 // });
4427
4428 // scan_items_remaining
4429 // .map(|remaining_items| format!("Files to scan: {}", remaining_items))
4430 // })
4431 .child(
4432 ModelSelector::new(
4433 self.fs.clone(),
4434 ButtonLike::new("active-model")
4435 .style(ButtonStyle::Subtle)
4436 .child(
4437 h_flex()
4438 .w_full()
4439 .gap_0p5()
4440 .child(
4441 div()
4442 .overflow_x_hidden()
4443 .flex_grow()
4444 .whitespace_nowrap()
4445 .child(match (active_provider, active_model) {
4446 (Some(provider), Some(model)) => h_flex()
4447 .gap_1()
4448 .child(
4449 Icon::new(model.icon().unwrap_or_else(|| provider.icon()))
4450 .color(Color::Muted)
4451 .size(IconSize::XSmall),
4452 )
4453 .child(
4454 Label::new(model.name().0)
4455 .size(LabelSize::Small)
4456 .color(Color::Muted),
4457 )
4458 .into_any_element(),
4459 _ => Label::new("No model selected")
4460 .size(LabelSize::Small)
4461 .color(Color::Muted)
4462 .into_any_element(),
4463 }),
4464 )
4465 .child(
4466 Icon::new(IconName::ChevronDown)
4467 .color(Color::Muted)
4468 .size(IconSize::XSmall),
4469 ),
4470 )
4471 .tooltip(move |cx| {
4472 Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4473 }),
4474 )
4475 .with_handle(self.model_selector_menu_handle.clone()),
4476 )
4477 .children(self.render_remaining_tokens(cx))
4478 .child(
4479 PopoverMenu::new("context-editor-popover")
4480 .trigger(
4481 IconButton::new("context-editor-trigger", IconName::EllipsisVertical)
4482 .icon_size(IconSize::Small)
4483 .tooltip(|cx| Tooltip::text("Open Context Options", cx)),
4484 )
4485 .menu({
4486 let weak_self = weak_self.clone();
4487 move |cx| {
4488 let weak_self = weak_self.clone();
4489 Some(ContextMenu::build(cx, move |menu, cx| {
4490 let context = weak_self
4491 .update(cx, |this, cx| {
4492 active_editor_focus_handle(&this.workspace, cx)
4493 })
4494 .ok()
4495 .flatten();
4496 menu.when_some(context, |menu, context| menu.context(context))
4497 .entry("Regenerate Context Title", None, {
4498 let weak_self = weak_self.clone();
4499 move |cx| {
4500 weak_self
4501 .update(cx, |_, cx| {
4502 cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
4503 })
4504 .ok();
4505 }
4506 })
4507 .custom_entry(
4508 |_| {
4509 h_flex()
4510 .w_full()
4511 .justify_between()
4512 .gap_2()
4513 .child(Label::new("Insert Context"))
4514 .child(Label::new("/ command").color(Color::Muted))
4515 .into_any()
4516 },
4517 {
4518 let weak_self = weak_self.clone();
4519 move |cx| {
4520 weak_self
4521 .update(cx, |this, cx| {
4522 if let Some(editor) =
4523 &this.active_context_editor
4524 {
4525 editor
4526 .update(cx, |this, cx| {
4527 this.slash_menu_handle
4528 .toggle(cx);
4529 })
4530 .ok();
4531 }
4532 })
4533 .ok();
4534 }
4535 },
4536 )
4537 .action("Insert Selection", QuoteSelection.boxed_clone())
4538 }))
4539 }
4540 }),
4541 );
4542
4543 h_flex()
4544 .size_full()
4545 .gap_2()
4546 .justify_between()
4547 .child(left_side)
4548 .child(right_side)
4549 }
4550}
4551
4552impl ToolbarItemView for ContextEditorToolbarItem {
4553 fn set_active_pane_item(
4554 &mut self,
4555 active_pane_item: Option<&dyn ItemHandle>,
4556 cx: &mut ViewContext<Self>,
4557 ) -> ToolbarItemLocation {
4558 self.active_context_editor = active_pane_item
4559 .and_then(|item| item.act_as::<ContextEditor>(cx))
4560 .map(|editor| editor.downgrade());
4561 cx.notify();
4562 if self.active_context_editor.is_none() {
4563 ToolbarItemLocation::Hidden
4564 } else {
4565 ToolbarItemLocation::PrimaryRight
4566 }
4567 }
4568
4569 fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
4570 cx.notify();
4571 }
4572}
4573
4574impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
4575
4576enum ContextEditorToolbarItemEvent {
4577 RegenerateSummary,
4578}
4579impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
4580
4581pub struct ContextHistory {
4582 picker: View<Picker<SavedContextPickerDelegate>>,
4583 _subscriptions: Vec<Subscription>,
4584 assistant_panel: WeakView<AssistantPanel>,
4585}
4586
4587impl ContextHistory {
4588 fn new(
4589 project: Model<Project>,
4590 context_store: Model<ContextStore>,
4591 assistant_panel: WeakView<AssistantPanel>,
4592 cx: &mut ViewContext<Self>,
4593 ) -> Self {
4594 let picker = cx.new_view(|cx| {
4595 Picker::uniform_list(
4596 SavedContextPickerDelegate::new(project, context_store.clone()),
4597 cx,
4598 )
4599 .modal(false)
4600 .max_height(None)
4601 });
4602
4603 let _subscriptions = vec![
4604 cx.observe(&context_store, |this, _, cx| {
4605 this.picker.update(cx, |picker, cx| picker.refresh(cx));
4606 }),
4607 cx.subscribe(&picker, Self::handle_picker_event),
4608 ];
4609
4610 Self {
4611 picker,
4612 _subscriptions,
4613 assistant_panel,
4614 }
4615 }
4616
4617 fn handle_picker_event(
4618 &mut self,
4619 _: View<Picker<SavedContextPickerDelegate>>,
4620 event: &SavedContextPickerEvent,
4621 cx: &mut ViewContext<Self>,
4622 ) {
4623 let SavedContextPickerEvent::Confirmed(context) = event;
4624 self.assistant_panel
4625 .update(cx, |assistant_panel, cx| match context {
4626 ContextMetadata::Remote(metadata) => {
4627 assistant_panel
4628 .open_remote_context(metadata.id.clone(), cx)
4629 .detach_and_log_err(cx);
4630 }
4631 ContextMetadata::Saved(metadata) => {
4632 assistant_panel
4633 .open_saved_context(metadata.path.clone(), cx)
4634 .detach_and_log_err(cx);
4635 }
4636 })
4637 .ok();
4638 }
4639}
4640
4641#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4642pub enum WorkflowAssistStatus {
4643 Pending,
4644 Confirmed,
4645 Done,
4646 Idle,
4647}
4648
4649impl Render for ContextHistory {
4650 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
4651 div().size_full().child(self.picker.clone())
4652 }
4653}
4654
4655impl FocusableView for ContextHistory {
4656 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4657 self.picker.focus_handle(cx)
4658 }
4659}
4660
4661impl EventEmitter<()> for ContextHistory {}
4662
4663impl Item for ContextHistory {
4664 type Event = ();
4665
4666 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4667 Some("History".into())
4668 }
4669}
4670
4671pub struct ConfigurationView {
4672 focus_handle: FocusHandle,
4673 configuration_views: HashMap<LanguageModelProviderId, AnyView>,
4674 _registry_subscription: Subscription,
4675}
4676
4677impl ConfigurationView {
4678 fn new(cx: &mut ViewContext<Self>) -> Self {
4679 let focus_handle = cx.focus_handle();
4680
4681 let registry_subscription = cx.subscribe(
4682 &LanguageModelRegistry::global(cx),
4683 |this, _, event: &language_model::Event, cx| match event {
4684 language_model::Event::AddedProvider(provider_id) => {
4685 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
4686 if let Some(provider) = provider {
4687 this.add_configuration_view(&provider, cx);
4688 }
4689 }
4690 language_model::Event::RemovedProvider(provider_id) => {
4691 this.remove_configuration_view(provider_id);
4692 }
4693 _ => {}
4694 },
4695 );
4696
4697 let mut this = Self {
4698 focus_handle,
4699 configuration_views: HashMap::default(),
4700 _registry_subscription: registry_subscription,
4701 };
4702 this.build_configuration_views(cx);
4703 this
4704 }
4705
4706 fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
4707 let providers = LanguageModelRegistry::read_global(cx).providers();
4708 for provider in providers {
4709 self.add_configuration_view(&provider, cx);
4710 }
4711 }
4712
4713 fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
4714 self.configuration_views.remove(provider_id);
4715 }
4716
4717 fn add_configuration_view(
4718 &mut self,
4719 provider: &Arc<dyn LanguageModelProvider>,
4720 cx: &mut ViewContext<Self>,
4721 ) {
4722 let configuration_view = provider.configuration_view(cx);
4723 self.configuration_views
4724 .insert(provider.id(), configuration_view);
4725 }
4726
4727 fn render_provider_view(
4728 &mut self,
4729 provider: &Arc<dyn LanguageModelProvider>,
4730 cx: &mut ViewContext<Self>,
4731 ) -> Div {
4732 let provider_id = provider.id().0.clone();
4733 let provider_name = provider.name().0.clone();
4734 let configuration_view = self.configuration_views.get(&provider.id()).cloned();
4735
4736 let open_new_context = cx.listener({
4737 let provider = provider.clone();
4738 move |_, _, cx| {
4739 cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
4740 provider.clone(),
4741 ))
4742 }
4743 });
4744
4745 v_flex()
4746 .gap_2()
4747 .child(
4748 h_flex()
4749 .justify_between()
4750 .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
4751 .when(provider.is_authenticated(cx), move |this| {
4752 this.child(
4753 h_flex().justify_end().child(
4754 Button::new(
4755 SharedString::from(format!("new-context-{provider_id}")),
4756 "Open new context",
4757 )
4758 .icon_position(IconPosition::Start)
4759 .icon(IconName::Plus)
4760 .style(ButtonStyle::Filled)
4761 .layer(ElevationIndex::ModalSurface)
4762 .on_click(open_new_context),
4763 ),
4764 )
4765 }),
4766 )
4767 .child(
4768 div()
4769 .p(Spacing::Large.rems(cx))
4770 .bg(cx.theme().colors().surface_background)
4771 .border_1()
4772 .border_color(cx.theme().colors().border_variant)
4773 .rounded_md()
4774 .when(configuration_view.is_none(), |this| {
4775 this.child(div().child(Label::new(format!(
4776 "No configuration view for {}",
4777 provider_name
4778 ))))
4779 })
4780 .when_some(configuration_view, |this, configuration_view| {
4781 this.child(configuration_view)
4782 }),
4783 )
4784 }
4785}
4786
4787impl Render for ConfigurationView {
4788 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4789 let providers = LanguageModelRegistry::read_global(cx).providers();
4790 let provider_views = providers
4791 .into_iter()
4792 .map(|provider| self.render_provider_view(&provider, cx))
4793 .collect::<Vec<_>>();
4794
4795 let mut element = v_flex()
4796 .id("assistant-configuration-view")
4797 .track_focus(&self.focus_handle(cx))
4798 .bg(cx.theme().colors().editor_background)
4799 .size_full()
4800 .overflow_y_scroll()
4801 .child(
4802 v_flex()
4803 .p(Spacing::XXLarge.rems(cx))
4804 .border_b_1()
4805 .border_color(cx.theme().colors().border)
4806 .gap_1()
4807 .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
4808 .child(
4809 Label::new(
4810 "At least one LLM provider must be configured to use the Assistant.",
4811 )
4812 .color(Color::Muted),
4813 ),
4814 )
4815 .child(
4816 v_flex()
4817 .p(Spacing::XXLarge.rems(cx))
4818 .mt_1()
4819 .gap_6()
4820 .flex_1()
4821 .children(provider_views),
4822 )
4823 .into_any();
4824
4825 // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
4826 // because we couldn't the element to take up the size of the parent.
4827 canvas(
4828 move |bounds, cx| {
4829 element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
4830 element
4831 },
4832 |_, mut element, cx| {
4833 element.paint(cx);
4834 },
4835 )
4836 .flex_1()
4837 .w_full()
4838 }
4839}
4840
4841pub enum ConfigurationViewEvent {
4842 NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
4843}
4844
4845impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
4846
4847impl FocusableView for ConfigurationView {
4848 fn focus_handle(&self, _: &AppContext) -> FocusHandle {
4849 self.focus_handle.clone()
4850 }
4851}
4852
4853impl Item for ConfigurationView {
4854 type Event = ConfigurationViewEvent;
4855
4856 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4857 Some("Configuration".into())
4858 }
4859}
4860
4861type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
4862
4863fn render_slash_command_output_toggle(
4864 row: MultiBufferRow,
4865 is_folded: bool,
4866 fold: ToggleFold,
4867 _cx: &mut WindowContext,
4868) -> AnyElement {
4869 Disclosure::new(
4870 ("slash-command-output-fold-indicator", row.0 as u64),
4871 !is_folded,
4872 )
4873 .selected(is_folded)
4874 .on_click(move |_e, cx| fold(!is_folded, cx))
4875 .into_any_element()
4876}
4877
4878fn fold_toggle(
4879 name: &'static str,
4880) -> impl Fn(
4881 MultiBufferRow,
4882 bool,
4883 Arc<dyn Fn(bool, &mut WindowContext<'_>) + Send + Sync>,
4884 &mut WindowContext<'_>,
4885) -> AnyElement {
4886 move |row, is_folded, fold, _cx| {
4887 Disclosure::new((name, row.0 as u64), !is_folded)
4888 .selected(is_folded)
4889 .on_click(move |_e, cx| fold(!is_folded, cx))
4890 .into_any_element()
4891 }
4892}
4893
4894fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
4895 FoldPlaceholder {
4896 render: Arc::new({
4897 move |fold_id, fold_range, _cx| {
4898 let editor = editor.clone();
4899 ButtonLike::new(fold_id)
4900 .style(ButtonStyle::Filled)
4901 .layer(ElevationIndex::ElevatedSurface)
4902 .child(Icon::new(IconName::TextSnippet))
4903 .child(Label::new(title.clone()).single_line())
4904 .on_click(move |_, cx| {
4905 editor
4906 .update(cx, |editor, cx| {
4907 let buffer_start = fold_range
4908 .start
4909 .to_point(&editor.buffer().read(cx).read(cx));
4910 let buffer_row = MultiBufferRow(buffer_start.row);
4911 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4912 })
4913 .ok();
4914 })
4915 .into_any_element()
4916 }
4917 }),
4918 constrain_width: false,
4919 merge_adjacent: false,
4920 }
4921}
4922
4923fn render_quote_selection_output_toggle(
4924 row: MultiBufferRow,
4925 is_folded: bool,
4926 fold: ToggleFold,
4927 _cx: &mut WindowContext,
4928) -> AnyElement {
4929 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
4930 .selected(is_folded)
4931 .on_click(move |_e, cx| fold(!is_folded, cx))
4932 .into_any_element()
4933}
4934
4935fn render_pending_slash_command_gutter_decoration(
4936 row: MultiBufferRow,
4937 status: &PendingSlashCommandStatus,
4938 confirm_command: Arc<dyn Fn(&mut WindowContext)>,
4939) -> AnyElement {
4940 let mut icon = IconButton::new(
4941 ("slash-command-gutter-decoration", row.0),
4942 ui::IconName::TriangleRight,
4943 )
4944 .on_click(move |_e, cx| confirm_command(cx))
4945 .icon_size(ui::IconSize::Small)
4946 .size(ui::ButtonSize::None);
4947
4948 match status {
4949 PendingSlashCommandStatus::Idle => {
4950 icon = icon.icon_color(Color::Muted);
4951 }
4952 PendingSlashCommandStatus::Running { .. } => {
4953 icon = icon.selected(true);
4954 }
4955 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
4956 }
4957
4958 icon.into_any_element()
4959}
4960
4961fn render_docs_slash_command_trailer(
4962 row: MultiBufferRow,
4963 command: PendingSlashCommand,
4964 cx: &mut WindowContext,
4965) -> AnyElement {
4966 if command.arguments.is_empty() {
4967 return Empty.into_any();
4968 }
4969 let args = DocsSlashCommandArgs::parse(&command.arguments);
4970
4971 let Some(store) = args
4972 .provider()
4973 .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
4974 else {
4975 return Empty.into_any();
4976 };
4977
4978 let Some(package) = args.package() else {
4979 return Empty.into_any();
4980 };
4981
4982 let mut children = Vec::new();
4983
4984 if store.is_indexing(&package) {
4985 children.push(
4986 div()
4987 .id(("crates-being-indexed", row.0))
4988 .child(Icon::new(IconName::ArrowCircle).with_animation(
4989 "arrow-circle",
4990 Animation::new(Duration::from_secs(4)).repeat(),
4991 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4992 ))
4993 .tooltip({
4994 let package = package.clone();
4995 move |cx| Tooltip::text(format!("Indexing {package}…"), cx)
4996 })
4997 .into_any_element(),
4998 );
4999 }
5000
5001 if let Some(latest_error) = store.latest_error_for_package(&package) {
5002 children.push(
5003 div()
5004 .id(("latest-error", row.0))
5005 .child(
5006 Icon::new(IconName::Warning)
5007 .size(IconSize::Small)
5008 .color(Color::Warning),
5009 )
5010 .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
5011 .into_any_element(),
5012 )
5013 }
5014
5015 let is_indexing = store.is_indexing(&package);
5016 let latest_error = store.latest_error_for_package(&package);
5017
5018 if !is_indexing && latest_error.is_none() {
5019 return Empty.into_any();
5020 }
5021
5022 h_flex().gap_2().children(children).into_any_element()
5023}
5024
5025fn make_lsp_adapter_delegate(
5026 project: &Model<Project>,
5027 cx: &mut AppContext,
5028) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
5029 project.update(cx, |project, cx| {
5030 // TODO: Find the right worktree.
5031 let Some(worktree) = project.worktrees(cx).next() else {
5032 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
5033 };
5034 let http_client = project.client().http_client().clone();
5035 project.lsp_store().update(cx, |lsp_store, cx| {
5036 Ok(Some(LocalLspAdapterDelegate::new(
5037 lsp_store,
5038 &worktree,
5039 http_client,
5040 project.fs().clone(),
5041 cx,
5042 ) as Arc<dyn LspAdapterDelegate>))
5043 })
5044 })
5045}
5046
5047fn slash_command_error_block_renderer(message: String) -> RenderBlock {
5048 Box::new(move |_| {
5049 div()
5050 .pl_6()
5051 .child(
5052 Label::new(format!("error: {}", message))
5053 .single_line()
5054 .color(Color::Error),
5055 )
5056 .into_any()
5057 })
5058}
5059
5060enum TokenState {
5061 NoTokensLeft {
5062 max_token_count: usize,
5063 token_count: usize,
5064 },
5065 HasMoreTokens {
5066 max_token_count: usize,
5067 token_count: usize,
5068 over_warn_threshold: bool,
5069 },
5070}
5071
5072fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
5073 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
5074
5075 let model = LanguageModelRegistry::read_global(cx).active_model()?;
5076 let token_count = context.read(cx).token_count()?;
5077 let max_token_count = model.max_token_count();
5078
5079 let remaining_tokens = max_token_count as isize - token_count as isize;
5080 let token_state = if remaining_tokens <= 0 {
5081 TokenState::NoTokensLeft {
5082 max_token_count,
5083 token_count,
5084 }
5085 } else {
5086 let over_warn_threshold =
5087 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
5088 TokenState::HasMoreTokens {
5089 max_token_count,
5090 token_count,
5091 over_warn_threshold,
5092 }
5093 };
5094 Some(token_state)
5095}
5096
5097fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
5098 let image_size = data
5099 .size(0)
5100 .map(|dimension| Pixels::from(u32::from(dimension)));
5101 let image_ratio = image_size.width / image_size.height;
5102 let bounds_ratio = max_size.width / max_size.height;
5103
5104 if image_size.width > max_size.width || image_size.height > max_size.height {
5105 if bounds_ratio > image_ratio {
5106 size(
5107 image_size.width * (max_size.height / image_size.height),
5108 max_size.height,
5109 )
5110 } else {
5111 size(
5112 max_size.width,
5113 image_size.height * (max_size.width / image_size.width),
5114 )
5115 }
5116 } else {
5117 size(image_size.width, image_size.height)
5118 }
5119}
5120
5121enum ConfigurationError {
5122 NoProvider,
5123 ProviderNotAuthenticated,
5124}
5125
5126fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
5127 let provider = LanguageModelRegistry::read_global(cx).active_provider();
5128 let is_authenticated = provider
5129 .as_ref()
5130 .map_or(false, |provider| provider.is_authenticated(cx));
5131
5132 if provider.is_some() && is_authenticated {
5133 return None;
5134 }
5135
5136 if provider.is_none() {
5137 return Some(ConfigurationError::NoProvider);
5138 }
5139
5140 if !is_authenticated {
5141 return Some(ConfigurationError::ProviderNotAuthenticated);
5142 }
5143
5144 None
5145}
5146
5147#[cfg(test)]
5148mod tests {
5149 use super::*;
5150 use gpui::{AppContext, Context};
5151 use language::Buffer;
5152 use unindent::Unindent;
5153
5154 #[gpui::test]
5155 fn test_find_code_blocks(cx: &mut AppContext) {
5156 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
5157
5158 let buffer = cx.new_model(|cx| {
5159 let text = r#"
5160 line 0
5161 line 1
5162 ```rust
5163 fn main() {}
5164 ```
5165 line 5
5166 line 6
5167 line 7
5168 ```go
5169 func main() {}
5170 ```
5171 line 11
5172 ```
5173 this is plain text code block
5174 ```
5175
5176 ```go
5177 func another() {}
5178 ```
5179 line 19
5180 "#
5181 .unindent();
5182 let mut buffer = Buffer::local(text, cx);
5183 buffer.set_language(Some(markdown.clone()), cx);
5184 buffer
5185 });
5186 let snapshot = buffer.read(cx).snapshot();
5187
5188 let code_blocks = vec![
5189 Point::new(3, 0)..Point::new(4, 0),
5190 Point::new(9, 0)..Point::new(10, 0),
5191 Point::new(13, 0)..Point::new(14, 0),
5192 Point::new(17, 0)..Point::new(18, 0),
5193 ]
5194 .into_iter()
5195 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
5196 .collect::<Vec<_>>();
5197
5198 let expected_results = vec![
5199 (0, None),
5200 (1, None),
5201 (2, Some(code_blocks[0].clone())),
5202 (3, Some(code_blocks[0].clone())),
5203 (4, Some(code_blocks[0].clone())),
5204 (5, None),
5205 (6, None),
5206 (7, None),
5207 (8, Some(code_blocks[1].clone())),
5208 (9, Some(code_blocks[1].clone())),
5209 (10, Some(code_blocks[1].clone())),
5210 (11, None),
5211 (12, Some(code_blocks[2].clone())),
5212 (13, Some(code_blocks[2].clone())),
5213 (14, Some(code_blocks[2].clone())),
5214 (15, None),
5215 (16, Some(code_blocks[3].clone())),
5216 (17, Some(code_blocks[3].clone())),
5217 (18, Some(code_blocks[3].clone())),
5218 (19, None),
5219 ];
5220
5221 for (row, expected) in expected_results {
5222 let offset = snapshot.point_to_offset(Point::new(row, 0));
5223 let range = find_surrounding_code_block(&snapshot, offset);
5224 assert_eq!(range, expected, "unexpected result on row {:?}", row);
5225 }
5226 }
5227}