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 crease_id: CreaseId,
1484 editor: Option<PatchEditorState>,
1485 update_task: Option<Task<()>>,
1486}
1487
1488struct PatchEditorState {
1489 editor: WeakView<ProposedChangesEditor>,
1490 opened_patch: AssistantPatch,
1491}
1492
1493type MessageHeader = MessageMetadata;
1494
1495#[derive(Clone)]
1496enum AssistError {
1497 FileRequired,
1498 PaymentRequired,
1499 MaxMonthlySpendReached,
1500 Message(SharedString),
1501}
1502
1503pub struct ContextEditor {
1504 context: Model<Context>,
1505 fs: Arc<dyn Fs>,
1506 slash_commands: Arc<SlashCommandWorkingSet>,
1507 tools: Arc<ToolWorkingSet>,
1508 workspace: WeakView<Workspace>,
1509 project: Model<Project>,
1510 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1511 editor: View<Editor>,
1512 blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
1513 image_blocks: HashSet<CustomBlockId>,
1514 scroll_position: Option<ScrollPosition>,
1515 remote_id: Option<workspace::ViewId>,
1516 pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
1517 invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
1518 pending_tool_use_creases: HashMap<Range<language::Anchor>, CreaseId>,
1519 _subscriptions: Vec<Subscription>,
1520 patches: HashMap<Range<language::Anchor>, PatchViewState>,
1521 active_patch: Option<Range<language::Anchor>>,
1522 assistant_panel: WeakView<AssistantPanel>,
1523 last_error: Option<AssistError>,
1524 show_accept_terms: bool,
1525 pub(crate) slash_menu_handle:
1526 PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
1527 // dragged_file_worktrees is used to keep references to worktrees that were added
1528 // when the user drag/dropped an external file onto the context editor. Since
1529 // the worktree is not part of the project panel, it would be dropped as soon as
1530 // the file is opened. In order to keep the worktree alive for the duration of the
1531 // context editor, we keep a reference here.
1532 dragged_file_worktrees: Vec<Model<Worktree>>,
1533}
1534
1535const DEFAULT_TAB_TITLE: &str = "New Chat";
1536const MAX_TAB_TITLE_LEN: usize = 16;
1537
1538impl ContextEditor {
1539 fn for_context(
1540 context: Model<Context>,
1541 fs: Arc<dyn Fs>,
1542 workspace: WeakView<Workspace>,
1543 project: Model<Project>,
1544 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
1545 assistant_panel: WeakView<AssistantPanel>,
1546 cx: &mut ViewContext<Self>,
1547 ) -> Self {
1548 let completion_provider = SlashCommandCompletionProvider::new(
1549 context.read(cx).slash_commands.clone(),
1550 Some(cx.view().downgrade()),
1551 Some(workspace.clone()),
1552 );
1553
1554 let editor = cx.new_view(|cx| {
1555 let mut editor = Editor::for_buffer(context.read(cx).buffer().clone(), None, cx);
1556 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
1557 editor.set_show_line_numbers(false, cx);
1558 editor.set_show_git_diff_gutter(false, cx);
1559 editor.set_show_code_actions(false, cx);
1560 editor.set_show_runnables(false, cx);
1561 editor.set_show_wrap_guides(false, cx);
1562 editor.set_show_indent_guides(false, cx);
1563 editor.set_completion_provider(Some(Box::new(completion_provider)));
1564 editor.set_collaboration_hub(Box::new(project.clone()));
1565 editor
1566 });
1567
1568 let _subscriptions = vec![
1569 cx.observe(&context, |_, _, cx| cx.notify()),
1570 cx.subscribe(&context, Self::handle_context_event),
1571 cx.subscribe(&editor, Self::handle_editor_event),
1572 cx.subscribe(&editor, Self::handle_editor_search_event),
1573 ];
1574
1575 let sections = context.read(cx).slash_command_output_sections().to_vec();
1576 let patch_ranges = context.read(cx).patch_ranges().collect::<Vec<_>>();
1577 let slash_commands = context.read(cx).slash_commands.clone();
1578 let tools = context.read(cx).tools.clone();
1579 let mut this = Self {
1580 context,
1581 slash_commands,
1582 tools,
1583 editor,
1584 lsp_adapter_delegate,
1585 blocks: Default::default(),
1586 image_blocks: Default::default(),
1587 scroll_position: None,
1588 remote_id: None,
1589 fs,
1590 workspace,
1591 project,
1592 pending_slash_command_creases: HashMap::default(),
1593 invoked_slash_command_creases: HashMap::default(),
1594 pending_tool_use_creases: HashMap::default(),
1595 _subscriptions,
1596 patches: HashMap::default(),
1597 active_patch: None,
1598 assistant_panel,
1599 last_error: None,
1600 show_accept_terms: false,
1601 slash_menu_handle: Default::default(),
1602 dragged_file_worktrees: Vec::new(),
1603 };
1604 this.update_message_headers(cx);
1605 this.update_image_blocks(cx);
1606 this.insert_slash_command_output_sections(sections, false, cx);
1607 this.patches_updated(&Vec::new(), &patch_ranges, cx);
1608 this
1609 }
1610
1611 fn insert_default_prompt(&mut self, cx: &mut ViewContext<Self>) {
1612 let command_name = DefaultSlashCommand.name();
1613 self.editor.update(cx, |editor, cx| {
1614 editor.insert(&format!("/{command_name}\n\n"), cx)
1615 });
1616 let command = self.context.update(cx, |context, cx| {
1617 context.reparse(cx);
1618 context.parsed_slash_commands()[0].clone()
1619 });
1620 self.run_command(
1621 command.source_range,
1622 &command.name,
1623 &command.arguments,
1624 false,
1625 self.workspace.clone(),
1626 cx,
1627 );
1628 }
1629
1630 fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
1631 self.send_to_model(RequestType::Chat, cx);
1632 }
1633
1634 fn edit(&mut self, _: &Edit, cx: &mut ViewContext<Self>) {
1635 self.send_to_model(RequestType::SuggestEdits, cx);
1636 }
1637
1638 fn focus_active_patch(&mut self, cx: &mut ViewContext<Self>) -> bool {
1639 if let Some((_range, patch)) = self.active_patch() {
1640 if let Some(editor) = patch
1641 .editor
1642 .as_ref()
1643 .and_then(|state| state.editor.upgrade())
1644 {
1645 cx.focus_view(&editor);
1646 return true;
1647 }
1648 }
1649
1650 false
1651 }
1652
1653 fn send_to_model(&mut self, request_type: RequestType, cx: &mut ViewContext<Self>) {
1654 let provider = LanguageModelRegistry::read_global(cx).active_provider();
1655 if provider
1656 .as_ref()
1657 .map_or(false, |provider| provider.must_accept_terms(cx))
1658 {
1659 self.show_accept_terms = true;
1660 cx.notify();
1661 return;
1662 }
1663
1664 if self.focus_active_patch(cx) {
1665 return;
1666 }
1667
1668 self.last_error = None;
1669
1670 if request_type == RequestType::SuggestEdits && !self.context.read(cx).contains_files(cx) {
1671 self.last_error = Some(AssistError::FileRequired);
1672 cx.notify();
1673 } else if let Some(user_message) = self
1674 .context
1675 .update(cx, |context, cx| context.assist(request_type, cx))
1676 {
1677 let new_selection = {
1678 let cursor = user_message
1679 .start
1680 .to_offset(self.context.read(cx).buffer().read(cx));
1681 cursor..cursor
1682 };
1683 self.editor.update(cx, |editor, cx| {
1684 editor.change_selections(
1685 Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
1686 cx,
1687 |selections| selections.select_ranges([new_selection]),
1688 );
1689 });
1690 // Avoid scrolling to the new cursor position so the assistant's output is stable.
1691 cx.defer(|this, _| this.scroll_position = None);
1692 }
1693
1694 cx.notify();
1695 }
1696
1697 fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1698 self.last_error = None;
1699
1700 if self
1701 .context
1702 .update(cx, |context, cx| context.cancel_last_assist(cx))
1703 {
1704 return;
1705 }
1706
1707 cx.propagate();
1708 }
1709
1710 fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
1711 let cursors = self.cursors(cx);
1712 self.context.update(cx, |context, cx| {
1713 let messages = context
1714 .messages_for_offsets(cursors, cx)
1715 .into_iter()
1716 .map(|message| message.id)
1717 .collect();
1718 context.cycle_message_roles(messages, cx)
1719 });
1720 }
1721
1722 fn cursors(&self, cx: &mut WindowContext) -> Vec<usize> {
1723 let selections = self
1724 .editor
1725 .update(cx, |editor, cx| editor.selections.all::<usize>(cx));
1726 selections
1727 .into_iter()
1728 .map(|selection| selection.head())
1729 .collect()
1730 }
1731
1732 pub fn insert_command(&mut self, name: &str, cx: &mut ViewContext<Self>) {
1733 if let Some(command) = self.slash_commands.command(name, cx) {
1734 self.editor.update(cx, |editor, cx| {
1735 editor.transact(cx, |editor, cx| {
1736 editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel());
1737 let snapshot = editor.buffer().read(cx).snapshot(cx);
1738 let newest_cursor = editor.selections.newest::<Point>(cx).head();
1739 if newest_cursor.column > 0
1740 || snapshot
1741 .chars_at(newest_cursor)
1742 .next()
1743 .map_or(false, |ch| ch != '\n')
1744 {
1745 editor.move_to_end_of_line(
1746 &MoveToEndOfLine {
1747 stop_at_soft_wraps: false,
1748 },
1749 cx,
1750 );
1751 editor.newline(&Newline, cx);
1752 }
1753
1754 editor.insert(&format!("/{name}"), cx);
1755 if command.accepts_arguments() {
1756 editor.insert(" ", cx);
1757 editor.show_completions(&ShowCompletions::default(), cx);
1758 }
1759 });
1760 });
1761 if !command.requires_argument() {
1762 self.confirm_command(&ConfirmCommand, cx);
1763 }
1764 }
1765 }
1766
1767 pub fn confirm_command(&mut self, _: &ConfirmCommand, cx: &mut ViewContext<Self>) {
1768 if self.editor.read(cx).has_active_completions_menu() {
1769 return;
1770 }
1771
1772 let selections = self.editor.read(cx).selections.disjoint_anchors();
1773 let mut commands_by_range = HashMap::default();
1774 let workspace = self.workspace.clone();
1775 self.context.update(cx, |context, cx| {
1776 context.reparse(cx);
1777 for selection in selections.iter() {
1778 if let Some(command) =
1779 context.pending_command_for_position(selection.head().text_anchor, cx)
1780 {
1781 commands_by_range
1782 .entry(command.source_range.clone())
1783 .or_insert_with(|| command.clone());
1784 }
1785 }
1786 });
1787
1788 if commands_by_range.is_empty() {
1789 cx.propagate();
1790 } else {
1791 for command in commands_by_range.into_values() {
1792 self.run_command(
1793 command.source_range,
1794 &command.name,
1795 &command.arguments,
1796 true,
1797 workspace.clone(),
1798 cx,
1799 );
1800 }
1801 cx.stop_propagation();
1802 }
1803 }
1804
1805 #[allow(clippy::too_many_arguments)]
1806 pub fn run_command(
1807 &mut self,
1808 command_range: Range<language::Anchor>,
1809 name: &str,
1810 arguments: &[String],
1811 ensure_trailing_newline: bool,
1812 workspace: WeakView<Workspace>,
1813 cx: &mut ViewContext<Self>,
1814 ) {
1815 if let Some(command) = self.slash_commands.command(name, cx) {
1816 let context = self.context.read(cx);
1817 let sections = context
1818 .slash_command_output_sections()
1819 .into_iter()
1820 .filter(|section| section.is_valid(context.buffer().read(cx)))
1821 .cloned()
1822 .collect::<Vec<_>>();
1823 let snapshot = context.buffer().read(cx).snapshot();
1824 let output = command.run(
1825 arguments,
1826 §ions,
1827 snapshot,
1828 workspace,
1829 self.lsp_adapter_delegate.clone(),
1830 cx,
1831 );
1832 self.context.update(cx, |context, cx| {
1833 context.insert_command_output(
1834 command_range,
1835 name,
1836 output,
1837 ensure_trailing_newline,
1838 cx,
1839 )
1840 });
1841 }
1842 }
1843
1844 fn handle_context_event(
1845 &mut self,
1846 _: Model<Context>,
1847 event: &ContextEvent,
1848 cx: &mut ViewContext<Self>,
1849 ) {
1850 let context_editor = cx.view().downgrade();
1851
1852 match event {
1853 ContextEvent::MessagesEdited => {
1854 self.update_message_headers(cx);
1855 self.update_image_blocks(cx);
1856 self.context.update(cx, |context, cx| {
1857 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1858 });
1859 }
1860 ContextEvent::SummaryChanged => {
1861 cx.emit(EditorEvent::TitleChanged);
1862 self.context.update(cx, |context, cx| {
1863 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
1864 });
1865 }
1866 ContextEvent::StreamedCompletion => {
1867 self.editor.update(cx, |editor, cx| {
1868 if let Some(scroll_position) = self.scroll_position {
1869 let snapshot = editor.snapshot(cx);
1870 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
1871 let scroll_top =
1872 cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
1873 editor.set_scroll_position(
1874 point(scroll_position.offset_before_cursor.x, scroll_top),
1875 cx,
1876 );
1877 }
1878
1879 let new_tool_uses = self
1880 .context
1881 .read(cx)
1882 .pending_tool_uses()
1883 .into_iter()
1884 .filter(|tool_use| {
1885 !self
1886 .pending_tool_use_creases
1887 .contains_key(&tool_use.source_range)
1888 })
1889 .cloned()
1890 .collect::<Vec<_>>();
1891
1892 let buffer = editor.buffer().read(cx).snapshot(cx);
1893 let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
1894 let excerpt_id = *excerpt_id;
1895
1896 let mut buffer_rows_to_fold = BTreeSet::new();
1897
1898 let creases = new_tool_uses
1899 .iter()
1900 .map(|tool_use| {
1901 let placeholder = FoldPlaceholder {
1902 render: render_fold_icon_button(
1903 cx.view().downgrade(),
1904 IconName::PocketKnife,
1905 tool_use.name.clone().into(),
1906 ),
1907 ..Default::default()
1908 };
1909 let render_trailer =
1910 move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
1911
1912 let start = buffer
1913 .anchor_in_excerpt(excerpt_id, tool_use.source_range.start)
1914 .unwrap();
1915 let end = buffer
1916 .anchor_in_excerpt(excerpt_id, tool_use.source_range.end)
1917 .unwrap();
1918
1919 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1920 buffer_rows_to_fold.insert(buffer_row);
1921
1922 self.context.update(cx, |context, cx| {
1923 context.insert_content(
1924 Content::ToolUse {
1925 range: tool_use.source_range.clone(),
1926 tool_use: LanguageModelToolUse {
1927 id: tool_use.id.to_string(),
1928 name: tool_use.name.clone(),
1929 input: tool_use.input.clone(),
1930 },
1931 },
1932 cx,
1933 );
1934 });
1935
1936 Crease::inline(
1937 start..end,
1938 placeholder,
1939 fold_toggle("tool-use"),
1940 render_trailer,
1941 )
1942 })
1943 .collect::<Vec<_>>();
1944
1945 let crease_ids = editor.insert_creases(creases, cx);
1946
1947 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1948 editor.fold_at(&FoldAt { buffer_row }, cx);
1949 }
1950
1951 self.pending_tool_use_creases.extend(
1952 new_tool_uses
1953 .iter()
1954 .map(|tool_use| tool_use.source_range.clone())
1955 .zip(crease_ids),
1956 );
1957 });
1958 }
1959 ContextEvent::PatchesUpdated { removed, updated } => {
1960 self.patches_updated(removed, updated, cx);
1961 }
1962 ContextEvent::ParsedSlashCommandsUpdated { removed, updated } => {
1963 self.editor.update(cx, |editor, cx| {
1964 let buffer = editor.buffer().read(cx).snapshot(cx);
1965 let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
1966
1967 editor.remove_creases(
1968 removed
1969 .iter()
1970 .filter_map(|range| self.pending_slash_command_creases.remove(range)),
1971 cx,
1972 );
1973
1974 let crease_ids = editor.insert_creases(
1975 updated.iter().map(|command| {
1976 let workspace = self.workspace.clone();
1977 let confirm_command = Arc::new({
1978 let context_editor = context_editor.clone();
1979 let command = command.clone();
1980 move |cx: &mut WindowContext| {
1981 context_editor
1982 .update(cx, |context_editor, cx| {
1983 context_editor.run_command(
1984 command.source_range.clone(),
1985 &command.name,
1986 &command.arguments,
1987 false,
1988 workspace.clone(),
1989 cx,
1990 );
1991 })
1992 .ok();
1993 }
1994 });
1995 let placeholder = FoldPlaceholder {
1996 render: Arc::new(move |_, _, _| Empty.into_any()),
1997 ..Default::default()
1998 };
1999 let render_toggle = {
2000 let confirm_command = confirm_command.clone();
2001 let command = command.clone();
2002 move |row, _, _, _cx: &mut WindowContext| {
2003 render_pending_slash_command_gutter_decoration(
2004 row,
2005 &command.status,
2006 confirm_command.clone(),
2007 )
2008 }
2009 };
2010 let render_trailer = {
2011 let command = command.clone();
2012 move |row, _unfold, cx: &mut WindowContext| {
2013 // TODO: In the future we should investigate how we can expose
2014 // this as a hook on the `SlashCommand` trait so that we don't
2015 // need to special-case it here.
2016 if command.name == DocsSlashCommand::NAME {
2017 return render_docs_slash_command_trailer(
2018 row,
2019 command.clone(),
2020 cx,
2021 );
2022 }
2023
2024 Empty.into_any()
2025 }
2026 };
2027
2028 let start = buffer
2029 .anchor_in_excerpt(excerpt_id, command.source_range.start)
2030 .unwrap();
2031 let end = buffer
2032 .anchor_in_excerpt(excerpt_id, command.source_range.end)
2033 .unwrap();
2034 Crease::inline(start..end, placeholder, render_toggle, render_trailer)
2035 }),
2036 cx,
2037 );
2038
2039 self.pending_slash_command_creases.extend(
2040 updated
2041 .iter()
2042 .map(|command| command.source_range.clone())
2043 .zip(crease_ids),
2044 );
2045 })
2046 }
2047 ContextEvent::InvokedSlashCommandChanged { command_id } => {
2048 self.update_invoked_slash_command(*command_id, cx);
2049 }
2050 ContextEvent::SlashCommandOutputSectionAdded { section } => {
2051 self.insert_slash_command_output_sections([section.clone()], false, cx);
2052 }
2053 ContextEvent::UsePendingTools => {
2054 let pending_tool_uses = self
2055 .context
2056 .read(cx)
2057 .pending_tool_uses()
2058 .into_iter()
2059 .filter(|tool_use| tool_use.status.is_idle())
2060 .cloned()
2061 .collect::<Vec<_>>();
2062
2063 for tool_use in pending_tool_uses {
2064 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
2065 let task = tool.run(tool_use.input, self.workspace.clone(), cx);
2066
2067 self.context.update(cx, |context, cx| {
2068 context.insert_tool_output(tool_use.id.clone(), task, cx);
2069 });
2070 }
2071 }
2072 }
2073 ContextEvent::ToolFinished {
2074 tool_use_id,
2075 output_range,
2076 } => {
2077 self.editor.update(cx, |editor, cx| {
2078 let buffer = editor.buffer().read(cx).snapshot(cx);
2079 let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
2080 let excerpt_id = *excerpt_id;
2081
2082 let placeholder = FoldPlaceholder {
2083 render: render_fold_icon_button(
2084 cx.view().downgrade(),
2085 IconName::PocketKnife,
2086 format!("Tool Result: {tool_use_id}").into(),
2087 ),
2088 ..Default::default()
2089 };
2090 let render_trailer =
2091 move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
2092
2093 let start = buffer
2094 .anchor_in_excerpt(excerpt_id, output_range.start)
2095 .unwrap();
2096 let end = buffer
2097 .anchor_in_excerpt(excerpt_id, output_range.end)
2098 .unwrap();
2099
2100 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2101
2102 let crease = Crease::inline(
2103 start..end,
2104 placeholder,
2105 fold_toggle("tool-use"),
2106 render_trailer,
2107 );
2108
2109 editor.insert_creases([crease], cx);
2110 editor.fold_at(&FoldAt { buffer_row }, cx);
2111 });
2112 }
2113 ContextEvent::Operation(_) => {}
2114 ContextEvent::ShowAssistError(error_message) => {
2115 self.last_error = Some(AssistError::Message(error_message.clone()));
2116 }
2117 ContextEvent::ShowPaymentRequiredError => {
2118 self.last_error = Some(AssistError::PaymentRequired);
2119 }
2120 ContextEvent::ShowMaxMonthlySpendReachedError => {
2121 self.last_error = Some(AssistError::MaxMonthlySpendReached);
2122 }
2123 }
2124 }
2125
2126 fn update_invoked_slash_command(
2127 &mut self,
2128 command_id: InvokedSlashCommandId,
2129 cx: &mut ViewContext<Self>,
2130 ) {
2131 if let Some(invoked_slash_command) =
2132 self.context.read(cx).invoked_slash_command(&command_id)
2133 {
2134 if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
2135 let run_commands_in_ranges = invoked_slash_command
2136 .run_commands_in_ranges
2137 .iter()
2138 .cloned()
2139 .collect::<Vec<_>>();
2140 for range in run_commands_in_ranges {
2141 let commands = self.context.update(cx, |context, cx| {
2142 context.reparse(cx);
2143 context
2144 .pending_commands_for_range(range.clone(), cx)
2145 .to_vec()
2146 });
2147
2148 for command in commands {
2149 self.run_command(
2150 command.source_range,
2151 &command.name,
2152 &command.arguments,
2153 false,
2154 self.workspace.clone(),
2155 cx,
2156 );
2157 }
2158 }
2159 }
2160 }
2161
2162 self.editor.update(cx, |editor, cx| {
2163 if let Some(invoked_slash_command) =
2164 self.context.read(cx).invoked_slash_command(&command_id)
2165 {
2166 if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
2167 let buffer = editor.buffer().read(cx).snapshot(cx);
2168 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
2169 buffer.as_singleton().unwrap();
2170
2171 let start = buffer
2172 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.start)
2173 .unwrap();
2174 let end = buffer
2175 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.end)
2176 .unwrap();
2177 editor.remove_folds_with_type(
2178 &[start..end],
2179 TypeId::of::<PendingSlashCommand>(),
2180 false,
2181 cx,
2182 );
2183
2184 editor.remove_creases(
2185 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
2186 cx,
2187 );
2188 } else if let hash_map::Entry::Vacant(entry) =
2189 self.invoked_slash_command_creases.entry(command_id)
2190 {
2191 let buffer = editor.buffer().read(cx).snapshot(cx);
2192 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
2193 buffer.as_singleton().unwrap();
2194 let context = self.context.downgrade();
2195 let crease_start = buffer
2196 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.start)
2197 .unwrap();
2198 let crease_end = buffer
2199 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.end)
2200 .unwrap();
2201 let crease = Crease::inline(
2202 crease_start..crease_end,
2203 invoked_slash_command_fold_placeholder(command_id, context),
2204 fold_toggle("invoked-slash-command"),
2205 |_row, _folded, _cx| Empty.into_any(),
2206 );
2207 let crease_ids = editor.insert_creases([crease.clone()], cx);
2208 editor.fold_creases(vec![crease], false, cx);
2209 entry.insert(crease_ids[0]);
2210 } else {
2211 cx.notify()
2212 }
2213 } else {
2214 editor.remove_creases(
2215 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
2216 cx,
2217 );
2218 cx.notify();
2219 };
2220 });
2221 }
2222
2223 fn patches_updated(
2224 &mut self,
2225 removed: &Vec<Range<text::Anchor>>,
2226 updated: &Vec<Range<text::Anchor>>,
2227 cx: &mut ViewContext<ContextEditor>,
2228 ) {
2229 let this = cx.view().downgrade();
2230 let mut editors_to_close = Vec::new();
2231
2232 self.editor.update(cx, |editor, cx| {
2233 let snapshot = editor.snapshot(cx);
2234 let multibuffer = &snapshot.buffer_snapshot;
2235 let (&excerpt_id, _, _) = multibuffer.as_singleton().unwrap();
2236
2237 let mut removed_crease_ids = Vec::new();
2238 let mut ranges_to_unfold: Vec<Range<Anchor>> = Vec::new();
2239 for range in removed {
2240 if let Some(state) = self.patches.remove(range) {
2241 let patch_start = multibuffer
2242 .anchor_in_excerpt(excerpt_id, range.start)
2243 .unwrap();
2244 let patch_end = multibuffer
2245 .anchor_in_excerpt(excerpt_id, range.end)
2246 .unwrap();
2247
2248 editors_to_close.extend(state.editor.and_then(|state| state.editor.upgrade()));
2249 ranges_to_unfold.push(patch_start..patch_end);
2250 removed_crease_ids.push(state.crease_id);
2251 }
2252 }
2253 editor.unfold_ranges(&ranges_to_unfold, true, false, cx);
2254 editor.remove_creases(removed_crease_ids, cx);
2255
2256 for range in updated {
2257 let Some(patch) = self.context.read(cx).patch_for_range(&range, cx).cloned() else {
2258 continue;
2259 };
2260
2261 let path_count = patch.path_count();
2262 let patch_start = multibuffer
2263 .anchor_in_excerpt(excerpt_id, patch.range.start)
2264 .unwrap();
2265 let patch_end = multibuffer
2266 .anchor_in_excerpt(excerpt_id, patch.range.end)
2267 .unwrap();
2268 let render_block: RenderBlock = Arc::new({
2269 let this = this.clone();
2270 let patch_range = range.clone();
2271 move |cx: &mut BlockContext<'_, '_>| {
2272 let max_width = cx.max_width;
2273 let gutter_width = cx.gutter_dimensions.full_width();
2274 let block_id = cx.block_id;
2275 let selected = cx.selected;
2276 this.update(&mut **cx, |this, cx| {
2277 this.render_patch_block(
2278 patch_range.clone(),
2279 max_width,
2280 gutter_width,
2281 block_id,
2282 selected,
2283 cx,
2284 )
2285 })
2286 .ok()
2287 .flatten()
2288 .unwrap_or_else(|| Empty.into_any())
2289 }
2290 });
2291
2292 let height = path_count as u32 + 1;
2293 let crease = Crease::block(
2294 patch_start..patch_end,
2295 height,
2296 BlockStyle::Flex,
2297 render_block.clone(),
2298 );
2299
2300 let should_refold;
2301 if let Some(state) = self.patches.get_mut(&range) {
2302 if let Some(editor_state) = &state.editor {
2303 if editor_state.opened_patch != patch {
2304 state.update_task = Some({
2305 let this = this.clone();
2306 cx.spawn(|_, cx| async move {
2307 Self::update_patch_editor(this.clone(), patch, cx)
2308 .await
2309 .log_err();
2310 })
2311 });
2312 }
2313 }
2314
2315 should_refold =
2316 snapshot.intersects_fold(patch_start.to_offset(&snapshot.buffer_snapshot));
2317 } else {
2318 let crease_id = editor.insert_creases([crease.clone()], cx)[0];
2319 self.patches.insert(
2320 range.clone(),
2321 PatchViewState {
2322 crease_id,
2323 editor: None,
2324 update_task: None,
2325 },
2326 );
2327
2328 should_refold = true;
2329 }
2330
2331 if should_refold {
2332 editor.unfold_ranges(&[patch_start..patch_end], true, false, cx);
2333 editor.fold_creases(vec![crease], false, cx);
2334 }
2335 }
2336 });
2337
2338 for editor in editors_to_close {
2339 self.close_patch_editor(editor, cx);
2340 }
2341
2342 self.update_active_patch(cx);
2343 }
2344
2345 fn insert_slash_command_output_sections(
2346 &mut self,
2347 sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
2348 expand_result: bool,
2349 cx: &mut ViewContext<Self>,
2350 ) {
2351 self.editor.update(cx, |editor, cx| {
2352 let buffer = editor.buffer().read(cx).snapshot(cx);
2353 let excerpt_id = *buffer.as_singleton().unwrap().0;
2354 let mut buffer_rows_to_fold = BTreeSet::new();
2355 let mut creases = Vec::new();
2356 for section in sections {
2357 let start = buffer
2358 .anchor_in_excerpt(excerpt_id, section.range.start)
2359 .unwrap();
2360 let end = buffer
2361 .anchor_in_excerpt(excerpt_id, section.range.end)
2362 .unwrap();
2363 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2364 buffer_rows_to_fold.insert(buffer_row);
2365 creases.push(
2366 Crease::inline(
2367 start..end,
2368 FoldPlaceholder {
2369 render: render_fold_icon_button(
2370 cx.view().downgrade(),
2371 section.icon,
2372 section.label.clone(),
2373 ),
2374 merge_adjacent: false,
2375 ..Default::default()
2376 },
2377 render_slash_command_output_toggle,
2378 |_, _, _| Empty.into_any_element(),
2379 )
2380 .with_metadata(CreaseMetadata {
2381 icon: section.icon,
2382 label: section.label,
2383 }),
2384 );
2385 }
2386
2387 editor.insert_creases(creases, cx);
2388
2389 if expand_result {
2390 buffer_rows_to_fold.clear();
2391 }
2392 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2393 editor.fold_at(&FoldAt { buffer_row }, cx);
2394 }
2395 });
2396 }
2397
2398 fn handle_editor_event(
2399 &mut self,
2400 _: View<Editor>,
2401 event: &EditorEvent,
2402 cx: &mut ViewContext<Self>,
2403 ) {
2404 match event {
2405 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2406 let cursor_scroll_position = self.cursor_scroll_position(cx);
2407 if *autoscroll {
2408 self.scroll_position = cursor_scroll_position;
2409 } else if self.scroll_position != cursor_scroll_position {
2410 self.scroll_position = None;
2411 }
2412 }
2413 EditorEvent::SelectionsChanged { .. } => {
2414 self.scroll_position = self.cursor_scroll_position(cx);
2415 self.update_active_patch(cx);
2416 }
2417 _ => {}
2418 }
2419 cx.emit(event.clone());
2420 }
2421
2422 fn active_patch(&self) -> Option<(Range<text::Anchor>, &PatchViewState)> {
2423 let patch = self.active_patch.as_ref()?;
2424 Some((patch.clone(), self.patches.get(&patch)?))
2425 }
2426
2427 fn update_active_patch(&mut self, cx: &mut ViewContext<Self>) {
2428 let newest_cursor = self.editor.update(cx, |editor, cx| {
2429 editor.selections.newest::<Point>(cx).head()
2430 });
2431 let context = self.context.read(cx);
2432
2433 let new_patch = context.patch_containing(newest_cursor, cx).cloned();
2434
2435 if new_patch.as_ref().map(|p| &p.range) == self.active_patch.as_ref() {
2436 return;
2437 }
2438
2439 if let Some(old_patch_range) = self.active_patch.take() {
2440 if let Some(patch_state) = self.patches.get_mut(&old_patch_range) {
2441 if let Some(state) = patch_state.editor.take() {
2442 if let Some(editor) = state.editor.upgrade() {
2443 self.close_patch_editor(editor, cx);
2444 }
2445 }
2446 }
2447 }
2448
2449 if let Some(new_patch) = new_patch {
2450 self.active_patch = Some(new_patch.range.clone());
2451
2452 if let Some(patch_state) = self.patches.get_mut(&new_patch.range) {
2453 let mut editor = None;
2454 if let Some(state) = &patch_state.editor {
2455 if let Some(opened_editor) = state.editor.upgrade() {
2456 editor = Some(opened_editor);
2457 }
2458 }
2459
2460 if let Some(editor) = editor {
2461 self.workspace
2462 .update(cx, |workspace, cx| {
2463 workspace.activate_item(&editor, true, false, cx);
2464 })
2465 .ok();
2466 } else {
2467 patch_state.update_task = Some(cx.spawn(move |this, cx| async move {
2468 Self::open_patch_editor(this, new_patch, cx).await.log_err();
2469 }));
2470 }
2471 }
2472 }
2473 }
2474
2475 fn close_patch_editor(
2476 &mut self,
2477 editor: View<ProposedChangesEditor>,
2478 cx: &mut ViewContext<ContextEditor>,
2479 ) {
2480 self.workspace
2481 .update(cx, |workspace, cx| {
2482 if let Some(pane) = workspace.pane_for(&editor) {
2483 pane.update(cx, |pane, cx| {
2484 let item_id = editor.entity_id();
2485 if !editor.read(cx).focus_handle(cx).is_focused(cx) {
2486 pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
2487 .detach_and_log_err(cx);
2488 }
2489 });
2490 }
2491 })
2492 .ok();
2493 }
2494
2495 async fn open_patch_editor(
2496 this: WeakView<Self>,
2497 patch: AssistantPatch,
2498 mut cx: AsyncWindowContext,
2499 ) -> Result<()> {
2500 let project = this.update(&mut cx, |this, _| this.project.clone())?;
2501 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2502
2503 let editor = cx.new_view(|cx| {
2504 let editor = ProposedChangesEditor::new(
2505 patch.title.clone(),
2506 resolved_patch
2507 .edit_groups
2508 .iter()
2509 .map(|(buffer, groups)| ProposedChangeLocation {
2510 buffer: buffer.clone(),
2511 ranges: groups
2512 .iter()
2513 .map(|group| group.context_range.clone())
2514 .collect(),
2515 })
2516 .collect(),
2517 Some(project.clone()),
2518 cx,
2519 );
2520 resolved_patch.apply(&editor, cx);
2521 editor
2522 })?;
2523
2524 this.update(&mut cx, |this, cx| {
2525 if let Some(patch_state) = this.patches.get_mut(&patch.range) {
2526 patch_state.editor = Some(PatchEditorState {
2527 editor: editor.downgrade(),
2528 opened_patch: patch,
2529 });
2530 patch_state.update_task.take();
2531 }
2532
2533 this.workspace
2534 .update(cx, |workspace, cx| {
2535 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2536 })
2537 .log_err();
2538 })?;
2539
2540 Ok(())
2541 }
2542
2543 async fn update_patch_editor(
2544 this: WeakView<Self>,
2545 patch: AssistantPatch,
2546 mut cx: AsyncWindowContext,
2547 ) -> Result<()> {
2548 let project = this.update(&mut cx, |this, _| this.project.clone())?;
2549 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
2550 this.update(&mut cx, |this, cx| {
2551 let patch_state = this.patches.get_mut(&patch.range)?;
2552
2553 let locations = resolved_patch
2554 .edit_groups
2555 .iter()
2556 .map(|(buffer, groups)| ProposedChangeLocation {
2557 buffer: buffer.clone(),
2558 ranges: groups
2559 .iter()
2560 .map(|group| group.context_range.clone())
2561 .collect(),
2562 })
2563 .collect();
2564
2565 if let Some(state) = &mut patch_state.editor {
2566 if let Some(editor) = state.editor.upgrade() {
2567 editor.update(cx, |editor, cx| {
2568 editor.set_title(patch.title.clone(), cx);
2569 editor.reset_locations(locations, cx);
2570 resolved_patch.apply(editor, cx);
2571 });
2572
2573 state.opened_patch = patch;
2574 } else {
2575 patch_state.editor.take();
2576 }
2577 }
2578 patch_state.update_task.take();
2579
2580 Some(())
2581 })?;
2582 Ok(())
2583 }
2584
2585 fn handle_editor_search_event(
2586 &mut self,
2587 _: View<Editor>,
2588 event: &SearchEvent,
2589 cx: &mut ViewContext<Self>,
2590 ) {
2591 cx.emit(event.clone());
2592 }
2593
2594 fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2595 self.editor.update(cx, |editor, cx| {
2596 let snapshot = editor.snapshot(cx);
2597 let cursor = editor.selections.newest_anchor().head();
2598 let cursor_row = cursor
2599 .to_display_point(&snapshot.display_snapshot)
2600 .row()
2601 .as_f32();
2602 let scroll_position = editor
2603 .scroll_manager
2604 .anchor()
2605 .scroll_position(&snapshot.display_snapshot);
2606
2607 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2608 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2609 Some(ScrollPosition {
2610 cursor,
2611 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2612 })
2613 } else {
2614 None
2615 }
2616 })
2617 }
2618
2619 fn esc_kbd(cx: &WindowContext) -> Div {
2620 let colors = cx.theme().colors().clone();
2621
2622 h_flex()
2623 .items_center()
2624 .gap_1()
2625 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
2626 .text_size(TextSize::XSmall.rems(cx))
2627 .text_color(colors.text_muted)
2628 .child("Press")
2629 .child(
2630 h_flex()
2631 .rounded_md()
2632 .px_1()
2633 .mr_0p5()
2634 .border_1()
2635 .border_color(theme::color_alpha(colors.border_variant, 0.6))
2636 .bg(theme::color_alpha(colors.element_background, 0.6))
2637 .child("esc"),
2638 )
2639 .child("to cancel")
2640 }
2641
2642 fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2643 self.editor.update(cx, |editor, cx| {
2644 let buffer = editor.buffer().read(cx).snapshot(cx);
2645
2646 let excerpt_id = *buffer.as_singleton().unwrap().0;
2647 let mut old_blocks = std::mem::take(&mut self.blocks);
2648 let mut blocks_to_remove: HashMap<_, _> = old_blocks
2649 .iter()
2650 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
2651 .collect();
2652 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
2653
2654 let render_block = |message: MessageMetadata| -> RenderBlock {
2655 Arc::new({
2656 let context = self.context.clone();
2657
2658 move |cx| {
2659 let message_id = MessageId(message.timestamp);
2660 let llm_loading = message.role == Role::Assistant
2661 && message.status == MessageStatus::Pending;
2662
2663 let (label, spinner, note) = match message.role {
2664 Role::User => (
2665 Label::new("You").color(Color::Default).into_any_element(),
2666 None,
2667 None,
2668 ),
2669 Role::Assistant => {
2670 let base_label = Label::new("Assistant").color(Color::Info);
2671 let mut spinner = None;
2672 let mut note = None;
2673 let animated_label = if llm_loading {
2674 base_label
2675 .with_animation(
2676 "pulsating-label",
2677 Animation::new(Duration::from_secs(2))
2678 .repeat()
2679 .with_easing(pulsating_between(0.4, 0.8)),
2680 |label, delta| label.alpha(delta),
2681 )
2682 .into_any_element()
2683 } else {
2684 base_label.into_any_element()
2685 };
2686 if llm_loading {
2687 spinner = Some(
2688 Icon::new(IconName::ArrowCircle)
2689 .size(IconSize::XSmall)
2690 .color(Color::Info)
2691 .with_animation(
2692 "arrow-circle",
2693 Animation::new(Duration::from_secs(2)).repeat(),
2694 |icon, delta| {
2695 icon.transform(Transformation::rotate(
2696 percentage(delta),
2697 ))
2698 },
2699 )
2700 .into_any_element(),
2701 );
2702 note = Some(Self::esc_kbd(cx).into_any_element());
2703 }
2704 (animated_label, spinner, note)
2705 }
2706 Role::System => (
2707 Label::new("System")
2708 .color(Color::Warning)
2709 .into_any_element(),
2710 None,
2711 None,
2712 ),
2713 };
2714
2715 let sender = h_flex()
2716 .items_center()
2717 .gap_2p5()
2718 .child(
2719 ButtonLike::new("role")
2720 .style(ButtonStyle::Filled)
2721 .child(
2722 h_flex()
2723 .items_center()
2724 .gap_1p5()
2725 .child(label)
2726 .children(spinner),
2727 )
2728 .tooltip(|cx| {
2729 Tooltip::with_meta(
2730 "Toggle message role",
2731 None,
2732 "Available roles: You (User), Assistant, System",
2733 cx,
2734 )
2735 })
2736 .on_click({
2737 let context = context.clone();
2738 move |_, cx| {
2739 context.update(cx, |context, cx| {
2740 context.cycle_message_roles(
2741 HashSet::from_iter(Some(message_id)),
2742 cx,
2743 )
2744 })
2745 }
2746 }),
2747 )
2748 .children(note);
2749
2750 h_flex()
2751 .id(("message_header", message_id.as_u64()))
2752 .pl(cx.gutter_dimensions.full_width())
2753 .h_11()
2754 .w_full()
2755 .relative()
2756 .gap_1p5()
2757 .child(sender)
2758 .children(match &message.cache {
2759 Some(cache) if cache.is_final_anchor => match cache.status {
2760 CacheStatus::Cached => Some(
2761 div()
2762 .id("cached")
2763 .child(
2764 Icon::new(IconName::DatabaseZap)
2765 .size(IconSize::XSmall)
2766 .color(Color::Hint),
2767 )
2768 .tooltip(|cx| {
2769 Tooltip::with_meta(
2770 "Context Cached",
2771 None,
2772 "Large messages cached to optimize performance",
2773 cx,
2774 )
2775 })
2776 .into_any_element(),
2777 ),
2778 CacheStatus::Pending => Some(
2779 div()
2780 .child(
2781 Icon::new(IconName::Ellipsis)
2782 .size(IconSize::XSmall)
2783 .color(Color::Hint),
2784 )
2785 .into_any_element(),
2786 ),
2787 },
2788 _ => None,
2789 })
2790 .children(match &message.status {
2791 MessageStatus::Error(error) => Some(
2792 Button::new("show-error", "Error")
2793 .color(Color::Error)
2794 .selected_label_color(Color::Error)
2795 .selected_icon_color(Color::Error)
2796 .icon(IconName::XCircle)
2797 .icon_color(Color::Error)
2798 .icon_size(IconSize::XSmall)
2799 .icon_position(IconPosition::Start)
2800 .tooltip(move |cx| Tooltip::text("View Details", cx))
2801 .on_click({
2802 let context = context.clone();
2803 let error = error.clone();
2804 move |_, cx| {
2805 context.update(cx, |_, cx| {
2806 cx.emit(ContextEvent::ShowAssistError(
2807 error.clone(),
2808 ));
2809 });
2810 }
2811 })
2812 .into_any_element(),
2813 ),
2814 MessageStatus::Canceled => Some(
2815 h_flex()
2816 .gap_1()
2817 .items_center()
2818 .child(
2819 Icon::new(IconName::XCircle)
2820 .color(Color::Disabled)
2821 .size(IconSize::XSmall),
2822 )
2823 .child(
2824 Label::new("Canceled")
2825 .size(LabelSize::Small)
2826 .color(Color::Disabled),
2827 )
2828 .into_any_element(),
2829 ),
2830 _ => None,
2831 })
2832 .into_any_element()
2833 }
2834 })
2835 };
2836 let create_block_properties = |message: &Message| BlockProperties {
2837 height: 2,
2838 style: BlockStyle::Sticky,
2839 placement: BlockPlacement::Above(
2840 buffer
2841 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
2842 .unwrap(),
2843 ),
2844 priority: usize::MAX,
2845 render: render_block(MessageMetadata::from(message)),
2846 };
2847 let mut new_blocks = vec![];
2848 let mut block_index_to_message = vec![];
2849 for message in self.context.read(cx).messages(cx) {
2850 if let Some(_) = blocks_to_remove.remove(&message.id) {
2851 // This is an old message that we might modify.
2852 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
2853 debug_assert!(
2854 false,
2855 "old_blocks should contain a message_id we've just removed."
2856 );
2857 continue;
2858 };
2859 // Should we modify it?
2860 let message_meta = MessageMetadata::from(&message);
2861 if meta != &message_meta {
2862 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
2863 *meta = message_meta;
2864 }
2865 } else {
2866 // This is a new message.
2867 new_blocks.push(create_block_properties(&message));
2868 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
2869 }
2870 }
2871 editor.replace_blocks(blocks_to_replace, None, cx);
2872 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
2873
2874 let ids = editor.insert_blocks(new_blocks, None, cx);
2875 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
2876 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
2877 ));
2878 self.blocks = old_blocks;
2879 });
2880 }
2881
2882 /// Returns either the selected text, or the content of the Markdown code
2883 /// block surrounding the cursor.
2884 fn get_selection_or_code_block(
2885 context_editor_view: &View<ContextEditor>,
2886 cx: &mut ViewContext<Workspace>,
2887 ) -> Option<(String, bool)> {
2888 const CODE_FENCE_DELIMITER: &'static str = "```";
2889
2890 let context_editor = context_editor_view.read(cx).editor.clone();
2891 context_editor.update(cx, |context_editor, cx| {
2892 if context_editor.selections.newest::<Point>(cx).is_empty() {
2893 let snapshot = context_editor.buffer().read(cx).snapshot(cx);
2894 let (_, _, snapshot) = snapshot.as_singleton()?;
2895
2896 let head = context_editor.selections.newest::<Point>(cx).head();
2897 let offset = snapshot.point_to_offset(head);
2898
2899 let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
2900 let mut text = snapshot
2901 .text_for_range(surrounding_code_block_range)
2902 .collect::<String>();
2903
2904 // If there is no newline trailing the closing three-backticks, then
2905 // tree-sitter-md extends the range of the content node to include
2906 // the backticks.
2907 if text.ends_with(CODE_FENCE_DELIMITER) {
2908 text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
2909 }
2910
2911 (!text.is_empty()).then_some((text, true))
2912 } else {
2913 let anchor = context_editor.selections.newest_anchor();
2914 let text = context_editor
2915 .buffer()
2916 .read(cx)
2917 .read(cx)
2918 .text_for_range(anchor.range())
2919 .collect::<String>();
2920
2921 (!text.is_empty()).then_some((text, false))
2922 }
2923 })
2924 }
2925
2926 fn insert_selection(
2927 workspace: &mut Workspace,
2928 _: &InsertIntoEditor,
2929 cx: &mut ViewContext<Workspace>,
2930 ) {
2931 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2932 return;
2933 };
2934 let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2935 return;
2936 };
2937 let Some(active_editor_view) = workspace
2938 .active_item(cx)
2939 .and_then(|item| item.act_as::<Editor>(cx))
2940 else {
2941 return;
2942 };
2943
2944 if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
2945 active_editor_view.update(cx, |editor, cx| {
2946 editor.insert(&text, cx);
2947 editor.focus(cx);
2948 })
2949 }
2950 }
2951
2952 fn copy_code(workspace: &mut Workspace, _: &CopyCode, cx: &mut ViewContext<Workspace>) {
2953 let result = maybe!({
2954 let panel = workspace.panel::<AssistantPanel>(cx)?;
2955 let context_editor_view = panel.read(cx).active_context_editor(cx)?;
2956 Self::get_selection_or_code_block(&context_editor_view, cx)
2957 });
2958 let Some((text, is_code_block)) = result else {
2959 return;
2960 };
2961
2962 cx.write_to_clipboard(ClipboardItem::new_string(text));
2963
2964 struct CopyToClipboardToast;
2965 workspace.show_toast(
2966 Toast::new(
2967 NotificationId::unique::<CopyToClipboardToast>(),
2968 format!(
2969 "{} copied to clipboard.",
2970 if is_code_block {
2971 "Code block"
2972 } else {
2973 "Selection"
2974 }
2975 ),
2976 )
2977 .autohide(),
2978 cx,
2979 );
2980 }
2981
2982 fn insert_dragged_files(
2983 workspace: &mut Workspace,
2984 action: &InsertDraggedFiles,
2985 cx: &mut ViewContext<Workspace>,
2986 ) {
2987 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2988 return;
2989 };
2990 let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
2991 return;
2992 };
2993
2994 let project = workspace.project().clone();
2995
2996 let paths = match action {
2997 InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
2998 InsertDraggedFiles::ExternalFiles(paths) => {
2999 let tasks = paths
3000 .clone()
3001 .into_iter()
3002 .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
3003 .collect::<Vec<_>>();
3004
3005 cx.spawn(move |_, cx| async move {
3006 let mut paths = vec![];
3007 let mut worktrees = vec![];
3008
3009 let opened_paths = futures::future::join_all(tasks).await;
3010 for (worktree, project_path) in opened_paths.into_iter().flatten() {
3011 let Ok(worktree_root_name) =
3012 worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
3013 else {
3014 continue;
3015 };
3016
3017 let mut full_path = PathBuf::from(worktree_root_name.clone());
3018 full_path.push(&project_path.path);
3019 paths.push(full_path);
3020 worktrees.push(worktree);
3021 }
3022
3023 (paths, worktrees)
3024 })
3025 }
3026 };
3027
3028 cx.spawn(|_, mut cx| async move {
3029 let (paths, dragged_file_worktrees) = paths.await;
3030 let cmd_name = file_command::FileSlashCommand.name();
3031
3032 context_editor_view
3033 .update(&mut cx, |context_editor, cx| {
3034 let file_argument = paths
3035 .into_iter()
3036 .map(|path| path.to_string_lossy().to_string())
3037 .collect::<Vec<_>>()
3038 .join(" ");
3039
3040 context_editor.editor.update(cx, |editor, cx| {
3041 editor.insert("\n", cx);
3042 editor.insert(&format!("/{} {}", cmd_name, file_argument), cx);
3043 });
3044
3045 context_editor.confirm_command(&ConfirmCommand, cx);
3046
3047 context_editor
3048 .dragged_file_worktrees
3049 .extend(dragged_file_worktrees);
3050 })
3051 .log_err();
3052 })
3053 .detach();
3054 }
3055
3056 fn quote_selection(
3057 workspace: &mut Workspace,
3058 _: &QuoteSelection,
3059 cx: &mut ViewContext<Workspace>,
3060 ) {
3061 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
3062 return;
3063 };
3064
3065 let Some(creases) = selections_creases(workspace, cx) else {
3066 return;
3067 };
3068
3069 if creases.is_empty() {
3070 return;
3071 }
3072 // Activate the panel
3073 if !panel.focus_handle(cx).contains_focused(cx) {
3074 workspace.toggle_panel_focus::<AssistantPanel>(cx);
3075 }
3076
3077 panel.update(cx, |_, cx| {
3078 // Wait to create a new context until the workspace is no longer
3079 // being updated.
3080 cx.defer(move |panel, cx| {
3081 if let Some(context) = panel
3082 .active_context_editor(cx)
3083 .or_else(|| panel.new_context(cx))
3084 {
3085 context.update(cx, |context, cx| {
3086 context.editor.update(cx, |editor, cx| {
3087 editor.insert("\n", cx);
3088 for (text, crease_title) in creases {
3089 let point = editor.selections.newest::<Point>(cx).head();
3090 let start_row = MultiBufferRow(point.row);
3091
3092 editor.insert(&text, cx);
3093
3094 let snapshot = editor.buffer().read(cx).snapshot(cx);
3095 let anchor_before = snapshot.anchor_after(point);
3096 let anchor_after = editor
3097 .selections
3098 .newest_anchor()
3099 .head()
3100 .bias_left(&snapshot);
3101
3102 editor.insert("\n", cx);
3103
3104 let fold_placeholder = quote_selection_fold_placeholder(
3105 crease_title,
3106 cx.view().downgrade(),
3107 );
3108 let crease = Crease::inline(
3109 anchor_before..anchor_after,
3110 fold_placeholder,
3111 render_quote_selection_output_toggle,
3112 |_, _, _| Empty.into_any(),
3113 );
3114 editor.insert_creases(vec![crease], cx);
3115 editor.fold_at(
3116 &FoldAt {
3117 buffer_row: start_row,
3118 },
3119 cx,
3120 );
3121 }
3122 })
3123 });
3124 };
3125 });
3126 });
3127 }
3128
3129 fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
3130 if self.editor.read(cx).selections.count() == 1 {
3131 let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
3132 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3133 copied_text,
3134 metadata,
3135 ));
3136 cx.stop_propagation();
3137 return;
3138 }
3139
3140 cx.propagate();
3141 }
3142
3143 fn cut(&mut self, _: &editor::actions::Cut, cx: &mut ViewContext<Self>) {
3144 if self.editor.read(cx).selections.count() == 1 {
3145 let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
3146
3147 self.editor.update(cx, |editor, cx| {
3148 editor.transact(cx, |this, cx| {
3149 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3150 s.select(selections);
3151 });
3152 this.insert("", cx);
3153 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
3154 copied_text,
3155 metadata,
3156 ));
3157 });
3158 });
3159
3160 cx.stop_propagation();
3161 return;
3162 }
3163
3164 cx.propagate();
3165 }
3166
3167 fn get_clipboard_contents(
3168 &mut self,
3169 cx: &mut ViewContext<Self>,
3170 ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
3171 let (snapshot, selection, creases) = self.editor.update(cx, |editor, cx| {
3172 let mut selection = editor.selections.newest::<Point>(cx);
3173 let snapshot = editor.buffer().read(cx).snapshot(cx);
3174
3175 let is_entire_line = selection.is_empty() || editor.selections.line_mode;
3176 if is_entire_line {
3177 selection.start = Point::new(selection.start.row, 0);
3178 selection.end =
3179 cmp::min(snapshot.max_point(), Point::new(selection.start.row + 1, 0));
3180 selection.goal = SelectionGoal::None;
3181 }
3182
3183 let selection_start = snapshot.point_to_offset(selection.start);
3184
3185 (
3186 snapshot.clone(),
3187 selection.clone(),
3188 editor.display_map.update(cx, |display_map, cx| {
3189 display_map
3190 .snapshot(cx)
3191 .crease_snapshot
3192 .creases_in_range(
3193 MultiBufferRow(selection.start.row)
3194 ..MultiBufferRow(selection.end.row + 1),
3195 &snapshot,
3196 )
3197 .filter_map(|crease| {
3198 if let Crease::Inline {
3199 range, metadata, ..
3200 } = &crease
3201 {
3202 let metadata = metadata.as_ref()?;
3203 let start = range
3204 .start
3205 .to_offset(&snapshot)
3206 .saturating_sub(selection_start);
3207 let end = range
3208 .end
3209 .to_offset(&snapshot)
3210 .saturating_sub(selection_start);
3211
3212 let range_relative_to_selection = start..end;
3213 if !range_relative_to_selection.is_empty() {
3214 return Some(SelectedCreaseMetadata {
3215 range_relative_to_selection,
3216 crease: metadata.clone(),
3217 });
3218 }
3219 }
3220 None
3221 })
3222 .collect::<Vec<_>>()
3223 }),
3224 )
3225 });
3226
3227 let selection = selection.map(|point| snapshot.point_to_offset(point));
3228 let context = self.context.read(cx);
3229
3230 let mut text = String::new();
3231 for message in context.messages(cx) {
3232 if message.offset_range.start >= selection.range().end {
3233 break;
3234 } else if message.offset_range.end >= selection.range().start {
3235 let range = cmp::max(message.offset_range.start, selection.range().start)
3236 ..cmp::min(message.offset_range.end, selection.range().end);
3237 if !range.is_empty() {
3238 for chunk in context.buffer().read(cx).text_for_range(range) {
3239 text.push_str(chunk);
3240 }
3241 if message.offset_range.end < selection.range().end {
3242 text.push('\n');
3243 }
3244 }
3245 }
3246 }
3247
3248 (text, CopyMetadata { creases }, vec![selection])
3249 }
3250
3251 fn paste(&mut self, action: &editor::actions::Paste, cx: &mut ViewContext<Self>) {
3252 cx.stop_propagation();
3253
3254 let images = if let Some(item) = cx.read_from_clipboard() {
3255 item.into_entries()
3256 .filter_map(|entry| {
3257 if let ClipboardEntry::Image(image) = entry {
3258 Some(image)
3259 } else {
3260 None
3261 }
3262 })
3263 .collect()
3264 } else {
3265 Vec::new()
3266 };
3267
3268 let metadata = if let Some(item) = cx.read_from_clipboard() {
3269 item.entries().first().and_then(|entry| {
3270 if let ClipboardEntry::String(text) = entry {
3271 text.metadata_json::<CopyMetadata>()
3272 } else {
3273 None
3274 }
3275 })
3276 } else {
3277 None
3278 };
3279
3280 if images.is_empty() {
3281 self.editor.update(cx, |editor, cx| {
3282 let paste_position = editor.selections.newest::<usize>(cx).head();
3283 editor.paste(action, cx);
3284
3285 if let Some(metadata) = metadata {
3286 let buffer = editor.buffer().read(cx).snapshot(cx);
3287
3288 let mut buffer_rows_to_fold = BTreeSet::new();
3289 let weak_editor = cx.view().downgrade();
3290 editor.insert_creases(
3291 metadata.creases.into_iter().map(|metadata| {
3292 let start = buffer.anchor_after(
3293 paste_position + metadata.range_relative_to_selection.start,
3294 );
3295 let end = buffer.anchor_before(
3296 paste_position + metadata.range_relative_to_selection.end,
3297 );
3298
3299 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
3300 buffer_rows_to_fold.insert(buffer_row);
3301 Crease::inline(
3302 start..end,
3303 FoldPlaceholder {
3304 render: render_fold_icon_button(
3305 weak_editor.clone(),
3306 metadata.crease.icon,
3307 metadata.crease.label.clone(),
3308 ),
3309 ..Default::default()
3310 },
3311 render_slash_command_output_toggle,
3312 |_, _, _| Empty.into_any(),
3313 )
3314 .with_metadata(metadata.crease.clone())
3315 }),
3316 cx,
3317 );
3318 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
3319 editor.fold_at(&FoldAt { buffer_row }, cx);
3320 }
3321 }
3322 });
3323 } else {
3324 let mut image_positions = Vec::new();
3325 self.editor.update(cx, |editor, cx| {
3326 editor.transact(cx, |editor, cx| {
3327 let edits = editor
3328 .selections
3329 .all::<usize>(cx)
3330 .into_iter()
3331 .map(|selection| (selection.start..selection.end, "\n"));
3332 editor.edit(edits, cx);
3333
3334 let snapshot = editor.buffer().read(cx).snapshot(cx);
3335 for selection in editor.selections.all::<usize>(cx) {
3336 image_positions.push(snapshot.anchor_before(selection.end));
3337 }
3338 });
3339 });
3340
3341 self.context.update(cx, |context, cx| {
3342 for image in images {
3343 let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
3344 else {
3345 continue;
3346 };
3347 let image_id = image.id();
3348 let image_task = LanguageModelImage::from_image(image, cx).shared();
3349
3350 for image_position in image_positions.iter() {
3351 context.insert_content(
3352 Content::Image {
3353 anchor: image_position.text_anchor,
3354 image_id,
3355 image: image_task.clone(),
3356 render_image: render_image.clone(),
3357 },
3358 cx,
3359 );
3360 }
3361 }
3362 });
3363 }
3364 }
3365
3366 fn update_image_blocks(&mut self, cx: &mut ViewContext<Self>) {
3367 self.editor.update(cx, |editor, cx| {
3368 let buffer = editor.buffer().read(cx).snapshot(cx);
3369 let excerpt_id = *buffer.as_singleton().unwrap().0;
3370 let old_blocks = std::mem::take(&mut self.image_blocks);
3371 let new_blocks = self
3372 .context
3373 .read(cx)
3374 .contents(cx)
3375 .filter_map(|content| {
3376 if let Content::Image {
3377 anchor,
3378 render_image,
3379 ..
3380 } = content
3381 {
3382 Some((anchor, render_image))
3383 } else {
3384 None
3385 }
3386 })
3387 .filter_map(|(anchor, render_image)| {
3388 const MAX_HEIGHT_IN_LINES: u32 = 8;
3389 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
3390 let image = render_image.clone();
3391 anchor.is_valid(&buffer).then(|| BlockProperties {
3392 placement: BlockPlacement::Above(anchor),
3393 height: MAX_HEIGHT_IN_LINES,
3394 style: BlockStyle::Sticky,
3395 render: Arc::new(move |cx| {
3396 let image_size = size_for_image(
3397 &image,
3398 size(
3399 cx.max_width - cx.gutter_dimensions.full_width(),
3400 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
3401 ),
3402 );
3403 h_flex()
3404 .pl(cx.gutter_dimensions.full_width())
3405 .child(
3406 img(image.clone())
3407 .object_fit(gpui::ObjectFit::ScaleDown)
3408 .w(image_size.width)
3409 .h(image_size.height),
3410 )
3411 .into_any_element()
3412 }),
3413 priority: 0,
3414 })
3415 })
3416 .collect::<Vec<_>>();
3417
3418 editor.remove_blocks(old_blocks, None, cx);
3419 let ids = editor.insert_blocks(new_blocks, None, cx);
3420 self.image_blocks = HashSet::from_iter(ids);
3421 });
3422 }
3423
3424 fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3425 self.context.update(cx, |context, cx| {
3426 let selections = self.editor.read(cx).selections.disjoint_anchors();
3427 for selection in selections.as_ref() {
3428 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3429 let range = selection
3430 .map(|endpoint| endpoint.to_offset(&buffer))
3431 .range();
3432 context.split_message(range, cx);
3433 }
3434 });
3435 }
3436
3437 fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3438 self.context.update(cx, |context, cx| {
3439 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3440 });
3441 }
3442
3443 fn title(&self, cx: &AppContext) -> Cow<str> {
3444 self.context
3445 .read(cx)
3446 .summary()
3447 .map(|summary| summary.text.clone())
3448 .map(Cow::Owned)
3449 .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3450 }
3451
3452 fn render_patch_block(
3453 &mut self,
3454 range: Range<text::Anchor>,
3455 max_width: Pixels,
3456 gutter_width: Pixels,
3457 id: BlockId,
3458 selected: bool,
3459 cx: &mut ViewContext<Self>,
3460 ) -> Option<AnyElement> {
3461 let snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3462 let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
3463 let excerpt_id = *excerpt_id;
3464 let anchor = snapshot
3465 .buffer_snapshot
3466 .anchor_in_excerpt(excerpt_id, range.start)
3467 .unwrap();
3468
3469 let theme = cx.theme().clone();
3470 let patch = self.context.read(cx).patch_for_range(&range, cx)?;
3471 let paths = patch
3472 .paths()
3473 .map(|p| SharedString::from(p.to_string()))
3474 .collect::<BTreeSet<_>>();
3475
3476 Some(
3477 v_flex()
3478 .id(id)
3479 .bg(theme.colors().editor_background)
3480 .ml(gutter_width)
3481 .pb_1()
3482 .w(max_width - gutter_width)
3483 .rounded_md()
3484 .border_1()
3485 .border_color(theme.colors().border_variant)
3486 .overflow_hidden()
3487 .hover(|style| style.border_color(theme.colors().text_accent))
3488 .when(selected, |this| {
3489 this.border_color(theme.colors().text_accent)
3490 })
3491 .cursor(CursorStyle::PointingHand)
3492 .on_click(cx.listener(move |this, _, cx| {
3493 this.editor.update(cx, |editor, cx| {
3494 editor.change_selections(None, cx, |selections| {
3495 selections.select_ranges(vec![anchor..anchor]);
3496 });
3497 });
3498 this.focus_active_patch(cx);
3499 }))
3500 .child(
3501 div()
3502 .px_2()
3503 .py_1()
3504 .overflow_hidden()
3505 .text_ellipsis()
3506 .border_b_1()
3507 .border_color(theme.colors().border_variant)
3508 .bg(theme.colors().element_background)
3509 .child(
3510 Label::new(patch.title.clone())
3511 .size(LabelSize::Small)
3512 .color(Color::Muted),
3513 ),
3514 )
3515 .children(paths.into_iter().map(|path| {
3516 h_flex()
3517 .px_2()
3518 .pt_1()
3519 .gap_1p5()
3520 .child(Icon::new(IconName::File).size(IconSize::Small))
3521 .child(Label::new(path).size(LabelSize::Small))
3522 }))
3523 .when(patch.status == AssistantPatchStatus::Pending, |div| {
3524 div.child(
3525 h_flex()
3526 .pt_1()
3527 .px_2()
3528 .gap_1()
3529 .child(
3530 Icon::new(IconName::ArrowCircle)
3531 .size(IconSize::XSmall)
3532 .color(Color::Muted)
3533 .with_animation(
3534 "arrow-circle",
3535 Animation::new(Duration::from_secs(2)).repeat(),
3536 |icon, delta| {
3537 icon.transform(Transformation::rotate(percentage(
3538 delta,
3539 )))
3540 },
3541 ),
3542 )
3543 .child(
3544 Label::new("Generating…")
3545 .color(Color::Muted)
3546 .size(LabelSize::Small)
3547 .with_animation(
3548 "pulsating-label",
3549 Animation::new(Duration::from_secs(2))
3550 .repeat()
3551 .with_easing(pulsating_between(0.4, 0.8)),
3552 |label, delta| label.alpha(delta),
3553 ),
3554 ),
3555 )
3556 })
3557 .into_any(),
3558 )
3559 }
3560
3561 fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3562 use feature_flags::FeatureFlagAppExt;
3563 let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
3564 assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
3565 });
3566
3567 if nudge.map_or(false, |value| value) {
3568 Some(
3569 h_flex()
3570 .p_3()
3571 .border_b_1()
3572 .border_color(cx.theme().colors().border_variant)
3573 .bg(cx.theme().colors().editor_background)
3574 .justify_between()
3575 .child(
3576 h_flex()
3577 .gap_3()
3578 .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
3579 .child(Label::new("Zed AI is here! Get started by signing in →")),
3580 )
3581 .child(
3582 Button::new("sign-in", "Sign in")
3583 .size(ButtonSize::Compact)
3584 .style(ButtonStyle::Filled)
3585 .on_click(cx.listener(|this, _event, cx| {
3586 let client = this
3587 .workspace
3588 .update(cx, |workspace, _| workspace.client().clone())
3589 .log_err();
3590
3591 if let Some(client) = client {
3592 cx.spawn(|this, mut cx| async move {
3593 client.authenticate_and_connect(true, &mut cx).await?;
3594 this.update(&mut cx, |_, cx| cx.notify())
3595 })
3596 .detach_and_log_err(cx)
3597 }
3598 })),
3599 )
3600 .into_any_element(),
3601 )
3602 } else if let Some(configuration_error) = configuration_error(cx) {
3603 let label = match configuration_error {
3604 ConfigurationError::NoProvider => "No LLM provider selected.",
3605 ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
3606 };
3607 Some(
3608 h_flex()
3609 .px_3()
3610 .py_2()
3611 .border_b_1()
3612 .border_color(cx.theme().colors().border_variant)
3613 .bg(cx.theme().colors().editor_background)
3614 .justify_between()
3615 .child(
3616 h_flex()
3617 .gap_3()
3618 .child(
3619 Icon::new(IconName::Warning)
3620 .size(IconSize::Small)
3621 .color(Color::Warning),
3622 )
3623 .child(Label::new(label)),
3624 )
3625 .child(
3626 Button::new("open-configuration", "Configure Providers")
3627 .size(ButtonSize::Compact)
3628 .icon(Some(IconName::SlidersVertical))
3629 .icon_size(IconSize::Small)
3630 .icon_position(IconPosition::Start)
3631 .style(ButtonStyle::Filled)
3632 .on_click({
3633 let focus_handle = self.focus_handle(cx).clone();
3634 move |_event, cx| {
3635 focus_handle.dispatch_action(&ShowConfiguration, cx);
3636 }
3637 }),
3638 )
3639 .into_any_element(),
3640 )
3641 } else {
3642 None
3643 }
3644 }
3645
3646 fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3647 let focus_handle = self.focus_handle(cx).clone();
3648
3649 let (style, tooltip) = match token_state(&self.context, cx) {
3650 Some(TokenState::NoTokensLeft { .. }) => (
3651 ButtonStyle::Tinted(TintColor::Negative),
3652 Some(Tooltip::text("Token limit reached", cx)),
3653 ),
3654 Some(TokenState::HasMoreTokens {
3655 over_warn_threshold,
3656 ..
3657 }) => {
3658 let (style, tooltip) = if over_warn_threshold {
3659 (
3660 ButtonStyle::Tinted(TintColor::Warning),
3661 Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3662 )
3663 } else {
3664 (ButtonStyle::Filled, None)
3665 };
3666 (style, tooltip)
3667 }
3668 None => (ButtonStyle::Filled, None),
3669 };
3670
3671 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3672
3673 let has_configuration_error = configuration_error(cx).is_some();
3674 let needs_to_accept_terms = self.show_accept_terms
3675 && provider
3676 .as_ref()
3677 .map_or(false, |provider| provider.must_accept_terms(cx));
3678 let disabled = has_configuration_error || needs_to_accept_terms;
3679
3680 ButtonLike::new("send_button")
3681 .disabled(disabled)
3682 .style(style)
3683 .when_some(tooltip, |button, tooltip| {
3684 button.tooltip(move |_| tooltip.clone())
3685 })
3686 .layer(ElevationIndex::ModalSurface)
3687 .child(Label::new(
3688 if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
3689 "Chat"
3690 } else {
3691 "Send"
3692 },
3693 ))
3694 .children(
3695 KeyBinding::for_action_in(&Assist, &focus_handle, cx)
3696 .map(|binding| binding.into_any_element()),
3697 )
3698 .on_click(move |_event, cx| {
3699 focus_handle.dispatch_action(&Assist, cx);
3700 })
3701 }
3702
3703 fn render_edit_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3704 let focus_handle = self.focus_handle(cx).clone();
3705
3706 let (style, tooltip) = match token_state(&self.context, cx) {
3707 Some(TokenState::NoTokensLeft { .. }) => (
3708 ButtonStyle::Tinted(TintColor::Negative),
3709 Some(Tooltip::text("Token limit reached", cx)),
3710 ),
3711 Some(TokenState::HasMoreTokens {
3712 over_warn_threshold,
3713 ..
3714 }) => {
3715 let (style, tooltip) = if over_warn_threshold {
3716 (
3717 ButtonStyle::Tinted(TintColor::Warning),
3718 Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3719 )
3720 } else {
3721 (ButtonStyle::Filled, None)
3722 };
3723 (style, tooltip)
3724 }
3725 None => (ButtonStyle::Filled, None),
3726 };
3727
3728 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3729
3730 let has_configuration_error = configuration_error(cx).is_some();
3731 let needs_to_accept_terms = self.show_accept_terms
3732 && provider
3733 .as_ref()
3734 .map_or(false, |provider| provider.must_accept_terms(cx));
3735 let disabled = has_configuration_error || needs_to_accept_terms;
3736
3737 ButtonLike::new("edit_button")
3738 .disabled(disabled)
3739 .style(style)
3740 .when_some(tooltip, |button, tooltip| {
3741 button.tooltip(move |_| tooltip.clone())
3742 })
3743 .layer(ElevationIndex::ModalSurface)
3744 .child(Label::new("Suggest Edits"))
3745 .children(
3746 KeyBinding::for_action_in(&Edit, &focus_handle, cx)
3747 .map(|binding| binding.into_any_element()),
3748 )
3749 .on_click(move |_event, cx| {
3750 focus_handle.dispatch_action(&Edit, cx);
3751 })
3752 }
3753
3754 fn render_inject_context_menu(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3755 slash_command_picker::SlashCommandSelector::new(
3756 self.slash_commands.clone(),
3757 cx.view().downgrade(),
3758 Button::new("trigger", "Add Context")
3759 .icon(IconName::Plus)
3760 .icon_size(IconSize::Small)
3761 .icon_color(Color::Muted)
3762 .icon_position(IconPosition::Start)
3763 .tooltip(|cx| Tooltip::text("Type / to insert via keyboard", cx)),
3764 )
3765 }
3766
3767 fn render_last_error(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3768 let last_error = self.last_error.as_ref()?;
3769
3770 Some(
3771 div()
3772 .absolute()
3773 .right_3()
3774 .bottom_12()
3775 .max_w_96()
3776 .py_2()
3777 .px_3()
3778 .elevation_2(cx)
3779 .occlude()
3780 .child(match last_error {
3781 AssistError::FileRequired => self.render_file_required_error(cx),
3782 AssistError::PaymentRequired => self.render_payment_required_error(cx),
3783 AssistError::MaxMonthlySpendReached => {
3784 self.render_max_monthly_spend_reached_error(cx)
3785 }
3786 AssistError::Message(error_message) => {
3787 self.render_assist_error(error_message, cx)
3788 }
3789 })
3790 .into_any(),
3791 )
3792 }
3793
3794 fn render_file_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3795 v_flex()
3796 .gap_0p5()
3797 .child(
3798 h_flex()
3799 .gap_1p5()
3800 .items_center()
3801 .child(Icon::new(IconName::Warning).color(Color::Warning))
3802 .child(
3803 Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
3804 ),
3805 )
3806 .child(
3807 div()
3808 .id("error-message")
3809 .max_h_24()
3810 .overflow_y_scroll()
3811 .child(Label::new(
3812 "To include files, type /file or /tab in your prompt.",
3813 )),
3814 )
3815 .child(
3816 h_flex()
3817 .justify_end()
3818 .mt_1()
3819 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3820 |this, _, cx| {
3821 this.last_error = None;
3822 cx.notify();
3823 },
3824 ))),
3825 )
3826 .into_any()
3827 }
3828
3829 fn render_payment_required_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3830 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.";
3831
3832 v_flex()
3833 .gap_0p5()
3834 .child(
3835 h_flex()
3836 .gap_1p5()
3837 .items_center()
3838 .child(Icon::new(IconName::XCircle).color(Color::Error))
3839 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
3840 )
3841 .child(
3842 div()
3843 .id("error-message")
3844 .max_h_24()
3845 .overflow_y_scroll()
3846 .child(Label::new(ERROR_MESSAGE)),
3847 )
3848 .child(
3849 h_flex()
3850 .justify_end()
3851 .mt_1()
3852 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
3853 |this, _, cx| {
3854 this.last_error = None;
3855 cx.open_url(&zed_urls::account_url(cx));
3856 cx.notify();
3857 },
3858 )))
3859 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3860 |this, _, cx| {
3861 this.last_error = None;
3862 cx.notify();
3863 },
3864 ))),
3865 )
3866 .into_any()
3867 }
3868
3869 fn render_max_monthly_spend_reached_error(&self, cx: &mut ViewContext<Self>) -> AnyElement {
3870 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
3871
3872 v_flex()
3873 .gap_0p5()
3874 .child(
3875 h_flex()
3876 .gap_1p5()
3877 .items_center()
3878 .child(Icon::new(IconName::XCircle).color(Color::Error))
3879 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
3880 )
3881 .child(
3882 div()
3883 .id("error-message")
3884 .max_h_24()
3885 .overflow_y_scroll()
3886 .child(Label::new(ERROR_MESSAGE)),
3887 )
3888 .child(
3889 h_flex()
3890 .justify_end()
3891 .mt_1()
3892 .child(
3893 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
3894 cx.listener(|this, _, cx| {
3895 this.last_error = None;
3896 cx.open_url(&zed_urls::account_url(cx));
3897 cx.notify();
3898 }),
3899 ),
3900 )
3901 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3902 |this, _, cx| {
3903 this.last_error = None;
3904 cx.notify();
3905 },
3906 ))),
3907 )
3908 .into_any()
3909 }
3910
3911 fn render_assist_error(
3912 &self,
3913 error_message: &SharedString,
3914 cx: &mut ViewContext<Self>,
3915 ) -> AnyElement {
3916 v_flex()
3917 .gap_0p5()
3918 .child(
3919 h_flex()
3920 .gap_1p5()
3921 .items_center()
3922 .child(Icon::new(IconName::XCircle).color(Color::Error))
3923 .child(
3924 Label::new("Error interacting with language model")
3925 .weight(FontWeight::MEDIUM),
3926 ),
3927 )
3928 .child(
3929 div()
3930 .id("error-message")
3931 .max_h_32()
3932 .overflow_y_scroll()
3933 .child(Label::new(error_message.clone())),
3934 )
3935 .child(
3936 h_flex()
3937 .justify_end()
3938 .mt_1()
3939 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
3940 |this, _, cx| {
3941 this.last_error = None;
3942 cx.notify();
3943 },
3944 ))),
3945 )
3946 .into_any()
3947 }
3948}
3949
3950/// Returns the contents of the *outermost* fenced code block that contains the given offset.
3951fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
3952 const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
3953 const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
3954
3955 let layer = snapshot.syntax_layers().next()?;
3956
3957 let root_node = layer.node();
3958 let mut cursor = root_node.walk();
3959
3960 // Go to the first child for the given offset
3961 while cursor.goto_first_child_for_byte(offset).is_some() {
3962 // If we're at the end of the node, go to the next one.
3963 // Example: if you have a fenced-code-block, and you're on the start of the line
3964 // right after the closing ```, you want to skip the fenced-code-block and
3965 // go to the next sibling.
3966 if cursor.node().end_byte() == offset {
3967 cursor.goto_next_sibling();
3968 }
3969
3970 if cursor.node().start_byte() > offset {
3971 break;
3972 }
3973
3974 // We found the fenced code block.
3975 if cursor.node().kind() == CODE_BLOCK_NODE {
3976 // Now we need to find the child node that contains the code.
3977 cursor.goto_first_child();
3978 loop {
3979 if cursor.node().kind() == CODE_BLOCK_CONTENT {
3980 return Some(cursor.node().byte_range());
3981 }
3982 if !cursor.goto_next_sibling() {
3983 break;
3984 }
3985 }
3986 }
3987 }
3988
3989 None
3990}
3991
3992pub fn selections_creases(
3993 workspace: &mut workspace::Workspace,
3994 cx: &mut ViewContext<Workspace>,
3995) -> Option<Vec<(String, String)>> {
3996 let editor = workspace
3997 .active_item(cx)
3998 .and_then(|item| item.act_as::<Editor>(cx))?;
3999
4000 let mut creases = vec![];
4001 editor.update(cx, |editor, cx| {
4002 let selections = editor.selections.all_adjusted(cx);
4003 let buffer = editor.buffer().read(cx).snapshot(cx);
4004 for selection in selections {
4005 let range = editor::ToOffset::to_offset(&selection.start, &buffer)
4006 ..editor::ToOffset::to_offset(&selection.end, &buffer);
4007 let selected_text = buffer.text_for_range(range.clone()).collect::<String>();
4008 if selected_text.is_empty() {
4009 continue;
4010 }
4011 let start_language = buffer.language_at(range.start);
4012 let end_language = buffer.language_at(range.end);
4013 let language_name = if start_language == end_language {
4014 start_language.map(|language| language.code_fence_block_name())
4015 } else {
4016 None
4017 };
4018 let language_name = language_name.as_deref().unwrap_or("");
4019 let filename = buffer
4020 .file_at(selection.start)
4021 .map(|file| file.full_path(cx));
4022 let text = if language_name == "markdown" {
4023 selected_text
4024 .lines()
4025 .map(|line| format!("> {}", line))
4026 .collect::<Vec<_>>()
4027 .join("\n")
4028 } else {
4029 let start_symbols = buffer
4030 .symbols_containing(selection.start, None)
4031 .map(|(_, symbols)| symbols);
4032 let end_symbols = buffer
4033 .symbols_containing(selection.end, None)
4034 .map(|(_, symbols)| symbols);
4035
4036 let outline_text =
4037 if let Some((start_symbols, end_symbols)) = start_symbols.zip(end_symbols) {
4038 Some(
4039 start_symbols
4040 .into_iter()
4041 .zip(end_symbols)
4042 .take_while(|(a, b)| a == b)
4043 .map(|(a, _)| a.text)
4044 .collect::<Vec<_>>()
4045 .join(" > "),
4046 )
4047 } else {
4048 None
4049 };
4050
4051 let line_comment_prefix = start_language
4052 .and_then(|l| l.default_scope().line_comment_prefixes().first().cloned());
4053
4054 let fence = codeblock_fence_for_path(
4055 filename.as_deref(),
4056 Some(selection.start.row..=selection.end.row),
4057 );
4058
4059 if let Some((line_comment_prefix, outline_text)) =
4060 line_comment_prefix.zip(outline_text)
4061 {
4062 let breadcrumb = format!("{line_comment_prefix}Excerpt from: {outline_text}\n");
4063 format!("{fence}{breadcrumb}{selected_text}\n```")
4064 } else {
4065 format!("{fence}{selected_text}\n```")
4066 }
4067 };
4068 let crease_title = if let Some(path) = filename {
4069 let start_line = selection.start.row + 1;
4070 let end_line = selection.end.row + 1;
4071 if start_line == end_line {
4072 format!("{}, Line {}", path.display(), start_line)
4073 } else {
4074 format!("{}, Lines {} to {}", path.display(), start_line, end_line)
4075 }
4076 } else {
4077 "Quoted selection".to_string()
4078 };
4079 creases.push((text, crease_title));
4080 }
4081 });
4082 Some(creases)
4083}
4084
4085fn render_fold_icon_button(
4086 editor: WeakView<Editor>,
4087 icon: IconName,
4088 label: SharedString,
4089) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut WindowContext) -> AnyElement> {
4090 Arc::new(move |fold_id, fold_range, _cx| {
4091 let editor = editor.clone();
4092 ButtonLike::new(fold_id)
4093 .style(ButtonStyle::Filled)
4094 .layer(ElevationIndex::ElevatedSurface)
4095 .child(Icon::new(icon))
4096 .child(Label::new(label.clone()).single_line())
4097 .on_click(move |_, cx| {
4098 editor
4099 .update(cx, |editor, cx| {
4100 let buffer_start = fold_range
4101 .start
4102 .to_point(&editor.buffer().read(cx).read(cx));
4103 let buffer_row = MultiBufferRow(buffer_start.row);
4104 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4105 })
4106 .ok();
4107 })
4108 .into_any_element()
4109 })
4110}
4111
4112#[derive(Debug, Clone, Serialize, Deserialize)]
4113struct CopyMetadata {
4114 creases: Vec<SelectedCreaseMetadata>,
4115}
4116
4117#[derive(Debug, Clone, Serialize, Deserialize)]
4118struct SelectedCreaseMetadata {
4119 range_relative_to_selection: Range<usize>,
4120 crease: CreaseMetadata,
4121}
4122
4123impl EventEmitter<EditorEvent> for ContextEditor {}
4124impl EventEmitter<SearchEvent> for ContextEditor {}
4125
4126impl Render for ContextEditor {
4127 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4128 let provider = LanguageModelRegistry::read_global(cx).active_provider();
4129 let accept_terms = if self.show_accept_terms {
4130 provider
4131 .as_ref()
4132 .and_then(|provider| provider.render_accept_terms(cx))
4133 } else {
4134 None
4135 };
4136
4137 v_flex()
4138 .key_context("ContextEditor")
4139 .capture_action(cx.listener(ContextEditor::cancel))
4140 .capture_action(cx.listener(ContextEditor::save))
4141 .capture_action(cx.listener(ContextEditor::copy))
4142 .capture_action(cx.listener(ContextEditor::cut))
4143 .capture_action(cx.listener(ContextEditor::paste))
4144 .capture_action(cx.listener(ContextEditor::cycle_message_role))
4145 .capture_action(cx.listener(ContextEditor::confirm_command))
4146 .on_action(cx.listener(ContextEditor::edit))
4147 .on_action(cx.listener(ContextEditor::assist))
4148 .on_action(cx.listener(ContextEditor::split))
4149 .size_full()
4150 .children(self.render_notice(cx))
4151 .child(
4152 div()
4153 .flex_grow()
4154 .bg(cx.theme().colors().editor_background)
4155 .child(self.editor.clone()),
4156 )
4157 .when_some(accept_terms, |this, element| {
4158 this.child(
4159 div()
4160 .absolute()
4161 .right_3()
4162 .bottom_12()
4163 .max_w_96()
4164 .py_2()
4165 .px_3()
4166 .elevation_2(cx)
4167 .bg(cx.theme().colors().surface_background)
4168 .occlude()
4169 .child(element),
4170 )
4171 })
4172 .children(self.render_last_error(cx))
4173 .child(
4174 h_flex().w_full().relative().child(
4175 h_flex()
4176 .p_2()
4177 .w_full()
4178 .border_t_1()
4179 .border_color(cx.theme().colors().border_variant)
4180 .bg(cx.theme().colors().editor_background)
4181 .child(h_flex().gap_1().child(self.render_inject_context_menu(cx)))
4182 .child(
4183 h_flex()
4184 .w_full()
4185 .justify_end()
4186 .when(
4187 AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
4188 |buttons| {
4189 buttons
4190 .items_center()
4191 .gap_1p5()
4192 .child(self.render_edit_button(cx))
4193 .child(
4194 Label::new("or")
4195 .size(LabelSize::Small)
4196 .color(Color::Muted),
4197 )
4198 },
4199 )
4200 .child(self.render_send_button(cx)),
4201 ),
4202 ),
4203 )
4204 }
4205}
4206
4207impl FocusableView for ContextEditor {
4208 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4209 self.editor.focus_handle(cx)
4210 }
4211}
4212
4213impl Item for ContextEditor {
4214 type Event = editor::EditorEvent;
4215
4216 fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
4217 Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
4218 }
4219
4220 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
4221 match event {
4222 EditorEvent::Edited { .. } => {
4223 f(item::ItemEvent::Edit);
4224 }
4225 EditorEvent::TitleChanged => {
4226 f(item::ItemEvent::UpdateTab);
4227 }
4228 _ => {}
4229 }
4230 }
4231
4232 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
4233 Some(self.title(cx).to_string().into())
4234 }
4235
4236 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
4237 Some(Box::new(handle.clone()))
4238 }
4239
4240 fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
4241 self.editor.update(cx, |editor, cx| {
4242 Item::set_nav_history(editor, nav_history, cx)
4243 })
4244 }
4245
4246 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
4247 self.editor
4248 .update(cx, |editor, cx| Item::navigate(editor, data, cx))
4249 }
4250
4251 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
4252 self.editor.update(cx, Item::deactivated)
4253 }
4254
4255 fn act_as_type<'a>(
4256 &'a self,
4257 type_id: TypeId,
4258 self_handle: &'a View<Self>,
4259 _: &'a AppContext,
4260 ) -> Option<AnyView> {
4261 if type_id == TypeId::of::<Self>() {
4262 Some(self_handle.to_any())
4263 } else if type_id == TypeId::of::<Editor>() {
4264 Some(self.editor.to_any())
4265 } else {
4266 None
4267 }
4268 }
4269}
4270
4271impl SearchableItem for ContextEditor {
4272 type Match = <Editor as SearchableItem>::Match;
4273
4274 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
4275 self.editor.update(cx, |editor, cx| {
4276 editor.clear_matches(cx);
4277 });
4278 }
4279
4280 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4281 self.editor
4282 .update(cx, |editor, cx| editor.update_matches(matches, cx));
4283 }
4284
4285 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
4286 self.editor
4287 .update(cx, |editor, cx| editor.query_suggestion(cx))
4288 }
4289
4290 fn activate_match(
4291 &mut self,
4292 index: usize,
4293 matches: &[Self::Match],
4294 cx: &mut ViewContext<Self>,
4295 ) {
4296 self.editor.update(cx, |editor, cx| {
4297 editor.activate_match(index, matches, cx);
4298 });
4299 }
4300
4301 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4302 self.editor
4303 .update(cx, |editor, cx| editor.select_matches(matches, cx));
4304 }
4305
4306 fn replace(
4307 &mut self,
4308 identifier: &Self::Match,
4309 query: &project::search::SearchQuery,
4310 cx: &mut ViewContext<Self>,
4311 ) {
4312 self.editor
4313 .update(cx, |editor, cx| editor.replace(identifier, query, cx));
4314 }
4315
4316 fn find_matches(
4317 &mut self,
4318 query: Arc<project::search::SearchQuery>,
4319 cx: &mut ViewContext<Self>,
4320 ) -> Task<Vec<Self::Match>> {
4321 self.editor
4322 .update(cx, |editor, cx| editor.find_matches(query, cx))
4323 }
4324
4325 fn active_match_index(
4326 &mut self,
4327 matches: &[Self::Match],
4328 cx: &mut ViewContext<Self>,
4329 ) -> Option<usize> {
4330 self.editor
4331 .update(cx, |editor, cx| editor.active_match_index(matches, cx))
4332 }
4333}
4334
4335impl FollowableItem for ContextEditor {
4336 fn remote_id(&self) -> Option<workspace::ViewId> {
4337 self.remote_id
4338 }
4339
4340 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
4341 let context = self.context.read(cx);
4342 Some(proto::view::Variant::ContextEditor(
4343 proto::view::ContextEditor {
4344 context_id: context.id().to_proto(),
4345 editor: if let Some(proto::view::Variant::Editor(proto)) =
4346 self.editor.read(cx).to_state_proto(cx)
4347 {
4348 Some(proto)
4349 } else {
4350 None
4351 },
4352 },
4353 ))
4354 }
4355
4356 fn from_state_proto(
4357 workspace: View<Workspace>,
4358 id: workspace::ViewId,
4359 state: &mut Option<proto::view::Variant>,
4360 cx: &mut WindowContext,
4361 ) -> Option<Task<Result<View<Self>>>> {
4362 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
4363 return None;
4364 };
4365 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
4366 unreachable!()
4367 };
4368
4369 let context_id = ContextId::from_proto(state.context_id);
4370 let editor_state = state.editor?;
4371
4372 let (project, panel) = workspace.update(cx, |workspace, cx| {
4373 Some((
4374 workspace.project().clone(),
4375 workspace.panel::<AssistantPanel>(cx)?,
4376 ))
4377 })?;
4378
4379 let context_editor =
4380 panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
4381
4382 Some(cx.spawn(|mut cx| async move {
4383 let context_editor = context_editor.await?;
4384 context_editor
4385 .update(&mut cx, |context_editor, cx| {
4386 context_editor.remote_id = Some(id);
4387 context_editor.editor.update(cx, |editor, cx| {
4388 editor.apply_update_proto(
4389 &project,
4390 proto::update_view::Variant::Editor(proto::update_view::Editor {
4391 selections: editor_state.selections,
4392 pending_selection: editor_state.pending_selection,
4393 scroll_top_anchor: editor_state.scroll_top_anchor,
4394 scroll_x: editor_state.scroll_y,
4395 scroll_y: editor_state.scroll_y,
4396 ..Default::default()
4397 }),
4398 cx,
4399 )
4400 })
4401 })?
4402 .await?;
4403 Ok(context_editor)
4404 }))
4405 }
4406
4407 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
4408 Editor::to_follow_event(event)
4409 }
4410
4411 fn add_event_to_update_proto(
4412 &self,
4413 event: &Self::Event,
4414 update: &mut Option<proto::update_view::Variant>,
4415 cx: &WindowContext,
4416 ) -> bool {
4417 self.editor
4418 .read(cx)
4419 .add_event_to_update_proto(event, update, cx)
4420 }
4421
4422 fn apply_update_proto(
4423 &mut self,
4424 project: &Model<Project>,
4425 message: proto::update_view::Variant,
4426 cx: &mut ViewContext<Self>,
4427 ) -> Task<Result<()>> {
4428 self.editor.update(cx, |editor, cx| {
4429 editor.apply_update_proto(project, message, cx)
4430 })
4431 }
4432
4433 fn is_project_item(&self, _cx: &WindowContext) -> bool {
4434 true
4435 }
4436
4437 fn set_leader_peer_id(
4438 &mut self,
4439 leader_peer_id: Option<proto::PeerId>,
4440 cx: &mut ViewContext<Self>,
4441 ) {
4442 self.editor.update(cx, |editor, cx| {
4443 editor.set_leader_peer_id(leader_peer_id, cx)
4444 })
4445 }
4446
4447 fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
4448 if existing.context.read(cx).id() == self.context.read(cx).id() {
4449 Some(item::Dedup::KeepExisting)
4450 } else {
4451 None
4452 }
4453 }
4454}
4455
4456pub struct ContextEditorToolbarItem {
4457 fs: Arc<dyn Fs>,
4458 active_context_editor: Option<WeakView<ContextEditor>>,
4459 model_summary_editor: View<Editor>,
4460 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4461}
4462
4463impl ContextEditorToolbarItem {
4464 pub fn new(
4465 workspace: &Workspace,
4466 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4467 model_summary_editor: View<Editor>,
4468 ) -> Self {
4469 Self {
4470 fs: workspace.app_state().fs.clone(),
4471 active_context_editor: None,
4472 model_summary_editor,
4473 model_selector_menu_handle,
4474 }
4475 }
4476
4477 fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
4478 let context = &self
4479 .active_context_editor
4480 .as_ref()?
4481 .upgrade()?
4482 .read(cx)
4483 .context;
4484 let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
4485 TokenState::NoTokensLeft {
4486 max_token_count,
4487 token_count,
4488 } => (Color::Error, token_count, max_token_count),
4489 TokenState::HasMoreTokens {
4490 max_token_count,
4491 token_count,
4492 over_warn_threshold,
4493 } => {
4494 let color = if over_warn_threshold {
4495 Color::Warning
4496 } else {
4497 Color::Muted
4498 };
4499 (color, token_count, max_token_count)
4500 }
4501 };
4502 Some(
4503 h_flex()
4504 .gap_0p5()
4505 .child(
4506 Label::new(humanize_token_count(token_count))
4507 .size(LabelSize::Small)
4508 .color(token_count_color),
4509 )
4510 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
4511 .child(
4512 Label::new(humanize_token_count(max_token_count))
4513 .size(LabelSize::Small)
4514 .color(Color::Muted),
4515 ),
4516 )
4517 }
4518}
4519
4520impl Render for ContextEditorToolbarItem {
4521 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4522 let left_side = h_flex()
4523 .group("chat-title-group")
4524 .gap_1()
4525 .items_center()
4526 .flex_grow()
4527 .child(
4528 div()
4529 .w_full()
4530 .when(self.active_context_editor.is_some(), |left_side| {
4531 left_side.child(self.model_summary_editor.clone())
4532 }),
4533 )
4534 .child(
4535 div().visible_on_hover("chat-title-group").child(
4536 IconButton::new("regenerate-context", IconName::RefreshTitle)
4537 .shape(ui::IconButtonShape::Square)
4538 .tooltip(|cx| Tooltip::text("Regenerate Title", cx))
4539 .on_click(cx.listener(move |_, _, cx| {
4540 cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
4541 })),
4542 ),
4543 );
4544 let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
4545 let active_model = LanguageModelRegistry::read_global(cx).active_model();
4546 let right_side = h_flex()
4547 .gap_2()
4548 // TODO display this in a nicer way, once we have a design for it.
4549 // .children({
4550 // let project = self
4551 // .workspace
4552 // .upgrade()
4553 // .map(|workspace| workspace.read(cx).project().downgrade());
4554 //
4555 // let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
4556 // project.and_then(|project| db.remaining_summaries(&project, cx))
4557 // });
4558 // scan_items_remaining
4559 // .map(|remaining_items| format!("Files to scan: {}", remaining_items))
4560 // })
4561 .child(
4562 ModelSelector::new(
4563 self.fs.clone(),
4564 ButtonLike::new("active-model")
4565 .style(ButtonStyle::Subtle)
4566 .child(
4567 h_flex()
4568 .w_full()
4569 .gap_0p5()
4570 .child(
4571 div()
4572 .overflow_x_hidden()
4573 .flex_grow()
4574 .whitespace_nowrap()
4575 .child(match (active_provider, active_model) {
4576 (Some(provider), Some(model)) => h_flex()
4577 .gap_1()
4578 .child(
4579 Icon::new(
4580 model
4581 .icon()
4582 .unwrap_or_else(|| provider.icon()),
4583 )
4584 .color(Color::Muted)
4585 .size(IconSize::XSmall),
4586 )
4587 .child(
4588 Label::new(model.name().0)
4589 .size(LabelSize::Small)
4590 .color(Color::Muted),
4591 )
4592 .into_any_element(),
4593 _ => Label::new("No model selected")
4594 .size(LabelSize::Small)
4595 .color(Color::Muted)
4596 .into_any_element(),
4597 }),
4598 )
4599 .child(
4600 Icon::new(IconName::ChevronDown)
4601 .color(Color::Muted)
4602 .size(IconSize::XSmall),
4603 ),
4604 )
4605 .tooltip(move |cx| {
4606 Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4607 }),
4608 )
4609 .with_handle(self.model_selector_menu_handle.clone()),
4610 )
4611 .children(self.render_remaining_tokens(cx));
4612
4613 h_flex()
4614 .px_0p5()
4615 .size_full()
4616 .gap_2()
4617 .justify_between()
4618 .child(left_side)
4619 .child(right_side)
4620 }
4621}
4622
4623impl ToolbarItemView for ContextEditorToolbarItem {
4624 fn set_active_pane_item(
4625 &mut self,
4626 active_pane_item: Option<&dyn ItemHandle>,
4627 cx: &mut ViewContext<Self>,
4628 ) -> ToolbarItemLocation {
4629 self.active_context_editor = active_pane_item
4630 .and_then(|item| item.act_as::<ContextEditor>(cx))
4631 .map(|editor| editor.downgrade());
4632 cx.notify();
4633 if self.active_context_editor.is_none() {
4634 ToolbarItemLocation::Hidden
4635 } else {
4636 ToolbarItemLocation::PrimaryRight
4637 }
4638 }
4639
4640 fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
4641 cx.notify();
4642 }
4643}
4644
4645impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
4646
4647enum ContextEditorToolbarItemEvent {
4648 RegenerateSummary,
4649}
4650impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
4651
4652pub struct ContextHistory {
4653 picker: View<Picker<SavedContextPickerDelegate>>,
4654 _subscriptions: Vec<Subscription>,
4655 assistant_panel: WeakView<AssistantPanel>,
4656}
4657
4658impl ContextHistory {
4659 fn new(
4660 project: Model<Project>,
4661 context_store: Model<ContextStore>,
4662 assistant_panel: WeakView<AssistantPanel>,
4663 cx: &mut ViewContext<Self>,
4664 ) -> Self {
4665 let picker = cx.new_view(|cx| {
4666 Picker::uniform_list(
4667 SavedContextPickerDelegate::new(project, context_store.clone()),
4668 cx,
4669 )
4670 .modal(false)
4671 .max_height(None)
4672 });
4673
4674 let _subscriptions = vec![
4675 cx.observe(&context_store, |this, _, cx| {
4676 this.picker.update(cx, |picker, cx| picker.refresh(cx));
4677 }),
4678 cx.subscribe(&picker, Self::handle_picker_event),
4679 ];
4680
4681 Self {
4682 picker,
4683 _subscriptions,
4684 assistant_panel,
4685 }
4686 }
4687
4688 fn handle_picker_event(
4689 &mut self,
4690 _: View<Picker<SavedContextPickerDelegate>>,
4691 event: &SavedContextPickerEvent,
4692 cx: &mut ViewContext<Self>,
4693 ) {
4694 let SavedContextPickerEvent::Confirmed(context) = event;
4695 self.assistant_panel
4696 .update(cx, |assistant_panel, cx| match context {
4697 ContextMetadata::Remote(metadata) => {
4698 assistant_panel
4699 .open_remote_context(metadata.id.clone(), cx)
4700 .detach_and_log_err(cx);
4701 }
4702 ContextMetadata::Saved(metadata) => {
4703 assistant_panel
4704 .open_saved_context(metadata.path.clone(), cx)
4705 .detach_and_log_err(cx);
4706 }
4707 })
4708 .ok();
4709 }
4710}
4711
4712#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4713pub enum WorkflowAssistStatus {
4714 Pending,
4715 Confirmed,
4716 Done,
4717 Idle,
4718}
4719
4720impl Render for ContextHistory {
4721 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
4722 div().size_full().child(self.picker.clone())
4723 }
4724}
4725
4726impl FocusableView for ContextHistory {
4727 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4728 self.picker.focus_handle(cx)
4729 }
4730}
4731
4732impl EventEmitter<()> for ContextHistory {}
4733
4734impl Item for ContextHistory {
4735 type Event = ();
4736
4737 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4738 Some("History".into())
4739 }
4740}
4741
4742pub struct ConfigurationView {
4743 focus_handle: FocusHandle,
4744 configuration_views: HashMap<LanguageModelProviderId, AnyView>,
4745 _registry_subscription: Subscription,
4746}
4747
4748impl ConfigurationView {
4749 fn new(cx: &mut ViewContext<Self>) -> Self {
4750 let focus_handle = cx.focus_handle();
4751
4752 let registry_subscription = cx.subscribe(
4753 &LanguageModelRegistry::global(cx),
4754 |this, _, event: &language_model::Event, cx| match event {
4755 language_model::Event::AddedProvider(provider_id) => {
4756 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
4757 if let Some(provider) = provider {
4758 this.add_configuration_view(&provider, cx);
4759 }
4760 }
4761 language_model::Event::RemovedProvider(provider_id) => {
4762 this.remove_configuration_view(provider_id);
4763 }
4764 _ => {}
4765 },
4766 );
4767
4768 let mut this = Self {
4769 focus_handle,
4770 configuration_views: HashMap::default(),
4771 _registry_subscription: registry_subscription,
4772 };
4773 this.build_configuration_views(cx);
4774 this
4775 }
4776
4777 fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
4778 let providers = LanguageModelRegistry::read_global(cx).providers();
4779 for provider in providers {
4780 self.add_configuration_view(&provider, cx);
4781 }
4782 }
4783
4784 fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
4785 self.configuration_views.remove(provider_id);
4786 }
4787
4788 fn add_configuration_view(
4789 &mut self,
4790 provider: &Arc<dyn LanguageModelProvider>,
4791 cx: &mut ViewContext<Self>,
4792 ) {
4793 let configuration_view = provider.configuration_view(cx);
4794 self.configuration_views
4795 .insert(provider.id(), configuration_view);
4796 }
4797
4798 fn render_provider_view(
4799 &mut self,
4800 provider: &Arc<dyn LanguageModelProvider>,
4801 cx: &mut ViewContext<Self>,
4802 ) -> Div {
4803 let provider_id = provider.id().0.clone();
4804 let provider_name = provider.name().0.clone();
4805 let configuration_view = self.configuration_views.get(&provider.id()).cloned();
4806
4807 let open_new_context = cx.listener({
4808 let provider = provider.clone();
4809 move |_, _, cx| {
4810 cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
4811 provider.clone(),
4812 ))
4813 }
4814 });
4815
4816 v_flex()
4817 .gap_2()
4818 .child(
4819 h_flex()
4820 .justify_between()
4821 .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
4822 .when(provider.is_authenticated(cx), move |this| {
4823 this.child(
4824 h_flex().justify_end().child(
4825 Button::new(
4826 SharedString::from(format!("new-context-{provider_id}")),
4827 "Open New Chat",
4828 )
4829 .icon_position(IconPosition::Start)
4830 .icon(IconName::Plus)
4831 .style(ButtonStyle::Filled)
4832 .layer(ElevationIndex::ModalSurface)
4833 .on_click(open_new_context),
4834 ),
4835 )
4836 }),
4837 )
4838 .child(
4839 div()
4840 .p(DynamicSpacing::Base08.rems(cx))
4841 .bg(cx.theme().colors().surface_background)
4842 .border_1()
4843 .border_color(cx.theme().colors().border_variant)
4844 .rounded_md()
4845 .when(configuration_view.is_none(), |this| {
4846 this.child(div().child(Label::new(format!(
4847 "No configuration view for {}",
4848 provider_name
4849 ))))
4850 })
4851 .when_some(configuration_view, |this, configuration_view| {
4852 this.child(configuration_view)
4853 }),
4854 )
4855 }
4856}
4857
4858impl Render for ConfigurationView {
4859 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4860 let providers = LanguageModelRegistry::read_global(cx).providers();
4861 let provider_views = providers
4862 .into_iter()
4863 .map(|provider| self.render_provider_view(&provider, cx))
4864 .collect::<Vec<_>>();
4865
4866 let mut element = v_flex()
4867 .id("assistant-configuration-view")
4868 .track_focus(&self.focus_handle(cx))
4869 .bg(cx.theme().colors().editor_background)
4870 .size_full()
4871 .overflow_y_scroll()
4872 .child(
4873 v_flex()
4874 .p(DynamicSpacing::Base16.rems(cx))
4875 .border_b_1()
4876 .border_color(cx.theme().colors().border)
4877 .gap_1()
4878 .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
4879 .child(
4880 Label::new(
4881 "At least one LLM provider must be configured to use the Assistant.",
4882 )
4883 .color(Color::Muted),
4884 ),
4885 )
4886 .child(
4887 v_flex()
4888 .p(DynamicSpacing::Base16.rems(cx))
4889 .mt_1()
4890 .gap_6()
4891 .flex_1()
4892 .children(provider_views),
4893 )
4894 .into_any();
4895
4896 // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
4897 // because we couldn't the element to take up the size of the parent.
4898 canvas(
4899 move |bounds, cx| {
4900 element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
4901 element
4902 },
4903 |_, mut element, cx| {
4904 element.paint(cx);
4905 },
4906 )
4907 .flex_1()
4908 .w_full()
4909 }
4910}
4911
4912pub enum ConfigurationViewEvent {
4913 NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
4914}
4915
4916impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
4917
4918impl FocusableView for ConfigurationView {
4919 fn focus_handle(&self, _: &AppContext) -> FocusHandle {
4920 self.focus_handle.clone()
4921 }
4922}
4923
4924impl Item for ConfigurationView {
4925 type Event = ConfigurationViewEvent;
4926
4927 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4928 Some("Configuration".into())
4929 }
4930}
4931
4932type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
4933
4934fn render_slash_command_output_toggle(
4935 row: MultiBufferRow,
4936 is_folded: bool,
4937 fold: ToggleFold,
4938 _cx: &mut WindowContext,
4939) -> AnyElement {
4940 Disclosure::new(
4941 ("slash-command-output-fold-indicator", row.0 as u64),
4942 !is_folded,
4943 )
4944 .selected(is_folded)
4945 .on_click(move |_e, cx| fold(!is_folded, cx))
4946 .into_any_element()
4947}
4948
4949fn fold_toggle(
4950 name: &'static str,
4951) -> impl Fn(
4952 MultiBufferRow,
4953 bool,
4954 Arc<dyn Fn(bool, &mut WindowContext<'_>) + Send + Sync>,
4955 &mut WindowContext<'_>,
4956) -> AnyElement {
4957 move |row, is_folded, fold, _cx| {
4958 Disclosure::new((name, row.0 as u64), !is_folded)
4959 .selected(is_folded)
4960 .on_click(move |_e, cx| fold(!is_folded, cx))
4961 .into_any_element()
4962 }
4963}
4964
4965fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
4966 FoldPlaceholder {
4967 render: Arc::new({
4968 move |fold_id, fold_range, _cx| {
4969 let editor = editor.clone();
4970 ButtonLike::new(fold_id)
4971 .style(ButtonStyle::Filled)
4972 .layer(ElevationIndex::ElevatedSurface)
4973 .child(Icon::new(IconName::TextSnippet))
4974 .child(Label::new(title.clone()).single_line())
4975 .on_click(move |_, cx| {
4976 editor
4977 .update(cx, |editor, cx| {
4978 let buffer_start = fold_range
4979 .start
4980 .to_point(&editor.buffer().read(cx).read(cx));
4981 let buffer_row = MultiBufferRow(buffer_start.row);
4982 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4983 })
4984 .ok();
4985 })
4986 .into_any_element()
4987 }
4988 }),
4989 merge_adjacent: false,
4990 ..Default::default()
4991 }
4992}
4993
4994fn render_quote_selection_output_toggle(
4995 row: MultiBufferRow,
4996 is_folded: bool,
4997 fold: ToggleFold,
4998 _cx: &mut WindowContext,
4999) -> AnyElement {
5000 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
5001 .selected(is_folded)
5002 .on_click(move |_e, cx| fold(!is_folded, cx))
5003 .into_any_element()
5004}
5005
5006fn render_pending_slash_command_gutter_decoration(
5007 row: MultiBufferRow,
5008 status: &PendingSlashCommandStatus,
5009 confirm_command: Arc<dyn Fn(&mut WindowContext)>,
5010) -> AnyElement {
5011 let mut icon = IconButton::new(
5012 ("slash-command-gutter-decoration", row.0),
5013 ui::IconName::TriangleRight,
5014 )
5015 .on_click(move |_e, cx| confirm_command(cx))
5016 .icon_size(ui::IconSize::Small)
5017 .size(ui::ButtonSize::None);
5018
5019 match status {
5020 PendingSlashCommandStatus::Idle => {
5021 icon = icon.icon_color(Color::Muted);
5022 }
5023 PendingSlashCommandStatus::Running { .. } => {
5024 icon = icon.selected(true);
5025 }
5026 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
5027 }
5028
5029 icon.into_any_element()
5030}
5031
5032fn render_docs_slash_command_trailer(
5033 row: MultiBufferRow,
5034 command: ParsedSlashCommand,
5035 cx: &mut WindowContext,
5036) -> AnyElement {
5037 if command.arguments.is_empty() {
5038 return Empty.into_any();
5039 }
5040 let args = DocsSlashCommandArgs::parse(&command.arguments);
5041
5042 let Some(store) = args
5043 .provider()
5044 .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
5045 else {
5046 return Empty.into_any();
5047 };
5048
5049 let Some(package) = args.package() else {
5050 return Empty.into_any();
5051 };
5052
5053 let mut children = Vec::new();
5054
5055 if store.is_indexing(&package) {
5056 children.push(
5057 div()
5058 .id(("crates-being-indexed", row.0))
5059 .child(Icon::new(IconName::ArrowCircle).with_animation(
5060 "arrow-circle",
5061 Animation::new(Duration::from_secs(4)).repeat(),
5062 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
5063 ))
5064 .tooltip({
5065 let package = package.clone();
5066 move |cx| Tooltip::text(format!("Indexing {package}…"), cx)
5067 })
5068 .into_any_element(),
5069 );
5070 }
5071
5072 if let Some(latest_error) = store.latest_error_for_package(&package) {
5073 children.push(
5074 div()
5075 .id(("latest-error", row.0))
5076 .child(
5077 Icon::new(IconName::Warning)
5078 .size(IconSize::Small)
5079 .color(Color::Warning),
5080 )
5081 .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
5082 .into_any_element(),
5083 )
5084 }
5085
5086 let is_indexing = store.is_indexing(&package);
5087 let latest_error = store.latest_error_for_package(&package);
5088
5089 if !is_indexing && latest_error.is_none() {
5090 return Empty.into_any();
5091 }
5092
5093 h_flex().gap_2().children(children).into_any_element()
5094}
5095
5096fn make_lsp_adapter_delegate(
5097 project: &Model<Project>,
5098 cx: &mut AppContext,
5099) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
5100 project.update(cx, |project, cx| {
5101 // TODO: Find the right worktree.
5102 let Some(worktree) = project.worktrees(cx).next() else {
5103 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
5104 };
5105 let http_client = project.client().http_client().clone();
5106 project.lsp_store().update(cx, |lsp_store, cx| {
5107 Ok(Some(LocalLspAdapterDelegate::new(
5108 lsp_store,
5109 &worktree,
5110 http_client,
5111 project.fs().clone(),
5112 cx,
5113 ) as Arc<dyn LspAdapterDelegate>))
5114 })
5115 })
5116}
5117
5118enum PendingSlashCommand {}
5119
5120fn invoked_slash_command_fold_placeholder(
5121 command_id: InvokedSlashCommandId,
5122 context: WeakModel<Context>,
5123) -> FoldPlaceholder {
5124 FoldPlaceholder {
5125 constrain_width: false,
5126 merge_adjacent: false,
5127 render: Arc::new(move |fold_id, _, cx| {
5128 let Some(context) = context.upgrade() else {
5129 return Empty.into_any();
5130 };
5131
5132 let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
5133 return Empty.into_any();
5134 };
5135
5136 h_flex()
5137 .id(fold_id)
5138 .px_1()
5139 .ml_6()
5140 .gap_2()
5141 .bg(cx.theme().colors().surface_background)
5142 .rounded_md()
5143 .child(Label::new(format!("/{}", command.name.clone())))
5144 .map(|parent| match &command.status {
5145 InvokedSlashCommandStatus::Running(_) => {
5146 parent.child(Icon::new(IconName::ArrowCircle).with_animation(
5147 "arrow-circle",
5148 Animation::new(Duration::from_secs(4)).repeat(),
5149 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
5150 ))
5151 }
5152 InvokedSlashCommandStatus::Error(message) => parent.child(
5153 Label::new(format!("error: {message}"))
5154 .single_line()
5155 .color(Color::Error),
5156 ),
5157 InvokedSlashCommandStatus::Finished => parent,
5158 })
5159 .into_any_element()
5160 }),
5161 type_tag: Some(TypeId::of::<PendingSlashCommand>()),
5162 }
5163}
5164
5165enum TokenState {
5166 NoTokensLeft {
5167 max_token_count: usize,
5168 token_count: usize,
5169 },
5170 HasMoreTokens {
5171 max_token_count: usize,
5172 token_count: usize,
5173 over_warn_threshold: bool,
5174 },
5175}
5176
5177fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
5178 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
5179
5180 let model = LanguageModelRegistry::read_global(cx).active_model()?;
5181 let token_count = context.read(cx).token_count()?;
5182 let max_token_count = model.max_token_count();
5183
5184 let remaining_tokens = max_token_count as isize - token_count as isize;
5185 let token_state = if remaining_tokens <= 0 {
5186 TokenState::NoTokensLeft {
5187 max_token_count,
5188 token_count,
5189 }
5190 } else {
5191 let over_warn_threshold =
5192 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
5193 TokenState::HasMoreTokens {
5194 max_token_count,
5195 token_count,
5196 over_warn_threshold,
5197 }
5198 };
5199 Some(token_state)
5200}
5201
5202fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
5203 let image_size = data
5204 .size(0)
5205 .map(|dimension| Pixels::from(u32::from(dimension)));
5206 let image_ratio = image_size.width / image_size.height;
5207 let bounds_ratio = max_size.width / max_size.height;
5208
5209 if image_size.width > max_size.width || image_size.height > max_size.height {
5210 if bounds_ratio > image_ratio {
5211 size(
5212 image_size.width * (max_size.height / image_size.height),
5213 max_size.height,
5214 )
5215 } else {
5216 size(
5217 max_size.width,
5218 image_size.height * (max_size.width / image_size.width),
5219 )
5220 }
5221 } else {
5222 size(image_size.width, image_size.height)
5223 }
5224}
5225
5226enum ConfigurationError {
5227 NoProvider,
5228 ProviderNotAuthenticated,
5229}
5230
5231fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
5232 let provider = LanguageModelRegistry::read_global(cx).active_provider();
5233 let is_authenticated = provider
5234 .as_ref()
5235 .map_or(false, |provider| provider.is_authenticated(cx));
5236
5237 if provider.is_some() && is_authenticated {
5238 return None;
5239 }
5240
5241 if provider.is_none() {
5242 return Some(ConfigurationError::NoProvider);
5243 }
5244
5245 if !is_authenticated {
5246 return Some(ConfigurationError::ProviderNotAuthenticated);
5247 }
5248
5249 None
5250}
5251
5252#[cfg(test)]
5253mod tests {
5254 use super::*;
5255 use gpui::{AppContext, Context};
5256 use language::Buffer;
5257 use unindent::Unindent;
5258
5259 #[gpui::test]
5260 fn test_find_code_blocks(cx: &mut AppContext) {
5261 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
5262
5263 let buffer = cx.new_model(|cx| {
5264 let text = r#"
5265 line 0
5266 line 1
5267 ```rust
5268 fn main() {}
5269 ```
5270 line 5
5271 line 6
5272 line 7
5273 ```go
5274 func main() {}
5275 ```
5276 line 11
5277 ```
5278 this is plain text code block
5279 ```
5280
5281 ```go
5282 func another() {}
5283 ```
5284 line 19
5285 "#
5286 .unindent();
5287 let mut buffer = Buffer::local(text, cx);
5288 buffer.set_language(Some(markdown.clone()), cx);
5289 buffer
5290 });
5291 let snapshot = buffer.read(cx).snapshot();
5292
5293 let code_blocks = vec![
5294 Point::new(3, 0)..Point::new(4, 0),
5295 Point::new(9, 0)..Point::new(10, 0),
5296 Point::new(13, 0)..Point::new(14, 0),
5297 Point::new(17, 0)..Point::new(18, 0),
5298 ]
5299 .into_iter()
5300 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
5301 .collect::<Vec<_>>();
5302
5303 let expected_results = vec![
5304 (0, None),
5305 (1, None),
5306 (2, Some(code_blocks[0].clone())),
5307 (3, Some(code_blocks[0].clone())),
5308 (4, Some(code_blocks[0].clone())),
5309 (5, None),
5310 (6, None),
5311 (7, None),
5312 (8, Some(code_blocks[1].clone())),
5313 (9, Some(code_blocks[1].clone())),
5314 (10, Some(code_blocks[1].clone())),
5315 (11, None),
5316 (12, Some(code_blocks[2].clone())),
5317 (13, Some(code_blocks[2].clone())),
5318 (14, Some(code_blocks[2].clone())),
5319 (15, None),
5320 (16, Some(code_blocks[3].clone())),
5321 (17, Some(code_blocks[3].clone())),
5322 (18, Some(code_blocks[3].clone())),
5323 (19, None),
5324 ];
5325
5326 for (row, expected) in expected_results {
5327 let offset = snapshot.point_to_offset(Point::new(row, 0));
5328 let range = find_surrounding_code_block(&snapshot, offset);
5329 assert_eq!(range, expected, "unexpected result on row {:?}", row);
5330 }
5331 }
5332}