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