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