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