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