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