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(Editor::single_line);
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(ConfigurationView::new);
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::ToolFinished {
2202 tool_use_id,
2203 output_range,
2204 } => {
2205 self.editor.update(cx, |editor, cx| {
2206 let buffer = editor.buffer().read(cx).snapshot(cx);
2207 let (excerpt_id, _buffer_id, _) = buffer.as_singleton().unwrap();
2208 let excerpt_id = *excerpt_id;
2209
2210 let placeholder = FoldPlaceholder {
2211 render: render_fold_icon_button(
2212 cx.view().downgrade(),
2213 IconName::PocketKnife,
2214 format!("Tool Result: {tool_use_id}").into(),
2215 ),
2216 constrain_width: false,
2217 merge_adjacent: false,
2218 };
2219 let render_trailer =
2220 move |_row, _unfold, _cx: &mut WindowContext| Empty.into_any();
2221
2222 let start = buffer
2223 .anchor_in_excerpt(excerpt_id, output_range.start)
2224 .unwrap();
2225 let end = buffer
2226 .anchor_in_excerpt(excerpt_id, output_range.end)
2227 .unwrap();
2228
2229 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2230
2231 let crease = Crease::new(
2232 start..end,
2233 placeholder,
2234 fold_toggle("tool-use"),
2235 render_trailer,
2236 );
2237
2238 editor.insert_creases([crease], cx);
2239 editor.fold_at(&FoldAt { buffer_row }, cx);
2240 });
2241 }
2242 ContextEvent::Operation(_) => {}
2243 ContextEvent::ShowAssistError(error_message) => {
2244 self.error_message = Some(error_message.clone());
2245 }
2246 }
2247 }
2248
2249 fn workflow_steps_updated(
2250 &mut self,
2251 removed: &Vec<Range<text::Anchor>>,
2252 updated: &Vec<Range<text::Anchor>>,
2253 cx: &mut ViewContext<ContextEditor>,
2254 ) {
2255 let this = cx.view().downgrade();
2256 let mut removed_crease_ids = Vec::new();
2257 let mut removed_block_ids = HashSet::default();
2258 let mut editors_to_close = Vec::new();
2259 for range in removed {
2260 if let Some(state) = self.workflow_steps.remove(range) {
2261 editors_to_close.extend(self.hide_workflow_step(range.clone(), cx));
2262 removed_block_ids.insert(state.header_block_id);
2263 removed_crease_ids.push(state.header_crease_id);
2264 removed_block_ids.extend(state.footer_block_id);
2265 removed_crease_ids.extend(state.footer_crease_id);
2266 }
2267 }
2268
2269 for range in updated {
2270 editors_to_close.extend(self.hide_workflow_step(range.clone(), cx));
2271 }
2272
2273 self.editor.update(cx, |editor, cx| {
2274 let snapshot = editor.snapshot(cx);
2275 let multibuffer = &snapshot.buffer_snapshot;
2276 let (&excerpt_id, _, buffer) = multibuffer.as_singleton().unwrap();
2277
2278 for range in updated {
2279 let Some(step) = self.context.read(cx).workflow_step_for_range(&range, cx) else {
2280 continue;
2281 };
2282
2283 let resolution = step.resolution.clone();
2284 let header_start = step.range.start;
2285 let header_end = if buffer.contains_str_at(step.leading_tags_end, "\n") {
2286 buffer.anchor_before(step.leading_tags_end.to_offset(&buffer) + 1)
2287 } else {
2288 step.leading_tags_end
2289 };
2290 let header_range = multibuffer
2291 .anchor_in_excerpt(excerpt_id, header_start)
2292 .unwrap()
2293 ..multibuffer
2294 .anchor_in_excerpt(excerpt_id, header_end)
2295 .unwrap();
2296 let footer_range = step.trailing_tag_start.map(|start| {
2297 let mut step_range_end = step.range.end.to_offset(&buffer);
2298 if buffer.contains_str_at(step_range_end, "\n") {
2299 // Only include the newline if it belongs to the same message.
2300 let messages = self
2301 .context
2302 .read(cx)
2303 .messages_for_offsets([step_range_end, step_range_end + 1], cx);
2304 if messages.len() == 1 {
2305 step_range_end += 1;
2306 }
2307 }
2308
2309 let end = buffer.anchor_before(step_range_end);
2310 multibuffer.anchor_in_excerpt(excerpt_id, start).unwrap()
2311 ..multibuffer.anchor_in_excerpt(excerpt_id, end).unwrap()
2312 });
2313
2314 let block_ids = editor.insert_blocks(
2315 [BlockProperties {
2316 position: header_range.start,
2317 height: 1,
2318 style: BlockStyle::Flex,
2319 render: Box::new({
2320 let this = this.clone();
2321 let range = step.range.clone();
2322 move |cx| {
2323 let block_id = cx.block_id;
2324 let max_width = cx.max_width;
2325 let gutter_width = cx.gutter_dimensions.full_width();
2326 this.update(&mut **cx, |this, cx| {
2327 this.render_workflow_step_header(
2328 range.clone(),
2329 max_width,
2330 gutter_width,
2331 block_id,
2332 cx,
2333 )
2334 })
2335 .ok()
2336 .flatten()
2337 .unwrap_or_else(|| Empty.into_any())
2338 }
2339 }),
2340 disposition: BlockDisposition::Above,
2341 priority: 0,
2342 }]
2343 .into_iter()
2344 .chain(footer_range.as_ref().map(|footer_range| {
2345 return BlockProperties {
2346 position: footer_range.end,
2347 height: 1,
2348 style: BlockStyle::Flex,
2349 render: Box::new({
2350 let this = this.clone();
2351 let range = step.range.clone();
2352 move |cx| {
2353 let max_width = cx.max_width;
2354 let gutter_width = cx.gutter_dimensions.full_width();
2355 this.update(&mut **cx, |this, cx| {
2356 this.render_workflow_step_footer(
2357 range.clone(),
2358 max_width,
2359 gutter_width,
2360 cx,
2361 )
2362 })
2363 .ok()
2364 .flatten()
2365 .unwrap_or_else(|| Empty.into_any())
2366 }
2367 }),
2368 disposition: BlockDisposition::Below,
2369 priority: 0,
2370 };
2371 })),
2372 None,
2373 cx,
2374 );
2375
2376 let header_placeholder = FoldPlaceholder {
2377 render: Arc::new(move |_, _crease_range, _cx| Empty.into_any()),
2378 constrain_width: false,
2379 merge_adjacent: false,
2380 };
2381 let footer_placeholder = FoldPlaceholder {
2382 render: render_fold_icon_button(
2383 cx.view().downgrade(),
2384 IconName::Code,
2385 "Edits".into(),
2386 ),
2387 constrain_width: false,
2388 merge_adjacent: false,
2389 };
2390
2391 let new_crease_ids = editor.insert_creases(
2392 [Crease::new(
2393 header_range.clone(),
2394 header_placeholder.clone(),
2395 fold_toggle("step-header"),
2396 |_, _, _| Empty.into_any_element(),
2397 )]
2398 .into_iter()
2399 .chain(footer_range.clone().map(|footer_range| {
2400 Crease::new(
2401 footer_range,
2402 footer_placeholder.clone(),
2403 |row, is_folded, fold, cx| {
2404 if is_folded {
2405 Empty.into_any_element()
2406 } else {
2407 fold_toggle("step-footer")(row, is_folded, fold, cx)
2408 }
2409 },
2410 |_, _, _| Empty.into_any_element(),
2411 )
2412 })),
2413 cx,
2414 );
2415
2416 let state = WorkflowStepViewState {
2417 header_block_id: block_ids[0],
2418 header_crease_id: new_crease_ids[0],
2419 footer_block_id: block_ids.get(1).copied(),
2420 footer_crease_id: new_crease_ids.get(1).copied(),
2421 resolution,
2422 assist: None,
2423 };
2424
2425 let mut folds_to_insert = [(header_range.clone(), header_placeholder)]
2426 .into_iter()
2427 .chain(
2428 footer_range
2429 .clone()
2430 .map(|range| (range, footer_placeholder)),
2431 )
2432 .collect::<Vec<_>>();
2433
2434 match self.workflow_steps.entry(range.clone()) {
2435 hash_map::Entry::Vacant(entry) => {
2436 entry.insert(state);
2437 }
2438 hash_map::Entry::Occupied(mut entry) => {
2439 let entry = entry.get_mut();
2440 removed_block_ids.insert(entry.header_block_id);
2441 removed_crease_ids.push(entry.header_crease_id);
2442 removed_block_ids.extend(entry.footer_block_id);
2443 removed_crease_ids.extend(entry.footer_crease_id);
2444 folds_to_insert.retain(|(range, _)| snapshot.intersects_fold(range.start));
2445 *entry = state;
2446 }
2447 }
2448
2449 editor.unfold_ranges(
2450 [header_range.clone()]
2451 .into_iter()
2452 .chain(footer_range.clone()),
2453 true,
2454 false,
2455 cx,
2456 );
2457
2458 if !folds_to_insert.is_empty() {
2459 editor.fold_ranges(folds_to_insert, false, cx);
2460 }
2461 }
2462
2463 editor.remove_creases(removed_crease_ids, cx);
2464 editor.remove_blocks(removed_block_ids, None, cx);
2465 });
2466
2467 for (editor, editor_was_open) in editors_to_close {
2468 self.close_workflow_editor(cx, editor, editor_was_open);
2469 }
2470
2471 self.update_active_workflow_step(cx);
2472 }
2473
2474 fn insert_slash_command_output_sections(
2475 &mut self,
2476 sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
2477 expand_result: bool,
2478 cx: &mut ViewContext<Self>,
2479 ) {
2480 self.editor.update(cx, |editor, cx| {
2481 let buffer = editor.buffer().read(cx).snapshot(cx);
2482 let excerpt_id = *buffer.as_singleton().unwrap().0;
2483 let mut buffer_rows_to_fold = BTreeSet::new();
2484 let mut creases = Vec::new();
2485 for section in sections {
2486 let start = buffer
2487 .anchor_in_excerpt(excerpt_id, section.range.start)
2488 .unwrap();
2489 let end = buffer
2490 .anchor_in_excerpt(excerpt_id, section.range.end)
2491 .unwrap();
2492 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
2493 buffer_rows_to_fold.insert(buffer_row);
2494 creases.push(Crease::new(
2495 start..end,
2496 FoldPlaceholder {
2497 render: render_fold_icon_button(
2498 cx.view().downgrade(),
2499 section.icon,
2500 section.label.clone(),
2501 ),
2502 constrain_width: false,
2503 merge_adjacent: false,
2504 },
2505 render_slash_command_output_toggle,
2506 |_, _, _| Empty.into_any_element(),
2507 ));
2508 }
2509
2510 editor.insert_creases(creases, cx);
2511
2512 if expand_result {
2513 buffer_rows_to_fold.clear();
2514 }
2515 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
2516 editor.fold_at(&FoldAt { buffer_row }, cx);
2517 }
2518 });
2519 }
2520
2521 fn handle_editor_event(
2522 &mut self,
2523 _: View<Editor>,
2524 event: &EditorEvent,
2525 cx: &mut ViewContext<Self>,
2526 ) {
2527 match event {
2528 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2529 let cursor_scroll_position = self.cursor_scroll_position(cx);
2530 if *autoscroll {
2531 self.scroll_position = cursor_scroll_position;
2532 } else if self.scroll_position != cursor_scroll_position {
2533 self.scroll_position = None;
2534 }
2535 }
2536 EditorEvent::SelectionsChanged { .. } => {
2537 self.scroll_position = self.cursor_scroll_position(cx);
2538 self.update_active_workflow_step(cx);
2539 }
2540 _ => {}
2541 }
2542 cx.emit(event.clone());
2543 }
2544
2545 fn active_workflow_step(&self) -> Option<(Range<text::Anchor>, &WorkflowStepViewState)> {
2546 let step = self.active_workflow_step.as_ref()?;
2547 Some((step.range.clone(), self.workflow_steps.get(&step.range)?))
2548 }
2549
2550 fn update_active_workflow_step(&mut self, cx: &mut ViewContext<Self>) {
2551 let newest_cursor = self.editor.read(cx).selections.newest::<usize>(cx).head();
2552 let context = self.context.read(cx);
2553
2554 let new_step = context
2555 .workflow_step_containing(newest_cursor, cx)
2556 .map(|step| ActiveWorkflowStep {
2557 resolved: step.resolution.is_some(),
2558 range: step.range.clone(),
2559 });
2560
2561 if new_step.as_ref() != self.active_workflow_step.as_ref() {
2562 let mut old_editor = None;
2563 let mut old_editor_was_open = None;
2564 if let Some(old_step) = self.active_workflow_step.take() {
2565 (old_editor, old_editor_was_open) =
2566 self.hide_workflow_step(old_step.range, cx).unzip();
2567 }
2568
2569 let mut new_editor = None;
2570 if let Some(new_step) = new_step {
2571 new_editor = self.show_workflow_step(new_step.range.clone(), cx);
2572 self.active_workflow_step = Some(new_step);
2573 }
2574
2575 if new_editor != old_editor {
2576 if let Some((old_editor, old_editor_was_open)) = old_editor.zip(old_editor_was_open)
2577 {
2578 self.close_workflow_editor(cx, old_editor, old_editor_was_open)
2579 }
2580 }
2581 }
2582 }
2583
2584 fn hide_workflow_step(
2585 &mut self,
2586 step_range: Range<language::Anchor>,
2587 cx: &mut ViewContext<Self>,
2588 ) -> Option<(View<Editor>, bool)> {
2589 if let Some(step) = self.workflow_steps.get_mut(&step_range) {
2590 let assist = step.assist.as_ref()?;
2591 let editor = assist.editor.upgrade()?;
2592
2593 if matches!(step.status(cx), WorkflowStepStatus::Idle) {
2594 let assist = step.assist.take().unwrap();
2595 InlineAssistant::update_global(cx, |assistant, cx| {
2596 for assist_id in assist.assist_ids {
2597 assistant.finish_assist(assist_id, true, cx)
2598 }
2599 });
2600 return Some((editor, assist.editor_was_open));
2601 }
2602 }
2603
2604 None
2605 }
2606
2607 fn close_workflow_editor(
2608 &mut self,
2609 cx: &mut ViewContext<ContextEditor>,
2610 editor: View<Editor>,
2611 editor_was_open: bool,
2612 ) {
2613 self.workspace
2614 .update(cx, |workspace, cx| {
2615 if let Some(pane) = workspace.pane_for(&editor) {
2616 pane.update(cx, |pane, cx| {
2617 let item_id = editor.entity_id();
2618 if !editor_was_open && !editor.read(cx).is_focused(cx) {
2619 pane.close_item_by_id(item_id, SaveIntent::Skip, cx)
2620 .detach_and_log_err(cx);
2621 }
2622 });
2623 }
2624 })
2625 .ok();
2626 }
2627
2628 fn show_workflow_step(
2629 &mut self,
2630 step_range: Range<language::Anchor>,
2631 cx: &mut ViewContext<Self>,
2632 ) -> Option<View<Editor>> {
2633 let step = self.workflow_steps.get_mut(&step_range)?;
2634
2635 let mut editor_to_return = None;
2636 let mut scroll_to_assist_id = None;
2637 match step.status(cx) {
2638 WorkflowStepStatus::Idle => {
2639 if let Some(assist) = step.assist.as_ref() {
2640 scroll_to_assist_id = assist.assist_ids.first().copied();
2641 } else if let Some(Ok(resolved)) = step.resolution.clone().as_deref() {
2642 step.assist = Self::open_assists_for_step(
2643 &resolved,
2644 &self.project,
2645 &self.assistant_panel,
2646 &self.workspace,
2647 cx,
2648 );
2649 editor_to_return = step
2650 .assist
2651 .as_ref()
2652 .and_then(|assist| assist.editor.upgrade());
2653 }
2654 }
2655 WorkflowStepStatus::Pending => {
2656 if let Some(assist) = step.assist.as_ref() {
2657 let assistant = InlineAssistant::global(cx);
2658 scroll_to_assist_id = assist
2659 .assist_ids
2660 .iter()
2661 .copied()
2662 .find(|assist_id| assistant.assist_status(*assist_id, cx).is_pending());
2663 }
2664 }
2665 WorkflowStepStatus::Done => {
2666 if let Some(assist) = step.assist.as_ref() {
2667 scroll_to_assist_id = assist.assist_ids.first().copied();
2668 }
2669 }
2670 _ => {}
2671 }
2672
2673 if let Some(assist_id) = scroll_to_assist_id {
2674 if let Some(assist_editor) = step
2675 .assist
2676 .as_ref()
2677 .and_then(|assists| assists.editor.upgrade())
2678 {
2679 editor_to_return = Some(assist_editor.clone());
2680 self.workspace
2681 .update(cx, |workspace, cx| {
2682 workspace.activate_item(&assist_editor, false, false, cx);
2683 })
2684 .ok();
2685 InlineAssistant::update_global(cx, |assistant, cx| {
2686 assistant.scroll_to_assist(assist_id, cx)
2687 });
2688 }
2689 }
2690
2691 editor_to_return
2692 }
2693
2694 fn open_assists_for_step(
2695 resolved_step: &WorkflowStepResolution,
2696 project: &Model<Project>,
2697 assistant_panel: &WeakView<AssistantPanel>,
2698 workspace: &WeakView<Workspace>,
2699 cx: &mut ViewContext<Self>,
2700 ) -> Option<WorkflowAssist> {
2701 let assistant_panel = assistant_panel.upgrade()?;
2702 if resolved_step.suggestion_groups.is_empty() {
2703 return None;
2704 }
2705
2706 let editor;
2707 let mut editor_was_open = false;
2708 let mut suggestion_groups = Vec::new();
2709 if resolved_step.suggestion_groups.len() == 1
2710 && resolved_step
2711 .suggestion_groups
2712 .values()
2713 .next()
2714 .unwrap()
2715 .len()
2716 == 1
2717 {
2718 // If there's only one buffer and one suggestion group, open it directly
2719 let (buffer, groups) = resolved_step.suggestion_groups.iter().next().unwrap();
2720 let group = groups.into_iter().next().unwrap();
2721 editor = workspace
2722 .update(cx, |workspace, cx| {
2723 let active_pane = workspace.active_pane().clone();
2724 editor_was_open =
2725 workspace.is_project_item_open::<Editor>(&active_pane, buffer, cx);
2726 workspace.open_project_item::<Editor>(
2727 active_pane,
2728 buffer.clone(),
2729 false,
2730 false,
2731 cx,
2732 )
2733 })
2734 .log_err()?;
2735 let (&excerpt_id, _, _) = editor
2736 .read(cx)
2737 .buffer()
2738 .read(cx)
2739 .read(cx)
2740 .as_singleton()
2741 .unwrap();
2742
2743 // Scroll the editor to the suggested assist
2744 editor.update(cx, |editor, cx| {
2745 let multibuffer = editor.buffer().read(cx).snapshot(cx);
2746 let (&excerpt_id, _, buffer) = multibuffer.as_singleton().unwrap();
2747 let anchor = if group.context_range.start.to_offset(buffer) == 0 {
2748 Anchor::min()
2749 } else {
2750 multibuffer
2751 .anchor_in_excerpt(excerpt_id, group.context_range.start)
2752 .unwrap()
2753 };
2754
2755 editor.set_scroll_anchor(
2756 ScrollAnchor {
2757 offset: gpui::Point::default(),
2758 anchor,
2759 },
2760 cx,
2761 );
2762 });
2763
2764 suggestion_groups.push((excerpt_id, group));
2765 } else {
2766 // If there are multiple buffers or suggestion groups, create a multibuffer
2767 let multibuffer = cx.new_model(|cx| {
2768 let replica_id = project.read(cx).replica_id();
2769 let mut multibuffer = MultiBuffer::new(replica_id, Capability::ReadWrite)
2770 .with_title(resolved_step.title.clone());
2771 for (buffer, groups) in &resolved_step.suggestion_groups {
2772 let excerpt_ids = multibuffer.push_excerpts(
2773 buffer.clone(),
2774 groups.iter().map(|suggestion_group| ExcerptRange {
2775 context: suggestion_group.context_range.clone(),
2776 primary: None,
2777 }),
2778 cx,
2779 );
2780 suggestion_groups.extend(excerpt_ids.into_iter().zip(groups));
2781 }
2782 multibuffer
2783 });
2784
2785 editor = cx.new_view(|cx| {
2786 Editor::for_multibuffer(multibuffer, Some(project.clone()), true, cx)
2787 });
2788 workspace
2789 .update(cx, |workspace, cx| {
2790 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
2791 })
2792 .log_err()?;
2793 }
2794
2795 let mut assist_ids = Vec::new();
2796 for (excerpt_id, suggestion_group) in suggestion_groups {
2797 for suggestion in &suggestion_group.suggestions {
2798 assist_ids.extend(suggestion.show(
2799 &editor,
2800 excerpt_id,
2801 workspace,
2802 &assistant_panel,
2803 cx,
2804 ));
2805 }
2806 }
2807
2808 Some(WorkflowAssist {
2809 assist_ids,
2810 editor: editor.downgrade(),
2811 editor_was_open,
2812 })
2813 }
2814
2815 fn handle_editor_search_event(
2816 &mut self,
2817 _: View<Editor>,
2818 event: &SearchEvent,
2819 cx: &mut ViewContext<Self>,
2820 ) {
2821 cx.emit(event.clone());
2822 }
2823
2824 fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2825 self.editor.update(cx, |editor, cx| {
2826 let snapshot = editor.snapshot(cx);
2827 let cursor = editor.selections.newest_anchor().head();
2828 let cursor_row = cursor
2829 .to_display_point(&snapshot.display_snapshot)
2830 .row()
2831 .as_f32();
2832 let scroll_position = editor
2833 .scroll_manager
2834 .anchor()
2835 .scroll_position(&snapshot.display_snapshot);
2836
2837 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2838 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2839 Some(ScrollPosition {
2840 cursor,
2841 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2842 })
2843 } else {
2844 None
2845 }
2846 })
2847 }
2848
2849 fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2850 self.editor.update(cx, |editor, cx| {
2851 let buffer = editor.buffer().read(cx).snapshot(cx);
2852
2853 let excerpt_id = *buffer.as_singleton().unwrap().0;
2854 let mut old_blocks = std::mem::take(&mut self.blocks);
2855 let mut blocks_to_remove: HashMap<_, _> = old_blocks
2856 .iter()
2857 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
2858 .collect();
2859 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
2860
2861 let render_block = |message: MessageMetadata| -> RenderBlock {
2862 Box::new({
2863 let context = self.context.clone();
2864 move |cx| {
2865 let message_id = MessageId(message.timestamp);
2866 let show_spinner = message.role == Role::Assistant
2867 && message.status == MessageStatus::Pending;
2868
2869 let label = match message.role {
2870 Role::User => {
2871 Label::new("You").color(Color::Default).into_any_element()
2872 }
2873 Role::Assistant => {
2874 let label = Label::new("Assistant").color(Color::Info);
2875 if show_spinner {
2876 label
2877 .with_animation(
2878 "pulsating-label",
2879 Animation::new(Duration::from_secs(2))
2880 .repeat()
2881 .with_easing(pulsating_between(0.4, 0.8)),
2882 |label, delta| label.alpha(delta),
2883 )
2884 .into_any_element()
2885 } else {
2886 label.into_any_element()
2887 }
2888 }
2889
2890 Role::System => Label::new("System")
2891 .color(Color::Warning)
2892 .into_any_element(),
2893 };
2894
2895 let sender = ButtonLike::new("role")
2896 .style(ButtonStyle::Filled)
2897 .child(label)
2898 .tooltip(|cx| {
2899 Tooltip::with_meta(
2900 "Toggle message role",
2901 None,
2902 "Available roles: You (User), Assistant, System",
2903 cx,
2904 )
2905 })
2906 .on_click({
2907 let context = context.clone();
2908 move |_, cx| {
2909 context.update(cx, |context, cx| {
2910 context.cycle_message_roles(
2911 HashSet::from_iter(Some(message_id)),
2912 cx,
2913 )
2914 })
2915 }
2916 });
2917
2918 h_flex()
2919 .id(("message_header", message_id.as_u64()))
2920 .pl(cx.gutter_dimensions.full_width())
2921 .h_11()
2922 .w_full()
2923 .relative()
2924 .gap_1()
2925 .child(sender)
2926 .children(match &message.cache {
2927 Some(cache) if cache.is_final_anchor => match cache.status {
2928 CacheStatus::Cached => Some(
2929 div()
2930 .id("cached")
2931 .child(
2932 Icon::new(IconName::DatabaseZap)
2933 .size(IconSize::XSmall)
2934 .color(Color::Hint),
2935 )
2936 .tooltip(|cx| {
2937 Tooltip::with_meta(
2938 "Context cached",
2939 None,
2940 "Large messages cached to optimize performance",
2941 cx,
2942 )
2943 })
2944 .into_any_element(),
2945 ),
2946 CacheStatus::Pending => Some(
2947 div()
2948 .child(
2949 Icon::new(IconName::Ellipsis)
2950 .size(IconSize::XSmall)
2951 .color(Color::Hint),
2952 )
2953 .into_any_element(),
2954 ),
2955 },
2956 _ => None,
2957 })
2958 .children(match &message.status {
2959 MessageStatus::Error(error) => Some(
2960 Button::new("show-error", "Error")
2961 .color(Color::Error)
2962 .selected_label_color(Color::Error)
2963 .selected_icon_color(Color::Error)
2964 .icon(IconName::XCircle)
2965 .icon_color(Color::Error)
2966 .icon_size(IconSize::Small)
2967 .icon_position(IconPosition::Start)
2968 .tooltip(move |cx| {
2969 Tooltip::with_meta(
2970 "Error interacting with language model",
2971 None,
2972 "Click for more details",
2973 cx,
2974 )
2975 })
2976 .on_click({
2977 let context = context.clone();
2978 let error = error.clone();
2979 move |_, cx| {
2980 context.update(cx, |_, cx| {
2981 cx.emit(ContextEvent::ShowAssistError(
2982 error.clone(),
2983 ));
2984 });
2985 }
2986 })
2987 .into_any_element(),
2988 ),
2989 MessageStatus::Canceled => Some(
2990 ButtonLike::new("canceled")
2991 .child(Icon::new(IconName::XCircle).color(Color::Disabled))
2992 .child(
2993 Label::new("Canceled")
2994 .size(LabelSize::Small)
2995 .color(Color::Disabled),
2996 )
2997 .tooltip(move |cx| {
2998 Tooltip::with_meta(
2999 "Canceled",
3000 None,
3001 "Interaction with the assistant was canceled",
3002 cx,
3003 )
3004 })
3005 .into_any_element(),
3006 ),
3007 _ => None,
3008 })
3009 .into_any_element()
3010 }
3011 })
3012 };
3013 let create_block_properties = |message: &Message| BlockProperties {
3014 position: buffer
3015 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
3016 .unwrap(),
3017 height: 2,
3018 style: BlockStyle::Sticky,
3019 disposition: BlockDisposition::Above,
3020 priority: usize::MAX,
3021 render: render_block(MessageMetadata::from(message)),
3022 };
3023 let mut new_blocks = vec![];
3024 let mut block_index_to_message = vec![];
3025 for message in self.context.read(cx).messages(cx) {
3026 if let Some(_) = blocks_to_remove.remove(&message.id) {
3027 // This is an old message that we might modify.
3028 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
3029 debug_assert!(
3030 false,
3031 "old_blocks should contain a message_id we've just removed."
3032 );
3033 continue;
3034 };
3035 // Should we modify it?
3036 let message_meta = MessageMetadata::from(&message);
3037 if meta != &message_meta {
3038 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
3039 *meta = message_meta;
3040 }
3041 } else {
3042 // This is a new message.
3043 new_blocks.push(create_block_properties(&message));
3044 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
3045 }
3046 }
3047 editor.replace_blocks(blocks_to_replace, None, cx);
3048 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
3049
3050 let ids = editor.insert_blocks(new_blocks, None, cx);
3051 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
3052 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
3053 ));
3054 self.blocks = old_blocks;
3055 });
3056 }
3057
3058 fn insert_selection(
3059 workspace: &mut Workspace,
3060 _: &InsertIntoEditor,
3061 cx: &mut ViewContext<Workspace>,
3062 ) {
3063 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
3064 return;
3065 };
3066 let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
3067 return;
3068 };
3069 let Some(active_editor_view) = workspace
3070 .active_item(cx)
3071 .and_then(|item| item.act_as::<Editor>(cx))
3072 else {
3073 return;
3074 };
3075
3076 let context_editor = context_editor_view.read(cx).editor.read(cx);
3077 let anchor = context_editor.selections.newest_anchor();
3078 let text = context_editor
3079 .buffer()
3080 .read(cx)
3081 .read(cx)
3082 .text_for_range(anchor.range())
3083 .collect::<String>();
3084
3085 // If nothing is selected, don't delete the current selection; instead, be a no-op.
3086 if !text.is_empty() {
3087 active_editor_view.update(cx, |editor, cx| {
3088 editor.insert(&text, cx);
3089 editor.focus(cx);
3090 })
3091 }
3092 }
3093
3094 fn insert_dragged_files(
3095 workspace: &mut Workspace,
3096 action: &InsertDraggedFiles,
3097 cx: &mut ViewContext<Workspace>,
3098 ) {
3099 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
3100 return;
3101 };
3102 let Some(context_editor_view) = panel.read(cx).active_context_editor(cx) else {
3103 return;
3104 };
3105
3106 let project = workspace.project().clone();
3107
3108 let paths = match action {
3109 InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
3110 InsertDraggedFiles::ExternalFiles(paths) => {
3111 let tasks = paths
3112 .clone()
3113 .into_iter()
3114 .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
3115 .collect::<Vec<_>>();
3116
3117 cx.spawn(move |_, cx| async move {
3118 let mut paths = vec![];
3119 let mut worktrees = vec![];
3120
3121 let opened_paths = futures::future::join_all(tasks).await;
3122 for (worktree, project_path) in opened_paths.into_iter().flatten() {
3123 let Ok(worktree_root_name) =
3124 worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
3125 else {
3126 continue;
3127 };
3128
3129 let mut full_path = PathBuf::from(worktree_root_name.clone());
3130 full_path.push(&project_path.path);
3131 paths.push(full_path);
3132 worktrees.push(worktree);
3133 }
3134
3135 (paths, worktrees)
3136 })
3137 }
3138 };
3139
3140 cx.spawn(|_, mut cx| async move {
3141 let (paths, dragged_file_worktrees) = paths.await;
3142 let cmd_name = file_command::FileSlashCommand.name();
3143
3144 context_editor_view
3145 .update(&mut cx, |context_editor, cx| {
3146 let file_argument = paths
3147 .into_iter()
3148 .map(|path| path.to_string_lossy().to_string())
3149 .collect::<Vec<_>>()
3150 .join(" ");
3151
3152 context_editor.editor.update(cx, |editor, cx| {
3153 editor.insert("\n", cx);
3154 editor.insert(&format!("/{} {}", cmd_name, file_argument), cx);
3155 });
3156
3157 context_editor.confirm_command(&ConfirmCommand, cx);
3158
3159 context_editor
3160 .dragged_file_worktrees
3161 .extend(dragged_file_worktrees);
3162 })
3163 .log_err();
3164 })
3165 .detach();
3166 }
3167
3168 fn quote_selection(
3169 workspace: &mut Workspace,
3170 _: &QuoteSelection,
3171 cx: &mut ViewContext<Workspace>,
3172 ) {
3173 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
3174 return;
3175 };
3176 let Some(editor) = workspace
3177 .active_item(cx)
3178 .and_then(|item| item.act_as::<Editor>(cx))
3179 else {
3180 return;
3181 };
3182
3183 let selection = editor.update(cx, |editor, cx| editor.selections.newest_adjusted(cx));
3184 let editor = editor.read(cx);
3185 let buffer = editor.buffer().read(cx).snapshot(cx);
3186 let range = editor::ToOffset::to_offset(&selection.start, &buffer)
3187 ..editor::ToOffset::to_offset(&selection.end, &buffer);
3188 let selected_text = buffer.text_for_range(range.clone()).collect::<String>();
3189 if selected_text.is_empty() {
3190 return;
3191 }
3192
3193 let start_language = buffer.language_at(range.start);
3194 let end_language = buffer.language_at(range.end);
3195 let language_name = if start_language == end_language {
3196 start_language.map(|language| language.code_fence_block_name())
3197 } else {
3198 None
3199 };
3200 let language_name = language_name.as_deref().unwrap_or("");
3201
3202 let filename = buffer
3203 .file_at(selection.start)
3204 .map(|file| file.full_path(cx));
3205
3206 let text = if language_name == "markdown" {
3207 selected_text
3208 .lines()
3209 .map(|line| format!("> {}", line))
3210 .collect::<Vec<_>>()
3211 .join("\n")
3212 } else {
3213 let start_symbols = buffer
3214 .symbols_containing(selection.start, None)
3215 .map(|(_, symbols)| symbols);
3216 let end_symbols = buffer
3217 .symbols_containing(selection.end, None)
3218 .map(|(_, symbols)| symbols);
3219
3220 let outline_text =
3221 if let Some((start_symbols, end_symbols)) = start_symbols.zip(end_symbols) {
3222 Some(
3223 start_symbols
3224 .into_iter()
3225 .zip(end_symbols)
3226 .take_while(|(a, b)| a == b)
3227 .map(|(a, _)| a.text)
3228 .collect::<Vec<_>>()
3229 .join(" > "),
3230 )
3231 } else {
3232 None
3233 };
3234
3235 let line_comment_prefix = start_language
3236 .and_then(|l| l.default_scope().line_comment_prefixes().first().cloned());
3237
3238 let fence = codeblock_fence_for_path(
3239 filename.as_deref(),
3240 Some(selection.start.row..selection.end.row),
3241 );
3242
3243 if let Some((line_comment_prefix, outline_text)) = line_comment_prefix.zip(outline_text)
3244 {
3245 let breadcrumb = format!("{line_comment_prefix}Excerpt from: {outline_text}\n");
3246 format!("{fence}{breadcrumb}{selected_text}\n```")
3247 } else {
3248 format!("{fence}{selected_text}\n```")
3249 }
3250 };
3251
3252 let crease_title = if let Some(path) = filename {
3253 let start_line = selection.start.row + 1;
3254 let end_line = selection.end.row + 1;
3255 if start_line == end_line {
3256 format!("{}, Line {}", path.display(), start_line)
3257 } else {
3258 format!("{}, Lines {} to {}", path.display(), start_line, end_line)
3259 }
3260 } else {
3261 "Quoted selection".to_string()
3262 };
3263
3264 // Activate the panel
3265 if !panel.focus_handle(cx).contains_focused(cx) {
3266 workspace.toggle_panel_focus::<AssistantPanel>(cx);
3267 }
3268
3269 panel.update(cx, |_, cx| {
3270 // Wait to create a new context until the workspace is no longer
3271 // being updated.
3272 cx.defer(move |panel, cx| {
3273 if let Some(context) = panel
3274 .active_context_editor(cx)
3275 .or_else(|| panel.new_context(cx))
3276 {
3277 context.update(cx, |context, cx| {
3278 context.editor.update(cx, |editor, cx| {
3279 editor.insert("\n", cx);
3280
3281 let point = editor.selections.newest::<Point>(cx).head();
3282 let start_row = MultiBufferRow(point.row);
3283
3284 editor.insert(&text, cx);
3285
3286 let snapshot = editor.buffer().read(cx).snapshot(cx);
3287 let anchor_before = snapshot.anchor_after(point);
3288 let anchor_after = editor
3289 .selections
3290 .newest_anchor()
3291 .head()
3292 .bias_left(&snapshot);
3293
3294 editor.insert("\n", cx);
3295
3296 let fold_placeholder = quote_selection_fold_placeholder(
3297 crease_title,
3298 cx.view().downgrade(),
3299 );
3300 let crease = Crease::new(
3301 anchor_before..anchor_after,
3302 fold_placeholder,
3303 render_quote_selection_output_toggle,
3304 |_, _, _| Empty.into_any(),
3305 );
3306 editor.insert_creases(vec![crease], cx);
3307 editor.fold_at(
3308 &FoldAt {
3309 buffer_row: start_row,
3310 },
3311 cx,
3312 );
3313 })
3314 });
3315 };
3316 });
3317 });
3318 }
3319
3320 fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
3321 let editor = self.editor.read(cx);
3322 let context = self.context.read(cx);
3323 if editor.selections.count() == 1 {
3324 let selection = editor.selections.newest::<usize>(cx);
3325 let mut copied_text = String::new();
3326 let mut spanned_messages = 0;
3327 for message in context.messages(cx) {
3328 if message.offset_range.start >= selection.range().end {
3329 break;
3330 } else if message.offset_range.end >= selection.range().start {
3331 let range = cmp::max(message.offset_range.start, selection.range().start)
3332 ..cmp::min(message.offset_range.end, selection.range().end);
3333 if !range.is_empty() {
3334 spanned_messages += 1;
3335 write!(&mut copied_text, "## {}\n\n", message.role).unwrap();
3336 for chunk in context.buffer().read(cx).text_for_range(range) {
3337 copied_text.push_str(chunk);
3338 }
3339 copied_text.push('\n');
3340 }
3341 }
3342 }
3343
3344 if spanned_messages > 1 {
3345 cx.write_to_clipboard(ClipboardItem::new_string(copied_text));
3346 return;
3347 }
3348 }
3349
3350 cx.propagate();
3351 }
3352
3353 fn paste(&mut self, _: &editor::actions::Paste, cx: &mut ViewContext<Self>) {
3354 let images = if let Some(item) = cx.read_from_clipboard() {
3355 item.into_entries()
3356 .filter_map(|entry| {
3357 if let ClipboardEntry::Image(image) = entry {
3358 Some(image)
3359 } else {
3360 None
3361 }
3362 })
3363 .collect()
3364 } else {
3365 Vec::new()
3366 };
3367
3368 if images.is_empty() {
3369 // If we didn't find any valid image data to paste, propagate to let normal pasting happen.
3370 cx.propagate();
3371 } else {
3372 let mut image_positions = Vec::new();
3373 self.editor.update(cx, |editor, cx| {
3374 editor.transact(cx, |editor, cx| {
3375 let edits = editor
3376 .selections
3377 .all::<usize>(cx)
3378 .into_iter()
3379 .map(|selection| (selection.start..selection.end, "\n"));
3380 editor.edit(edits, cx);
3381
3382 let snapshot = editor.buffer().read(cx).snapshot(cx);
3383 for selection in editor.selections.all::<usize>(cx) {
3384 image_positions.push(snapshot.anchor_before(selection.end));
3385 }
3386 });
3387 });
3388
3389 self.context.update(cx, |context, cx| {
3390 for image in images {
3391 let image_id = image.id();
3392 context.insert_image(image, cx);
3393 for image_position in image_positions.iter() {
3394 context.insert_image_anchor(image_id, image_position.text_anchor, cx);
3395 }
3396 }
3397 });
3398 }
3399 }
3400
3401 fn update_image_blocks(&mut self, cx: &mut ViewContext<Self>) {
3402 self.editor.update(cx, |editor, cx| {
3403 let buffer = editor.buffer().read(cx).snapshot(cx);
3404 let excerpt_id = *buffer.as_singleton().unwrap().0;
3405 let old_blocks = std::mem::take(&mut self.image_blocks);
3406 let new_blocks = self
3407 .context
3408 .read(cx)
3409 .images(cx)
3410 .filter_map(|image| {
3411 const MAX_HEIGHT_IN_LINES: u32 = 8;
3412 let anchor = buffer.anchor_in_excerpt(excerpt_id, image.anchor).unwrap();
3413 let image = image.render_image.clone();
3414 anchor.is_valid(&buffer).then(|| BlockProperties {
3415 position: anchor,
3416 height: MAX_HEIGHT_IN_LINES,
3417 style: BlockStyle::Sticky,
3418 render: Box::new(move |cx| {
3419 let image_size = size_for_image(
3420 &image,
3421 size(
3422 cx.max_width - cx.gutter_dimensions.full_width(),
3423 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
3424 ),
3425 );
3426 h_flex()
3427 .pl(cx.gutter_dimensions.full_width())
3428 .child(
3429 img(image.clone())
3430 .object_fit(gpui::ObjectFit::ScaleDown)
3431 .w(image_size.width)
3432 .h(image_size.height),
3433 )
3434 .into_any_element()
3435 }),
3436
3437 disposition: BlockDisposition::Above,
3438 priority: 0,
3439 })
3440 })
3441 .collect::<Vec<_>>();
3442
3443 editor.remove_blocks(old_blocks, None, cx);
3444 let ids = editor.insert_blocks(new_blocks, None, cx);
3445 self.image_blocks = HashSet::from_iter(ids);
3446 });
3447 }
3448
3449 fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
3450 self.context.update(cx, |context, cx| {
3451 let selections = self.editor.read(cx).selections.disjoint_anchors();
3452 for selection in selections.as_ref() {
3453 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
3454 let range = selection
3455 .map(|endpoint| endpoint.to_offset(&buffer))
3456 .range();
3457 context.split_message(range, cx);
3458 }
3459 });
3460 }
3461
3462 fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
3463 self.context.update(cx, |context, cx| {
3464 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
3465 });
3466 }
3467
3468 fn title(&self, cx: &AppContext) -> Cow<str> {
3469 self.context
3470 .read(cx)
3471 .summary()
3472 .map(|summary| summary.text.clone())
3473 .map(Cow::Owned)
3474 .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
3475 }
3476
3477 fn render_workflow_step_header(
3478 &self,
3479 range: Range<text::Anchor>,
3480 max_width: Pixels,
3481 gutter_width: Pixels,
3482 id: BlockId,
3483 cx: &mut ViewContext<Self>,
3484 ) -> Option<AnyElement> {
3485 let step_state = self.workflow_steps.get(&range)?;
3486 let status = step_state.status(cx);
3487 let this = cx.view().downgrade();
3488
3489 let theme = cx.theme().status();
3490 let is_confirmed = status.is_confirmed();
3491 let border_color = if is_confirmed {
3492 theme.ignored_border
3493 } else {
3494 theme.info_border
3495 };
3496
3497 let editor = self.editor.read(cx);
3498 let focus_handle = editor.focus_handle(cx);
3499 let snapshot = editor
3500 .buffer()
3501 .read(cx)
3502 .as_singleton()?
3503 .read(cx)
3504 .text_snapshot();
3505 let start_offset = range.start.to_offset(&snapshot);
3506 let parent_message = self
3507 .context
3508 .read(cx)
3509 .messages_for_offsets([start_offset], cx);
3510 debug_assert_eq!(parent_message.len(), 1);
3511 let parent_message = parent_message.first()?;
3512
3513 let step_index = self
3514 .workflow_steps
3515 .keys()
3516 .filter(|workflow_step_range| {
3517 workflow_step_range
3518 .start
3519 .cmp(&parent_message.anchor_range.start, &snapshot)
3520 .is_ge()
3521 && workflow_step_range.end.cmp(&range.end, &snapshot).is_le()
3522 })
3523 .count();
3524
3525 let step_label = Label::new(format!("Step {step_index}")).size(LabelSize::Small);
3526
3527 let step_label = if is_confirmed {
3528 h_flex()
3529 .items_center()
3530 .gap_2()
3531 .child(step_label.strikethrough(true).color(Color::Muted))
3532 .child(
3533 Icon::new(IconName::Check)
3534 .size(IconSize::Small)
3535 .color(Color::Created),
3536 )
3537 } else {
3538 div().child(step_label)
3539 };
3540
3541 Some(
3542 v_flex()
3543 .w(max_width)
3544 .pl(gutter_width)
3545 .child(
3546 h_flex()
3547 .w_full()
3548 .h_8()
3549 .border_b_1()
3550 .border_color(border_color)
3551 .items_center()
3552 .justify_between()
3553 .gap_2()
3554 .child(h_flex().justify_start().gap_2().child(step_label))
3555 .child(h_flex().w_full().justify_end().child(
3556 Self::render_workflow_step_status(
3557 status,
3558 range.clone(),
3559 focus_handle.clone(),
3560 this.clone(),
3561 id,
3562 ),
3563 )),
3564 )
3565 // todo!("do we wanna keep this?")
3566 // .children(edit_paths.iter().map(|path| {
3567 // h_flex()
3568 // .gap_1()
3569 // .child(Icon::new(IconName::File))
3570 // .child(Label::new(path.clone()))
3571 // }))
3572 .into_any(),
3573 )
3574 }
3575
3576 fn render_workflow_step_footer(
3577 &self,
3578 step_range: Range<text::Anchor>,
3579 max_width: Pixels,
3580 gutter_width: Pixels,
3581 cx: &mut ViewContext<Self>,
3582 ) -> Option<AnyElement> {
3583 let step = self.workflow_steps.get(&step_range)?;
3584 let current_status = step.status(cx);
3585 let theme = cx.theme().status();
3586 let border_color = if current_status.is_confirmed() {
3587 theme.ignored_border
3588 } else {
3589 theme.info_border
3590 };
3591 Some(
3592 v_flex()
3593 .w(max_width)
3594 .pt_1()
3595 .pl(gutter_width)
3596 .child(h_flex().h(px(1.)).bg(border_color))
3597 .into_any(),
3598 )
3599 }
3600
3601 fn render_workflow_step_status(
3602 status: WorkflowStepStatus,
3603 step_range: Range<language::Anchor>,
3604 focus_handle: FocusHandle,
3605 editor: WeakView<ContextEditor>,
3606 id: BlockId,
3607 ) -> AnyElement {
3608 let id = EntityId::from(id).as_u64();
3609 fn display_keybind_in_tooltip(
3610 step_range: &Range<language::Anchor>,
3611 editor: &WeakView<ContextEditor>,
3612 cx: &mut WindowContext<'_>,
3613 ) -> bool {
3614 editor
3615 .update(cx, |this, _| {
3616 this.active_workflow_step
3617 .as_ref()
3618 .map(|step| &step.range == step_range)
3619 })
3620 .ok()
3621 .flatten()
3622 .unwrap_or_default()
3623 }
3624
3625 match status {
3626 WorkflowStepStatus::Error(error) => {
3627 let error = error.to_string();
3628 h_flex()
3629 .gap_2()
3630 .child(
3631 div()
3632 .id("step-resolution-failure")
3633 .child(
3634 Label::new("Step Resolution Failed")
3635 .size(LabelSize::Small)
3636 .color(Color::Error),
3637 )
3638 .tooltip(move |cx| Tooltip::text(error.clone(), cx)),
3639 )
3640 .child(
3641 Button::new(("transform", id), "Retry")
3642 .icon(IconName::Update)
3643 .icon_position(IconPosition::Start)
3644 .icon_size(IconSize::Small)
3645 .label_size(LabelSize::Small)
3646 .on_click({
3647 let editor = editor.clone();
3648 let step_range = step_range.clone();
3649 move |_, cx| {
3650 editor
3651 .update(cx, |this, cx| {
3652 this.resolve_workflow_step(step_range.clone(), cx)
3653 })
3654 .ok();
3655 }
3656 }),
3657 )
3658 .into_any()
3659 }
3660 WorkflowStepStatus::Idle | WorkflowStepStatus::Resolving { .. } => {
3661 Button::new(("transform", id), "Transform")
3662 .icon(IconName::SparkleAlt)
3663 .icon_position(IconPosition::Start)
3664 .icon_size(IconSize::Small)
3665 .label_size(LabelSize::Small)
3666 .style(ButtonStyle::Tinted(TintColor::Accent))
3667 .tooltip({
3668 let step_range = step_range.clone();
3669 let editor = editor.clone();
3670 move |cx| {
3671 cx.new_view(|cx| {
3672 let tooltip = Tooltip::new("Transform");
3673 if display_keybind_in_tooltip(&step_range, &editor, cx) {
3674 tooltip.key_binding(KeyBinding::for_action_in(
3675 &Assist,
3676 &focus_handle,
3677 cx,
3678 ))
3679 } else {
3680 tooltip
3681 }
3682 })
3683 .into()
3684 }
3685 })
3686 .on_click({
3687 let editor = editor.clone();
3688 let step_range = step_range.clone();
3689 let is_idle = matches!(status, WorkflowStepStatus::Idle);
3690 move |_, cx| {
3691 if is_idle {
3692 editor
3693 .update(cx, |this, cx| {
3694 this.apply_workflow_step(step_range.clone(), cx)
3695 })
3696 .ok();
3697 }
3698 }
3699 })
3700 .map(|this| {
3701 if let WorkflowStepStatus::Resolving = &status {
3702 this.with_animation(
3703 ("resolving-suggestion-animation", id),
3704 Animation::new(Duration::from_secs(2))
3705 .repeat()
3706 .with_easing(pulsating_between(0.4, 0.8)),
3707 |label, delta| label.alpha(delta),
3708 )
3709 .into_any_element()
3710 } else {
3711 this.into_any_element()
3712 }
3713 })
3714 }
3715 WorkflowStepStatus::Pending => h_flex()
3716 .items_center()
3717 .gap_2()
3718 .child(
3719 Label::new("Applying...")
3720 .size(LabelSize::Small)
3721 .with_animation(
3722 ("applying-step-transformation-label", id),
3723 Animation::new(Duration::from_secs(2))
3724 .repeat()
3725 .with_easing(pulsating_between(0.4, 0.8)),
3726 |label, delta| label.alpha(delta),
3727 ),
3728 )
3729 .child(
3730 IconButton::new(("stop-transformation", id), IconName::Stop)
3731 .icon_size(IconSize::Small)
3732 .icon_color(Color::Error)
3733 .style(ButtonStyle::Subtle)
3734 .tooltip({
3735 let step_range = step_range.clone();
3736 let editor = editor.clone();
3737 move |cx| {
3738 cx.new_view(|cx| {
3739 let tooltip = Tooltip::new("Stop Transformation");
3740 if display_keybind_in_tooltip(&step_range, &editor, cx) {
3741 tooltip.key_binding(KeyBinding::for_action_in(
3742 &editor::actions::Cancel,
3743 &focus_handle,
3744 cx,
3745 ))
3746 } else {
3747 tooltip
3748 }
3749 })
3750 .into()
3751 }
3752 })
3753 .on_click({
3754 let editor = editor.clone();
3755 let step_range = step_range.clone();
3756 move |_, cx| {
3757 editor
3758 .update(cx, |this, cx| {
3759 this.stop_workflow_step(step_range.clone(), cx)
3760 })
3761 .ok();
3762 }
3763 }),
3764 )
3765 .into_any_element(),
3766 WorkflowStepStatus::Done => h_flex()
3767 .gap_1()
3768 .child(
3769 IconButton::new(("stop-transformation", id), IconName::Close)
3770 .icon_size(IconSize::Small)
3771 .style(ButtonStyle::Tinted(TintColor::Negative))
3772 .tooltip({
3773 let focus_handle = focus_handle.clone();
3774 let editor = editor.clone();
3775 let step_range = step_range.clone();
3776 move |cx| {
3777 cx.new_view(|cx| {
3778 let tooltip = Tooltip::new("Reject Transformation");
3779 if display_keybind_in_tooltip(&step_range, &editor, cx) {
3780 tooltip.key_binding(KeyBinding::for_action_in(
3781 &editor::actions::Cancel,
3782 &focus_handle,
3783 cx,
3784 ))
3785 } else {
3786 tooltip
3787 }
3788 })
3789 .into()
3790 }
3791 })
3792 .on_click({
3793 let editor = editor.clone();
3794 let step_range = step_range.clone();
3795 move |_, cx| {
3796 editor
3797 .update(cx, |this, cx| {
3798 this.reject_workflow_step(step_range.clone(), cx);
3799 })
3800 .ok();
3801 }
3802 }),
3803 )
3804 .child(
3805 Button::new(("confirm-workflow-step", id), "Accept")
3806 .icon(IconName::Check)
3807 .icon_position(IconPosition::Start)
3808 .icon_size(IconSize::Small)
3809 .label_size(LabelSize::Small)
3810 .style(ButtonStyle::Tinted(TintColor::Positive))
3811 .tooltip({
3812 let editor = editor.clone();
3813 let step_range = step_range.clone();
3814 move |cx| {
3815 cx.new_view(|cx| {
3816 let tooltip = Tooltip::new("Accept Transformation");
3817 if display_keybind_in_tooltip(&step_range, &editor, cx) {
3818 tooltip.key_binding(KeyBinding::for_action_in(
3819 &Assist,
3820 &focus_handle,
3821 cx,
3822 ))
3823 } else {
3824 tooltip
3825 }
3826 })
3827 .into()
3828 }
3829 })
3830 .on_click({
3831 let editor = editor.clone();
3832 let step_range = step_range.clone();
3833 move |_, cx| {
3834 editor
3835 .update(cx, |this, cx| {
3836 this.confirm_workflow_step(step_range.clone(), cx);
3837 })
3838 .ok();
3839 }
3840 }),
3841 )
3842 .into_any_element(),
3843 WorkflowStepStatus::Confirmed => h_flex()
3844 .child(
3845 Button::new(("revert-workflow-step", id), "Undo")
3846 .style(ButtonStyle::Filled)
3847 .icon(Some(IconName::Undo))
3848 .icon_position(IconPosition::Start)
3849 .icon_size(IconSize::Small)
3850 .label_size(LabelSize::Small)
3851 .on_click({
3852 let editor = editor.clone();
3853 let step_range = step_range.clone();
3854 move |_, cx| {
3855 editor
3856 .update(cx, |this, cx| {
3857 this.undo_workflow_step(step_range.clone(), cx);
3858 })
3859 .ok();
3860 }
3861 }),
3862 )
3863 .into_any_element(),
3864 }
3865 }
3866
3867 fn render_notice(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
3868 use feature_flags::FeatureFlagAppExt;
3869 let nudge = self.assistant_panel.upgrade().map(|assistant_panel| {
3870 assistant_panel.read(cx).show_zed_ai_notice && cx.has_flag::<feature_flags::ZedPro>()
3871 });
3872
3873 if nudge.map_or(false, |value| value) {
3874 Some(
3875 h_flex()
3876 .p_3()
3877 .border_b_1()
3878 .border_color(cx.theme().colors().border_variant)
3879 .bg(cx.theme().colors().editor_background)
3880 .justify_between()
3881 .child(
3882 h_flex()
3883 .gap_3()
3884 .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
3885 .child(Label::new("Zed AI is here! Get started by signing in →")),
3886 )
3887 .child(
3888 Button::new("sign-in", "Sign in")
3889 .size(ButtonSize::Compact)
3890 .style(ButtonStyle::Filled)
3891 .on_click(cx.listener(|this, _event, cx| {
3892 let client = this
3893 .workspace
3894 .update(cx, |workspace, _| workspace.client().clone())
3895 .log_err();
3896
3897 if let Some(client) = client {
3898 cx.spawn(|this, mut cx| async move {
3899 client.authenticate_and_connect(true, &mut cx).await?;
3900 this.update(&mut cx, |_, cx| cx.notify())
3901 })
3902 .detach_and_log_err(cx)
3903 }
3904 })),
3905 )
3906 .into_any_element(),
3907 )
3908 } else if let Some(configuration_error) = configuration_error(cx) {
3909 let label = match configuration_error {
3910 ConfigurationError::NoProvider => "No LLM provider selected.",
3911 ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
3912 };
3913 Some(
3914 h_flex()
3915 .px_3()
3916 .py_2()
3917 .border_b_1()
3918 .border_color(cx.theme().colors().border_variant)
3919 .bg(cx.theme().colors().editor_background)
3920 .justify_between()
3921 .child(
3922 h_flex()
3923 .gap_3()
3924 .child(
3925 Icon::new(IconName::ExclamationTriangle)
3926 .size(IconSize::Small)
3927 .color(Color::Warning),
3928 )
3929 .child(Label::new(label)),
3930 )
3931 .child(
3932 Button::new("open-configuration", "Open configuration")
3933 .size(ButtonSize::Compact)
3934 .icon_size(IconSize::Small)
3935 .style(ButtonStyle::Filled)
3936 .on_click({
3937 let focus_handle = self.focus_handle(cx).clone();
3938 move |_event, cx| {
3939 focus_handle.dispatch_action(&ShowConfiguration, cx);
3940 }
3941 }),
3942 )
3943 .into_any_element(),
3944 )
3945 } else {
3946 None
3947 }
3948 }
3949
3950 fn render_send_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3951 let focus_handle = self.focus_handle(cx).clone();
3952 let button_text = match self.active_workflow_step() {
3953 Some((_, step)) => match step.status(cx) {
3954 WorkflowStepStatus::Error(_) => "Retry Step Resolution",
3955 WorkflowStepStatus::Resolving => "Transform",
3956 WorkflowStepStatus::Idle => "Transform",
3957 WorkflowStepStatus::Pending => "Applying...",
3958 WorkflowStepStatus::Done => "Accept",
3959 WorkflowStepStatus::Confirmed => "Send",
3960 },
3961 None => "Send",
3962 };
3963
3964 let (style, tooltip) = match token_state(&self.context, cx) {
3965 Some(TokenState::NoTokensLeft { .. }) => (
3966 ButtonStyle::Tinted(TintColor::Negative),
3967 Some(Tooltip::text("Token limit reached", cx)),
3968 ),
3969 Some(TokenState::HasMoreTokens {
3970 over_warn_threshold,
3971 ..
3972 }) => {
3973 let (style, tooltip) = if over_warn_threshold {
3974 (
3975 ButtonStyle::Tinted(TintColor::Warning),
3976 Some(Tooltip::text("Token limit is close to exhaustion", cx)),
3977 )
3978 } else {
3979 (ButtonStyle::Filled, None)
3980 };
3981 (style, tooltip)
3982 }
3983 None => (ButtonStyle::Filled, None),
3984 };
3985
3986 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3987
3988 let has_configuration_error = configuration_error(cx).is_some();
3989 let needs_to_accept_terms = self.show_accept_terms
3990 && provider
3991 .as_ref()
3992 .map_or(false, |provider| provider.must_accept_terms(cx));
3993 let disabled = has_configuration_error || needs_to_accept_terms;
3994
3995 ButtonLike::new("send_button")
3996 .disabled(disabled)
3997 .style(style)
3998 .when_some(tooltip, |button, tooltip| {
3999 button.tooltip(move |_| tooltip.clone())
4000 })
4001 .layer(ElevationIndex::ModalSurface)
4002 .child(Label::new(button_text))
4003 .children(
4004 KeyBinding::for_action_in(&Assist, &focus_handle, cx)
4005 .map(|binding| binding.into_any_element()),
4006 )
4007 .on_click(move |_event, cx| {
4008 focus_handle.dispatch_action(&Assist, cx);
4009 })
4010 }
4011}
4012
4013fn render_fold_icon_button(
4014 editor: WeakView<Editor>,
4015 icon: IconName,
4016 label: SharedString,
4017) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut WindowContext) -> AnyElement> {
4018 Arc::new(move |fold_id, fold_range, _cx| {
4019 let editor = editor.clone();
4020 ButtonLike::new(fold_id)
4021 .style(ButtonStyle::Filled)
4022 .layer(ElevationIndex::ElevatedSurface)
4023 .child(Icon::new(icon))
4024 .child(Label::new(label.clone()).single_line())
4025 .on_click(move |_, cx| {
4026 editor
4027 .update(cx, |editor, cx| {
4028 let buffer_start = fold_range
4029 .start
4030 .to_point(&editor.buffer().read(cx).read(cx));
4031 let buffer_row = MultiBufferRow(buffer_start.row);
4032 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4033 })
4034 .ok();
4035 })
4036 .into_any_element()
4037 })
4038}
4039
4040impl EventEmitter<EditorEvent> for ContextEditor {}
4041impl EventEmitter<SearchEvent> for ContextEditor {}
4042
4043impl Render for ContextEditor {
4044 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4045 let provider = LanguageModelRegistry::read_global(cx).active_provider();
4046 let accept_terms = if self.show_accept_terms {
4047 provider
4048 .as_ref()
4049 .and_then(|provider| provider.render_accept_terms(cx))
4050 } else {
4051 None
4052 };
4053 let focus_handle = self
4054 .workspace
4055 .update(cx, |workspace, cx| {
4056 Some(workspace.active_item_as::<Editor>(cx)?.focus_handle(cx))
4057 })
4058 .ok()
4059 .flatten();
4060 v_flex()
4061 .key_context("ContextEditor")
4062 .capture_action(cx.listener(ContextEditor::cancel))
4063 .capture_action(cx.listener(ContextEditor::save))
4064 .capture_action(cx.listener(ContextEditor::copy))
4065 .capture_action(cx.listener(ContextEditor::paste))
4066 .capture_action(cx.listener(ContextEditor::cycle_message_role))
4067 .capture_action(cx.listener(ContextEditor::confirm_command))
4068 .on_action(cx.listener(ContextEditor::assist))
4069 .on_action(cx.listener(ContextEditor::split))
4070 .size_full()
4071 .children(self.render_notice(cx))
4072 .child(
4073 div()
4074 .flex_grow()
4075 .bg(cx.theme().colors().editor_background)
4076 .child(self.editor.clone()),
4077 )
4078 .when_some(accept_terms, |this, element| {
4079 this.child(
4080 div()
4081 .absolute()
4082 .right_3()
4083 .bottom_12()
4084 .max_w_96()
4085 .py_2()
4086 .px_3()
4087 .elevation_2(cx)
4088 .bg(cx.theme().colors().surface_background)
4089 .occlude()
4090 .child(element),
4091 )
4092 })
4093 .when_some(self.error_message.clone(), |this, error_message| {
4094 this.child(
4095 div()
4096 .absolute()
4097 .right_3()
4098 .bottom_12()
4099 .max_w_96()
4100 .py_2()
4101 .px_3()
4102 .elevation_2(cx)
4103 .occlude()
4104 .child(
4105 v_flex()
4106 .gap_0p5()
4107 .child(
4108 h_flex()
4109 .gap_1p5()
4110 .items_center()
4111 .child(Icon::new(IconName::XCircle).color(Color::Error))
4112 .child(
4113 Label::new("Error interacting with language model")
4114 .weight(FontWeight::MEDIUM),
4115 ),
4116 )
4117 .child(
4118 div()
4119 .id("error-message")
4120 .max_h_24()
4121 .overflow_y_scroll()
4122 .child(Label::new(error_message)),
4123 )
4124 .child(h_flex().justify_end().mt_1().child(
4125 Button::new("dismiss", "Dismiss").on_click(cx.listener(
4126 |this, _, cx| {
4127 this.error_message = None;
4128 cx.notify();
4129 },
4130 )),
4131 )),
4132 ),
4133 )
4134 })
4135 .child(
4136 h_flex().w_full().relative().child(
4137 h_flex()
4138 .p_2()
4139 .w_full()
4140 .border_t_1()
4141 .border_color(cx.theme().colors().border_variant)
4142 .bg(cx.theme().colors().editor_background)
4143 .child(
4144 h_flex()
4145 .gap_2()
4146 .child(render_inject_context_menu(cx.view().downgrade(), cx))
4147 .child(
4148 IconButton::new("quote-button", IconName::Quote)
4149 .icon_size(IconSize::Small)
4150 .on_click(|_, cx| {
4151 cx.dispatch_action(QuoteSelection.boxed_clone());
4152 })
4153 .tooltip(move |cx| {
4154 cx.new_view(|cx| {
4155 Tooltip::new("Insert Selection").key_binding(
4156 focus_handle.as_ref().and_then(|handle| {
4157 KeyBinding::for_action_in(
4158 &QuoteSelection,
4159 &handle,
4160 cx,
4161 )
4162 }),
4163 )
4164 })
4165 .into()
4166 }),
4167 ),
4168 )
4169 .child(
4170 h_flex()
4171 .w_full()
4172 .justify_end()
4173 .child(div().child(self.render_send_button(cx))),
4174 ),
4175 ),
4176 )
4177 }
4178}
4179
4180impl FocusableView for ContextEditor {
4181 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4182 self.editor.focus_handle(cx)
4183 }
4184}
4185
4186impl Item for ContextEditor {
4187 type Event = editor::EditorEvent;
4188
4189 fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
4190 Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
4191 }
4192
4193 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
4194 match event {
4195 EditorEvent::Edited { .. } => {
4196 f(item::ItemEvent::Edit);
4197 }
4198 EditorEvent::TitleChanged => {
4199 f(item::ItemEvent::UpdateTab);
4200 }
4201 _ => {}
4202 }
4203 }
4204
4205 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
4206 Some(self.title(cx).to_string().into())
4207 }
4208
4209 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
4210 Some(Box::new(handle.clone()))
4211 }
4212
4213 fn set_nav_history(&mut self, nav_history: pane::ItemNavHistory, cx: &mut ViewContext<Self>) {
4214 self.editor.update(cx, |editor, cx| {
4215 Item::set_nav_history(editor, nav_history, cx)
4216 })
4217 }
4218
4219 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
4220 self.editor
4221 .update(cx, |editor, cx| Item::navigate(editor, data, cx))
4222 }
4223
4224 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
4225 self.editor.update(cx, Item::deactivated)
4226 }
4227}
4228
4229impl SearchableItem for ContextEditor {
4230 type Match = <Editor as SearchableItem>::Match;
4231
4232 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
4233 self.editor.update(cx, |editor, cx| {
4234 editor.clear_matches(cx);
4235 });
4236 }
4237
4238 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4239 self.editor
4240 .update(cx, |editor, cx| editor.update_matches(matches, cx));
4241 }
4242
4243 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
4244 self.editor
4245 .update(cx, |editor, cx| editor.query_suggestion(cx))
4246 }
4247
4248 fn activate_match(
4249 &mut self,
4250 index: usize,
4251 matches: &[Self::Match],
4252 cx: &mut ViewContext<Self>,
4253 ) {
4254 self.editor.update(cx, |editor, cx| {
4255 editor.activate_match(index, matches, cx);
4256 });
4257 }
4258
4259 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
4260 self.editor
4261 .update(cx, |editor, cx| editor.select_matches(matches, cx));
4262 }
4263
4264 fn replace(
4265 &mut self,
4266 identifier: &Self::Match,
4267 query: &project::search::SearchQuery,
4268 cx: &mut ViewContext<Self>,
4269 ) {
4270 self.editor
4271 .update(cx, |editor, cx| editor.replace(identifier, query, cx));
4272 }
4273
4274 fn find_matches(
4275 &mut self,
4276 query: Arc<project::search::SearchQuery>,
4277 cx: &mut ViewContext<Self>,
4278 ) -> Task<Vec<Self::Match>> {
4279 self.editor
4280 .update(cx, |editor, cx| editor.find_matches(query, cx))
4281 }
4282
4283 fn active_match_index(
4284 &mut self,
4285 matches: &[Self::Match],
4286 cx: &mut ViewContext<Self>,
4287 ) -> Option<usize> {
4288 self.editor
4289 .update(cx, |editor, cx| editor.active_match_index(matches, cx))
4290 }
4291}
4292
4293impl FollowableItem for ContextEditor {
4294 fn remote_id(&self) -> Option<workspace::ViewId> {
4295 self.remote_id
4296 }
4297
4298 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
4299 let context = self.context.read(cx);
4300 Some(proto::view::Variant::ContextEditor(
4301 proto::view::ContextEditor {
4302 context_id: context.id().to_proto(),
4303 editor: if let Some(proto::view::Variant::Editor(proto)) =
4304 self.editor.read(cx).to_state_proto(cx)
4305 {
4306 Some(proto)
4307 } else {
4308 None
4309 },
4310 },
4311 ))
4312 }
4313
4314 fn from_state_proto(
4315 workspace: View<Workspace>,
4316 id: workspace::ViewId,
4317 state: &mut Option<proto::view::Variant>,
4318 cx: &mut WindowContext,
4319 ) -> Option<Task<Result<View<Self>>>> {
4320 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
4321 return None;
4322 };
4323 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
4324 unreachable!()
4325 };
4326
4327 let context_id = ContextId::from_proto(state.context_id);
4328 let editor_state = state.editor?;
4329
4330 let (project, panel) = workspace.update(cx, |workspace, cx| {
4331 Some((
4332 workspace.project().clone(),
4333 workspace.panel::<AssistantPanel>(cx)?,
4334 ))
4335 })?;
4336
4337 let context_editor =
4338 panel.update(cx, |panel, cx| panel.open_remote_context(context_id, cx));
4339
4340 Some(cx.spawn(|mut cx| async move {
4341 let context_editor = context_editor.await?;
4342 context_editor
4343 .update(&mut cx, |context_editor, cx| {
4344 context_editor.remote_id = Some(id);
4345 context_editor.editor.update(cx, |editor, cx| {
4346 editor.apply_update_proto(
4347 &project,
4348 proto::update_view::Variant::Editor(proto::update_view::Editor {
4349 selections: editor_state.selections,
4350 pending_selection: editor_state.pending_selection,
4351 scroll_top_anchor: editor_state.scroll_top_anchor,
4352 scroll_x: editor_state.scroll_y,
4353 scroll_y: editor_state.scroll_y,
4354 ..Default::default()
4355 }),
4356 cx,
4357 )
4358 })
4359 })?
4360 .await?;
4361 Ok(context_editor)
4362 }))
4363 }
4364
4365 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
4366 Editor::to_follow_event(event)
4367 }
4368
4369 fn add_event_to_update_proto(
4370 &self,
4371 event: &Self::Event,
4372 update: &mut Option<proto::update_view::Variant>,
4373 cx: &WindowContext,
4374 ) -> bool {
4375 self.editor
4376 .read(cx)
4377 .add_event_to_update_proto(event, update, cx)
4378 }
4379
4380 fn apply_update_proto(
4381 &mut self,
4382 project: &Model<Project>,
4383 message: proto::update_view::Variant,
4384 cx: &mut ViewContext<Self>,
4385 ) -> Task<Result<()>> {
4386 self.editor.update(cx, |editor, cx| {
4387 editor.apply_update_proto(project, message, cx)
4388 })
4389 }
4390
4391 fn is_project_item(&self, _cx: &WindowContext) -> bool {
4392 true
4393 }
4394
4395 fn set_leader_peer_id(
4396 &mut self,
4397 leader_peer_id: Option<proto::PeerId>,
4398 cx: &mut ViewContext<Self>,
4399 ) {
4400 self.editor.update(cx, |editor, cx| {
4401 editor.set_leader_peer_id(leader_peer_id, cx)
4402 })
4403 }
4404
4405 fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<item::Dedup> {
4406 if existing.context.read(cx).id() == self.context.read(cx).id() {
4407 Some(item::Dedup::KeepExisting)
4408 } else {
4409 None
4410 }
4411 }
4412}
4413
4414pub struct ContextEditorToolbarItem {
4415 fs: Arc<dyn Fs>,
4416 workspace: WeakView<Workspace>,
4417 active_context_editor: Option<WeakView<ContextEditor>>,
4418 model_summary_editor: View<Editor>,
4419 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4420}
4421
4422fn active_editor_focus_handle(
4423 workspace: &WeakView<Workspace>,
4424 cx: &WindowContext<'_>,
4425) -> Option<FocusHandle> {
4426 workspace.upgrade().and_then(|workspace| {
4427 Some(
4428 workspace
4429 .read(cx)
4430 .active_item_as::<Editor>(cx)?
4431 .focus_handle(cx),
4432 )
4433 })
4434}
4435
4436fn render_inject_context_menu(
4437 active_context_editor: WeakView<ContextEditor>,
4438 cx: &mut WindowContext<'_>,
4439) -> impl IntoElement {
4440 let commands = SlashCommandRegistry::global(cx);
4441
4442 slash_command_picker::SlashCommandSelector::new(
4443 commands.clone(),
4444 active_context_editor,
4445 IconButton::new("trigger", IconName::SlashSquare)
4446 .icon_size(IconSize::Small)
4447 .tooltip(|cx| {
4448 Tooltip::with_meta("Insert Context", None, "Type / to insert via keyboard", cx)
4449 }),
4450 )
4451}
4452
4453impl ContextEditorToolbarItem {
4454 pub fn new(
4455 workspace: &Workspace,
4456 model_selector_menu_handle: PopoverMenuHandle<Picker<ModelPickerDelegate>>,
4457 model_summary_editor: View<Editor>,
4458 ) -> Self {
4459 Self {
4460 fs: workspace.app_state().fs.clone(),
4461 workspace: workspace.weak_handle(),
4462 active_context_editor: None,
4463 model_summary_editor,
4464 model_selector_menu_handle,
4465 }
4466 }
4467
4468 fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
4469 let context = &self
4470 .active_context_editor
4471 .as_ref()?
4472 .upgrade()?
4473 .read(cx)
4474 .context;
4475 let (token_count_color, token_count, max_token_count) = match token_state(context, cx)? {
4476 TokenState::NoTokensLeft {
4477 max_token_count,
4478 token_count,
4479 } => (Color::Error, token_count, max_token_count),
4480 TokenState::HasMoreTokens {
4481 max_token_count,
4482 token_count,
4483 over_warn_threshold,
4484 } => {
4485 let color = if over_warn_threshold {
4486 Color::Warning
4487 } else {
4488 Color::Muted
4489 };
4490 (color, token_count, max_token_count)
4491 }
4492 };
4493 Some(
4494 h_flex()
4495 .gap_0p5()
4496 .child(
4497 Label::new(humanize_token_count(token_count))
4498 .size(LabelSize::Small)
4499 .color(token_count_color),
4500 )
4501 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
4502 .child(
4503 Label::new(humanize_token_count(max_token_count))
4504 .size(LabelSize::Small)
4505 .color(Color::Muted),
4506 ),
4507 )
4508 }
4509}
4510
4511impl Render for ContextEditorToolbarItem {
4512 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4513 let left_side = h_flex()
4514 .pl_1()
4515 .gap_2()
4516 .flex_1()
4517 .min_w(rems(DEFAULT_TAB_TITLE.len() as f32))
4518 .when(self.active_context_editor.is_some(), |left_side| {
4519 left_side.child(self.model_summary_editor.clone())
4520 });
4521 let active_provider = LanguageModelRegistry::read_global(cx).active_provider();
4522 let active_model = LanguageModelRegistry::read_global(cx).active_model();
4523 let weak_self = cx.view().downgrade();
4524 let right_side = h_flex()
4525 .gap_2()
4526 .child(
4527 ModelSelector::new(
4528 self.fs.clone(),
4529 ButtonLike::new("active-model")
4530 .style(ButtonStyle::Subtle)
4531 .child(
4532 h_flex()
4533 .w_full()
4534 .gap_0p5()
4535 .child(
4536 div()
4537 .overflow_x_hidden()
4538 .flex_grow()
4539 .whitespace_nowrap()
4540 .child(match (active_provider, active_model) {
4541 (Some(provider), Some(model)) => h_flex()
4542 .gap_1()
4543 .child(
4544 Icon::new(model.icon().unwrap_or_else(|| provider.icon()))
4545 .color(Color::Muted)
4546 .size(IconSize::XSmall),
4547 )
4548 .child(
4549 Label::new(model.name().0)
4550 .size(LabelSize::Small)
4551 .color(Color::Muted),
4552 )
4553 .into_any_element(),
4554 _ => Label::new("No model selected")
4555 .size(LabelSize::Small)
4556 .color(Color::Muted)
4557 .into_any_element(),
4558 }),
4559 )
4560 .child(
4561 Icon::new(IconName::ChevronDown)
4562 .color(Color::Muted)
4563 .size(IconSize::XSmall),
4564 ),
4565 )
4566 .tooltip(move |cx| {
4567 Tooltip::for_action("Change Model", &ToggleModelSelector, cx)
4568 }),
4569 )
4570 .with_handle(self.model_selector_menu_handle.clone()),
4571 )
4572 .children(self.render_remaining_tokens(cx))
4573 .child(
4574 PopoverMenu::new("context-editor-popover")
4575 .trigger(
4576 IconButton::new("context-editor-trigger", IconName::EllipsisVertical)
4577 .icon_size(IconSize::Small)
4578 .tooltip(|cx| Tooltip::text("Open Context Options", cx)),
4579 )
4580 .menu({
4581 let weak_self = weak_self.clone();
4582 move |cx| {
4583 let weak_self = weak_self.clone();
4584 Some(ContextMenu::build(cx, move |menu, cx| {
4585 let context = weak_self
4586 .update(cx, |this, cx| {
4587 active_editor_focus_handle(&this.workspace, cx)
4588 })
4589 .ok()
4590 .flatten();
4591 menu.when_some(context, |menu, context| menu.context(context))
4592 .entry("Regenerate Context Title", None, {
4593 let weak_self = weak_self.clone();
4594 move |cx| {
4595 weak_self
4596 .update(cx, |_, cx| {
4597 cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
4598 })
4599 .ok();
4600 }
4601 })
4602 .custom_entry(
4603 |_| {
4604 h_flex()
4605 .w_full()
4606 .justify_between()
4607 .gap_2()
4608 .child(Label::new("Insert Context"))
4609 .child(Label::new("/ command").color(Color::Muted))
4610 .into_any()
4611 },
4612 {
4613 let weak_self = weak_self.clone();
4614 move |cx| {
4615 weak_self
4616 .update(cx, |this, cx| {
4617 if let Some(editor) =
4618 &this.active_context_editor
4619 {
4620 editor
4621 .update(cx, |this, cx| {
4622 this.slash_menu_handle
4623 .toggle(cx);
4624 })
4625 .ok();
4626 }
4627 })
4628 .ok();
4629 }
4630 },
4631 )
4632 .action("Insert Selection", QuoteSelection.boxed_clone())
4633 }))
4634 }
4635 }),
4636 );
4637
4638 h_flex()
4639 .size_full()
4640 .gap_2()
4641 .justify_between()
4642 .child(left_side)
4643 .child(right_side)
4644 }
4645}
4646
4647impl ToolbarItemView for ContextEditorToolbarItem {
4648 fn set_active_pane_item(
4649 &mut self,
4650 active_pane_item: Option<&dyn ItemHandle>,
4651 cx: &mut ViewContext<Self>,
4652 ) -> ToolbarItemLocation {
4653 self.active_context_editor = active_pane_item
4654 .and_then(|item| item.act_as::<ContextEditor>(cx))
4655 .map(|editor| editor.downgrade());
4656 cx.notify();
4657 if self.active_context_editor.is_none() {
4658 ToolbarItemLocation::Hidden
4659 } else {
4660 ToolbarItemLocation::PrimaryRight
4661 }
4662 }
4663
4664 fn pane_focus_update(&mut self, _pane_focused: bool, cx: &mut ViewContext<Self>) {
4665 cx.notify();
4666 }
4667}
4668
4669impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
4670
4671enum ContextEditorToolbarItemEvent {
4672 RegenerateSummary,
4673}
4674impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
4675
4676pub struct ContextHistory {
4677 picker: View<Picker<SavedContextPickerDelegate>>,
4678 _subscriptions: Vec<Subscription>,
4679 assistant_panel: WeakView<AssistantPanel>,
4680}
4681
4682impl ContextHistory {
4683 fn new(
4684 project: Model<Project>,
4685 context_store: Model<ContextStore>,
4686 assistant_panel: WeakView<AssistantPanel>,
4687 cx: &mut ViewContext<Self>,
4688 ) -> Self {
4689 let picker = cx.new_view(|cx| {
4690 Picker::uniform_list(
4691 SavedContextPickerDelegate::new(project, context_store.clone()),
4692 cx,
4693 )
4694 .modal(false)
4695 .max_height(None)
4696 });
4697
4698 let _subscriptions = vec![
4699 cx.observe(&context_store, |this, _, cx| {
4700 this.picker.update(cx, |picker, cx| picker.refresh(cx));
4701 }),
4702 cx.subscribe(&picker, Self::handle_picker_event),
4703 ];
4704
4705 Self {
4706 picker,
4707 _subscriptions,
4708 assistant_panel,
4709 }
4710 }
4711
4712 fn handle_picker_event(
4713 &mut self,
4714 _: View<Picker<SavedContextPickerDelegate>>,
4715 event: &SavedContextPickerEvent,
4716 cx: &mut ViewContext<Self>,
4717 ) {
4718 let SavedContextPickerEvent::Confirmed(context) = event;
4719 self.assistant_panel
4720 .update(cx, |assistant_panel, cx| match context {
4721 ContextMetadata::Remote(metadata) => {
4722 assistant_panel
4723 .open_remote_context(metadata.id.clone(), cx)
4724 .detach_and_log_err(cx);
4725 }
4726 ContextMetadata::Saved(metadata) => {
4727 assistant_panel
4728 .open_saved_context(metadata.path.clone(), cx)
4729 .detach_and_log_err(cx);
4730 }
4731 })
4732 .ok();
4733 }
4734}
4735
4736#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4737pub enum WorkflowAssistStatus {
4738 Pending,
4739 Confirmed,
4740 Done,
4741 Idle,
4742}
4743
4744impl WorkflowAssist {
4745 pub fn status(&self, cx: &AppContext) -> WorkflowAssistStatus {
4746 let assistant = InlineAssistant::global(cx);
4747 if self
4748 .assist_ids
4749 .iter()
4750 .any(|assist_id| assistant.assist_status(*assist_id, cx).is_pending())
4751 {
4752 WorkflowAssistStatus::Pending
4753 } else if self
4754 .assist_ids
4755 .iter()
4756 .all(|assist_id| assistant.assist_status(*assist_id, cx).is_confirmed())
4757 {
4758 WorkflowAssistStatus::Confirmed
4759 } else if self
4760 .assist_ids
4761 .iter()
4762 .all(|assist_id| assistant.assist_status(*assist_id, cx).is_done())
4763 {
4764 WorkflowAssistStatus::Done
4765 } else {
4766 WorkflowAssistStatus::Idle
4767 }
4768 }
4769}
4770
4771impl Render for ContextHistory {
4772 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
4773 div().size_full().child(self.picker.clone())
4774 }
4775}
4776
4777impl FocusableView for ContextHistory {
4778 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
4779 self.picker.focus_handle(cx)
4780 }
4781}
4782
4783impl EventEmitter<()> for ContextHistory {}
4784
4785impl Item for ContextHistory {
4786 type Event = ();
4787
4788 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4789 Some("History".into())
4790 }
4791}
4792
4793pub struct ConfigurationView {
4794 focus_handle: FocusHandle,
4795 configuration_views: HashMap<LanguageModelProviderId, AnyView>,
4796 _registry_subscription: Subscription,
4797}
4798
4799impl ConfigurationView {
4800 fn new(cx: &mut ViewContext<Self>) -> Self {
4801 let focus_handle = cx.focus_handle();
4802
4803 let registry_subscription = cx.subscribe(
4804 &LanguageModelRegistry::global(cx),
4805 |this, _, event: &language_model::Event, cx| match event {
4806 language_model::Event::AddedProvider(provider_id) => {
4807 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
4808 if let Some(provider) = provider {
4809 this.add_configuration_view(&provider, cx);
4810 }
4811 }
4812 language_model::Event::RemovedProvider(provider_id) => {
4813 this.remove_configuration_view(provider_id);
4814 }
4815 _ => {}
4816 },
4817 );
4818
4819 let mut this = Self {
4820 focus_handle,
4821 configuration_views: HashMap::default(),
4822 _registry_subscription: registry_subscription,
4823 };
4824 this.build_configuration_views(cx);
4825 this
4826 }
4827
4828 fn build_configuration_views(&mut self, cx: &mut ViewContext<Self>) {
4829 let providers = LanguageModelRegistry::read_global(cx).providers();
4830 for provider in providers {
4831 self.add_configuration_view(&provider, cx);
4832 }
4833 }
4834
4835 fn remove_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
4836 self.configuration_views.remove(provider_id);
4837 }
4838
4839 fn add_configuration_view(
4840 &mut self,
4841 provider: &Arc<dyn LanguageModelProvider>,
4842 cx: &mut ViewContext<Self>,
4843 ) {
4844 let configuration_view = provider.configuration_view(cx);
4845 self.configuration_views
4846 .insert(provider.id(), configuration_view);
4847 }
4848
4849 fn render_provider_view(
4850 &mut self,
4851 provider: &Arc<dyn LanguageModelProvider>,
4852 cx: &mut ViewContext<Self>,
4853 ) -> Div {
4854 let provider_id = provider.id().0.clone();
4855 let provider_name = provider.name().0.clone();
4856 let configuration_view = self.configuration_views.get(&provider.id()).cloned();
4857
4858 let open_new_context = cx.listener({
4859 let provider = provider.clone();
4860 move |_, _, cx| {
4861 cx.emit(ConfigurationViewEvent::NewProviderContextEditor(
4862 provider.clone(),
4863 ))
4864 }
4865 });
4866
4867 v_flex()
4868 .gap_2()
4869 .child(
4870 h_flex()
4871 .justify_between()
4872 .child(Headline::new(provider_name.clone()).size(HeadlineSize::Small))
4873 .when(provider.is_authenticated(cx), move |this| {
4874 this.child(
4875 h_flex().justify_end().child(
4876 Button::new(
4877 SharedString::from(format!("new-context-{provider_id}")),
4878 "Open new context",
4879 )
4880 .icon_position(IconPosition::Start)
4881 .icon(IconName::Plus)
4882 .style(ButtonStyle::Filled)
4883 .layer(ElevationIndex::ModalSurface)
4884 .on_click(open_new_context),
4885 ),
4886 )
4887 }),
4888 )
4889 .child(
4890 div()
4891 .p(Spacing::Large.rems(cx))
4892 .bg(cx.theme().colors().surface_background)
4893 .border_1()
4894 .border_color(cx.theme().colors().border_variant)
4895 .rounded_md()
4896 .when(configuration_view.is_none(), |this| {
4897 this.child(div().child(Label::new(format!(
4898 "No configuration view for {}",
4899 provider_name
4900 ))))
4901 })
4902 .when_some(configuration_view, |this, configuration_view| {
4903 this.child(configuration_view)
4904 }),
4905 )
4906 }
4907}
4908
4909impl Render for ConfigurationView {
4910 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
4911 let providers = LanguageModelRegistry::read_global(cx).providers();
4912 let provider_views = providers
4913 .into_iter()
4914 .map(|provider| self.render_provider_view(&provider, cx))
4915 .collect::<Vec<_>>();
4916
4917 let mut element = v_flex()
4918 .id("assistant-configuration-view")
4919 .track_focus(&self.focus_handle)
4920 .bg(cx.theme().colors().editor_background)
4921 .size_full()
4922 .overflow_y_scroll()
4923 .child(
4924 v_flex()
4925 .p(Spacing::XXLarge.rems(cx))
4926 .border_b_1()
4927 .border_color(cx.theme().colors().border)
4928 .gap_1()
4929 .child(Headline::new("Configure your Assistant").size(HeadlineSize::Medium))
4930 .child(
4931 Label::new(
4932 "At least one LLM provider must be configured to use the Assistant.",
4933 )
4934 .color(Color::Muted),
4935 ),
4936 )
4937 .child(
4938 v_flex()
4939 .p(Spacing::XXLarge.rems(cx))
4940 .mt_1()
4941 .gap_6()
4942 .flex_1()
4943 .children(provider_views),
4944 )
4945 .into_any();
4946
4947 // We use a canvas here to get scrolling to work in the ConfigurationView. It's a workaround
4948 // because we couldn't the element to take up the size of the parent.
4949 canvas(
4950 move |bounds, cx| {
4951 element.prepaint_as_root(bounds.origin, bounds.size.into(), cx);
4952 element
4953 },
4954 |_, mut element, cx| {
4955 element.paint(cx);
4956 },
4957 )
4958 .flex_1()
4959 .w_full()
4960 }
4961}
4962
4963pub enum ConfigurationViewEvent {
4964 NewProviderContextEditor(Arc<dyn LanguageModelProvider>),
4965}
4966
4967impl EventEmitter<ConfigurationViewEvent> for ConfigurationView {}
4968
4969impl FocusableView for ConfigurationView {
4970 fn focus_handle(&self, _: &AppContext) -> FocusHandle {
4971 self.focus_handle.clone()
4972 }
4973}
4974
4975impl Item for ConfigurationView {
4976 type Event = ConfigurationViewEvent;
4977
4978 fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
4979 Some("Configuration".into())
4980 }
4981}
4982
4983type ToggleFold = Arc<dyn Fn(bool, &mut WindowContext) + Send + Sync>;
4984
4985fn render_slash_command_output_toggle(
4986 row: MultiBufferRow,
4987 is_folded: bool,
4988 fold: ToggleFold,
4989 _cx: &mut WindowContext,
4990) -> AnyElement {
4991 Disclosure::new(
4992 ("slash-command-output-fold-indicator", row.0 as u64),
4993 !is_folded,
4994 )
4995 .selected(is_folded)
4996 .on_click(move |_e, cx| fold(!is_folded, cx))
4997 .into_any_element()
4998}
4999
5000fn fold_toggle(
5001 name: &'static str,
5002) -> impl Fn(
5003 MultiBufferRow,
5004 bool,
5005 Arc<dyn Fn(bool, &mut WindowContext<'_>) + Send + Sync>,
5006 &mut WindowContext<'_>,
5007) -> AnyElement {
5008 move |row, is_folded, fold, _cx| {
5009 Disclosure::new((name, row.0 as u64), !is_folded)
5010 .selected(is_folded)
5011 .on_click(move |_e, cx| fold(!is_folded, cx))
5012 .into_any_element()
5013 }
5014}
5015
5016fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) -> FoldPlaceholder {
5017 FoldPlaceholder {
5018 render: Arc::new({
5019 move |fold_id, fold_range, _cx| {
5020 let editor = editor.clone();
5021 ButtonLike::new(fold_id)
5022 .style(ButtonStyle::Filled)
5023 .layer(ElevationIndex::ElevatedSurface)
5024 .child(Icon::new(IconName::TextSelect))
5025 .child(Label::new(title.clone()).single_line())
5026 .on_click(move |_, cx| {
5027 editor
5028 .update(cx, |editor, cx| {
5029 let buffer_start = fold_range
5030 .start
5031 .to_point(&editor.buffer().read(cx).read(cx));
5032 let buffer_row = MultiBufferRow(buffer_start.row);
5033 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
5034 })
5035 .ok();
5036 })
5037 .into_any_element()
5038 }
5039 }),
5040 constrain_width: false,
5041 merge_adjacent: false,
5042 }
5043}
5044
5045fn render_quote_selection_output_toggle(
5046 row: MultiBufferRow,
5047 is_folded: bool,
5048 fold: ToggleFold,
5049 _cx: &mut WindowContext,
5050) -> AnyElement {
5051 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
5052 .selected(is_folded)
5053 .on_click(move |_e, cx| fold(!is_folded, cx))
5054 .into_any_element()
5055}
5056
5057fn render_pending_slash_command_gutter_decoration(
5058 row: MultiBufferRow,
5059 status: &PendingSlashCommandStatus,
5060 confirm_command: Arc<dyn Fn(&mut WindowContext)>,
5061) -> AnyElement {
5062 let mut icon = IconButton::new(
5063 ("slash-command-gutter-decoration", row.0),
5064 ui::IconName::TriangleRight,
5065 )
5066 .on_click(move |_e, cx| confirm_command(cx))
5067 .icon_size(ui::IconSize::Small)
5068 .size(ui::ButtonSize::None);
5069
5070 match status {
5071 PendingSlashCommandStatus::Idle => {
5072 icon = icon.icon_color(Color::Muted);
5073 }
5074 PendingSlashCommandStatus::Running { .. } => {
5075 icon = icon.selected(true);
5076 }
5077 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
5078 }
5079
5080 icon.into_any_element()
5081}
5082
5083fn render_docs_slash_command_trailer(
5084 row: MultiBufferRow,
5085 command: PendingSlashCommand,
5086 cx: &mut WindowContext,
5087) -> AnyElement {
5088 if command.arguments.is_empty() {
5089 return Empty.into_any();
5090 }
5091 let args = DocsSlashCommandArgs::parse(&command.arguments);
5092
5093 let Some(store) = args
5094 .provider()
5095 .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
5096 else {
5097 return Empty.into_any();
5098 };
5099
5100 let Some(package) = args.package() else {
5101 return Empty.into_any();
5102 };
5103
5104 let mut children = Vec::new();
5105
5106 if store.is_indexing(&package) {
5107 children.push(
5108 div()
5109 .id(("crates-being-indexed", row.0))
5110 .child(Icon::new(IconName::ArrowCircle).with_animation(
5111 "arrow-circle",
5112 Animation::new(Duration::from_secs(4)).repeat(),
5113 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
5114 ))
5115 .tooltip({
5116 let package = package.clone();
5117 move |cx| Tooltip::text(format!("Indexing {package}…"), cx)
5118 })
5119 .into_any_element(),
5120 );
5121 }
5122
5123 if let Some(latest_error) = store.latest_error_for_package(&package) {
5124 children.push(
5125 div()
5126 .id(("latest-error", row.0))
5127 .child(
5128 Icon::new(IconName::ExclamationTriangle)
5129 .size(IconSize::Small)
5130 .color(Color::Warning),
5131 )
5132 .tooltip(move |cx| Tooltip::text(format!("Failed to index: {latest_error}"), cx))
5133 .into_any_element(),
5134 )
5135 }
5136
5137 let is_indexing = store.is_indexing(&package);
5138 let latest_error = store.latest_error_for_package(&package);
5139
5140 if !is_indexing && latest_error.is_none() {
5141 return Empty.into_any();
5142 }
5143
5144 h_flex().gap_2().children(children).into_any_element()
5145}
5146
5147fn make_lsp_adapter_delegate(
5148 project: &Model<Project>,
5149 cx: &mut AppContext,
5150) -> Result<Arc<dyn LspAdapterDelegate>> {
5151 project.update(cx, |project, cx| {
5152 // TODO: Find the right worktree.
5153 let worktree = project
5154 .worktrees(cx)
5155 .next()
5156 .ok_or_else(|| anyhow!("no worktrees when constructing ProjectLspAdapterDelegate"))?;
5157 project.lsp_store().update(cx, |lsp_store, cx| {
5158 Ok(ProjectLspAdapterDelegate::new(lsp_store, &worktree, cx)
5159 as Arc<dyn LspAdapterDelegate>)
5160 })
5161 })
5162}
5163
5164fn slash_command_error_block_renderer(message: String) -> RenderBlock {
5165 Box::new(move |_| {
5166 div()
5167 .pl_6()
5168 .child(
5169 Label::new(format!("error: {}", message))
5170 .single_line()
5171 .color(Color::Error),
5172 )
5173 .into_any()
5174 })
5175}
5176
5177enum TokenState {
5178 NoTokensLeft {
5179 max_token_count: usize,
5180 token_count: usize,
5181 },
5182 HasMoreTokens {
5183 max_token_count: usize,
5184 token_count: usize,
5185 over_warn_threshold: bool,
5186 },
5187}
5188
5189fn token_state(context: &Model<Context>, cx: &AppContext) -> Option<TokenState> {
5190 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
5191
5192 let model = LanguageModelRegistry::read_global(cx).active_model()?;
5193 let token_count = context.read(cx).token_count()?;
5194 let max_token_count = model.max_token_count();
5195
5196 let remaining_tokens = max_token_count as isize - token_count as isize;
5197 let token_state = if remaining_tokens <= 0 {
5198 TokenState::NoTokensLeft {
5199 max_token_count,
5200 token_count,
5201 }
5202 } else {
5203 let over_warn_threshold =
5204 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
5205 TokenState::HasMoreTokens {
5206 max_token_count,
5207 token_count,
5208 over_warn_threshold,
5209 }
5210 };
5211 Some(token_state)
5212}
5213
5214fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
5215 let image_size = data
5216 .size(0)
5217 .map(|dimension| Pixels::from(u32::from(dimension)));
5218 let image_ratio = image_size.width / image_size.height;
5219 let bounds_ratio = max_size.width / max_size.height;
5220
5221 if image_size.width > max_size.width || image_size.height > max_size.height {
5222 if bounds_ratio > image_ratio {
5223 size(
5224 image_size.width * (max_size.height / image_size.height),
5225 max_size.height,
5226 )
5227 } else {
5228 size(
5229 max_size.width,
5230 image_size.height * (max_size.width / image_size.width),
5231 )
5232 }
5233 } else {
5234 size(image_size.width, image_size.height)
5235 }
5236}
5237
5238enum ConfigurationError {
5239 NoProvider,
5240 ProviderNotAuthenticated,
5241}
5242
5243fn configuration_error(cx: &AppContext) -> Option<ConfigurationError> {
5244 let provider = LanguageModelRegistry::read_global(cx).active_provider();
5245 let is_authenticated = provider
5246 .as_ref()
5247 .map_or(false, |provider| provider.is_authenticated(cx));
5248
5249 if provider.is_some() && is_authenticated {
5250 return None;
5251 }
5252
5253 if provider.is_none() {
5254 return Some(ConfigurationError::NoProvider);
5255 }
5256
5257 if !is_authenticated {
5258 return Some(ConfigurationError::ProviderNotAuthenticated);
5259 }
5260
5261 None
5262}