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