1use crate::{
2 assistant_settings::{AssistantDockPosition, AssistantSettings, OpenAIModel},
3 codegen::{self, Codegen, CodegenKind},
4 prompts::generate_content_prompt,
5 Assist, CycleMessageRole, InlineAssist, MessageId, MessageMetadata, MessageStatus,
6 NewConversation, QuoteSelection, ResetKey, Role, SavedConversation, SavedConversationMetadata,
7 SavedMessage, Split, ToggleFocus, ToggleIncludeConversation, ToggleRetrieveContext,
8};
9
10use ai::{
11 auth::ProviderCredential,
12 completion::{CompletionProvider, CompletionRequest},
13 providers::open_ai::{OpenAICompletionProvider, OpenAIRequest, RequestMessage},
14};
15
16use ai::prompts::repository_context::PromptCodeSnippet;
17use anyhow::{anyhow, Result};
18use chrono::{DateTime, Local};
19use client::{telemetry::AssistantKind, TelemetrySettings};
20use collections::{hash_map, HashMap, HashSet, VecDeque};
21use editor::{
22 display_map::{
23 BlockContext, BlockDisposition, BlockId, BlockProperties, BlockStyle, ToDisplayPoint,
24 },
25 scroll::autoscroll::{Autoscroll, AutoscrollStrategy},
26 Anchor, Editor, EditorElement, EditorEvent, EditorStyle, MoveDown, MoveUp, MultiBufferSnapshot,
27 ToOffset, ToPoint,
28};
29use fs::Fs;
30use futures::StreamExt;
31use gpui::{
32 div, point, relative, rems, uniform_list, Action, AnyElement, AppContext, AsyncWindowContext,
33 ClipboardItem, Context, Div, EventEmitter, FocusHandle, Focusable, FocusableView, FontStyle,
34 FontWeight, HighlightStyle, InteractiveElement, IntoElement, Model, ModelContext,
35 ParentElement, Pixels, PromptLevel, Render, SharedString, StatefulInteractiveElement, Styled,
36 Subscription, Task, TextStyle, UniformListScrollHandle, View, ViewContext, VisualContext,
37 WeakModel, WeakView, WhiteSpace, WindowContext,
38};
39use language::{language_settings::SoftWrap, Buffer, LanguageRegistry, ToOffset as _};
40use project::Project;
41use search::BufferSearchBar;
42use semantic_index::{SemanticIndex, SemanticIndexStatus};
43use settings::{Settings, SettingsStore};
44use std::{
45 cell::Cell,
46 cmp,
47 fmt::Write,
48 iter,
49 ops::Range,
50 path::{Path, PathBuf},
51 rc::Rc,
52 sync::Arc,
53 time::{Duration, Instant},
54};
55use theme::ThemeSettings;
56use ui::{
57 h_stack, prelude::*, v_stack, Button, ButtonLike, Icon, IconButton, IconElement, Label, Tooltip,
58};
59use util::{paths::CONVERSATIONS_DIR, post_inc, ResultExt, TryFutureExt};
60use uuid::Uuid;
61use workspace::{
62 dock::{DockPosition, Panel, PanelEvent},
63 searchable::Direction,
64 Save, Toast, ToggleZoom, Toolbar, Workspace,
65};
66
67pub fn init(cx: &mut AppContext) {
68 AssistantSettings::register(cx);
69 cx.observe_new_views(
70 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
71 workspace
72 .register_action(|workspace, _: &ToggleFocus, cx| {
73 workspace.toggle_panel_focus::<AssistantPanel>(cx);
74 })
75 .register_action(AssistantPanel::inline_assist)
76 .register_action(AssistantPanel::cancel_last_inline_assist)
77 .register_action(ConversationEditor::quote_selection);
78 },
79 )
80 .detach();
81}
82
83pub struct AssistantPanel {
84 workspace: WeakView<Workspace>,
85 width: Option<f32>,
86 height: Option<f32>,
87 active_editor_index: Option<usize>,
88 prev_active_editor_index: Option<usize>,
89 editors: Vec<View<ConversationEditor>>,
90 saved_conversations: Vec<SavedConversationMetadata>,
91 saved_conversations_scroll_handle: UniformListScrollHandle,
92 zoomed: bool,
93 focus_handle: FocusHandle,
94 toolbar: View<Toolbar>,
95 completion_provider: Arc<dyn CompletionProvider>,
96 api_key_editor: Option<View<Editor>>,
97 languages: Arc<LanguageRegistry>,
98 fs: Arc<dyn Fs>,
99 subscriptions: Vec<Subscription>,
100 next_inline_assist_id: usize,
101 pending_inline_assists: HashMap<usize, PendingInlineAssist>,
102 pending_inline_assist_ids_by_editor: HashMap<WeakView<Editor>, Vec<usize>>,
103 include_conversation_in_next_inline_assist: bool,
104 inline_prompt_history: VecDeque<String>,
105 _watch_saved_conversations: Task<Result<()>>,
106 semantic_index: Option<Model<SemanticIndex>>,
107 retrieve_context_in_next_inline_assist: bool,
108}
109
110impl AssistantPanel {
111 const INLINE_PROMPT_HISTORY_MAX_LEN: usize = 20;
112
113 pub fn load(
114 workspace: WeakView<Workspace>,
115 cx: AsyncWindowContext,
116 ) -> Task<Result<View<Self>>> {
117 cx.spawn(|mut cx| async move {
118 let fs = workspace.update(&mut cx, |workspace, _| workspace.app_state().fs.clone())?;
119 let saved_conversations = SavedConversationMetadata::list(fs.clone())
120 .await
121 .log_err()
122 .unwrap_or_default();
123
124 // TODO: deserialize state.
125 let workspace_handle = workspace.clone();
126 workspace.update(&mut cx, |workspace, cx| {
127 cx.build_view::<Self>(|cx| {
128 const CONVERSATION_WATCH_DURATION: Duration = Duration::from_millis(100);
129 let _watch_saved_conversations = cx.spawn(move |this, mut cx| async move {
130 let mut events = fs
131 .watch(&CONVERSATIONS_DIR, CONVERSATION_WATCH_DURATION)
132 .await;
133 while events.next().await.is_some() {
134 let saved_conversations = SavedConversationMetadata::list(fs.clone())
135 .await
136 .log_err()
137 .unwrap_or_default();
138 this.update(&mut cx, |this, cx| {
139 this.saved_conversations = saved_conversations;
140 cx.notify();
141 })
142 .ok();
143 }
144
145 anyhow::Ok(())
146 });
147
148 let toolbar = cx.build_view(|cx| {
149 let mut toolbar = Toolbar::new();
150 toolbar.set_can_navigate(false, cx);
151 toolbar.add_item(cx.build_view(|cx| BufferSearchBar::new(cx)), cx);
152 toolbar
153 });
154
155 let semantic_index = SemanticIndex::global(cx);
156 // Defaulting currently to GPT4, allow for this to be set via config.
157 let completion_provider = Arc::new(OpenAICompletionProvider::new(
158 "gpt-4",
159 cx.background_executor().clone(),
160 ));
161
162 let focus_handle = cx.focus_handle();
163 cx.on_focus_in(&focus_handle, Self::focus_in).detach();
164 cx.on_focus_out(&focus_handle, Self::focus_out).detach();
165
166 let mut this = Self {
167 workspace: workspace_handle,
168 active_editor_index: Default::default(),
169 prev_active_editor_index: Default::default(),
170 editors: Default::default(),
171 saved_conversations,
172 saved_conversations_scroll_handle: Default::default(),
173 zoomed: false,
174 focus_handle,
175 toolbar,
176 completion_provider,
177 api_key_editor: None,
178 languages: workspace.app_state().languages.clone(),
179 fs: workspace.app_state().fs.clone(),
180 width: None,
181 height: None,
182 subscriptions: Default::default(),
183 next_inline_assist_id: 0,
184 pending_inline_assists: Default::default(),
185 pending_inline_assist_ids_by_editor: Default::default(),
186 include_conversation_in_next_inline_assist: false,
187 inline_prompt_history: Default::default(),
188 _watch_saved_conversations,
189 semantic_index,
190 retrieve_context_in_next_inline_assist: false,
191 };
192
193 let mut old_dock_position = this.position(cx);
194 this.subscriptions =
195 vec![cx.observe_global::<SettingsStore>(move |this, cx| {
196 let new_dock_position = this.position(cx);
197 if new_dock_position != old_dock_position {
198 old_dock_position = new_dock_position;
199 cx.emit(PanelEvent::ChangePosition);
200 }
201 cx.notify();
202 })];
203
204 this
205 })
206 })
207 })
208 }
209
210 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
211 self.toolbar
212 .update(cx, |toolbar, cx| toolbar.focus_changed(true, cx));
213 cx.notify();
214 if self.focus_handle.is_focused(cx) {
215 if let Some(editor) = self.active_editor() {
216 cx.focus_view(editor);
217 } else if let Some(api_key_editor) = self.api_key_editor.as_ref() {
218 cx.focus_view(api_key_editor);
219 }
220 }
221 }
222
223 fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
224 self.toolbar
225 .update(cx, |toolbar, cx| toolbar.focus_changed(false, cx));
226 cx.notify();
227 }
228
229 pub fn inline_assist(
230 workspace: &mut Workspace,
231 _: &InlineAssist,
232 cx: &mut ViewContext<Workspace>,
233 ) {
234 let this = if let Some(this) = workspace.panel::<AssistantPanel>(cx) {
235 if this.update(cx, |assistant, cx| {
236 if !assistant.has_credentials() {
237 assistant.load_credentials(cx);
238 };
239
240 assistant.has_credentials()
241 }) {
242 this
243 } else {
244 workspace.focus_panel::<AssistantPanel>(cx);
245 return;
246 }
247 } else {
248 return;
249 };
250
251 let active_editor = if let Some(active_editor) = workspace
252 .active_item(cx)
253 .and_then(|item| item.act_as::<Editor>(cx))
254 {
255 active_editor
256 } else {
257 return;
258 };
259
260 let project = workspace.project();
261
262 this.update(cx, |assistant, cx| {
263 assistant.new_inline_assist(&active_editor, cx, project)
264 });
265 }
266
267 fn new_inline_assist(
268 &mut self,
269 editor: &View<Editor>,
270 cx: &mut ViewContext<Self>,
271 project: &Model<Project>,
272 ) {
273 let selection = editor.read(cx).selections.newest_anchor().clone();
274 if selection.start.excerpt_id != selection.end.excerpt_id {
275 return;
276 }
277 let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
278
279 // Extend the selection to the start and the end of the line.
280 let mut point_selection = selection.map(|selection| selection.to_point(&snapshot));
281 if point_selection.end > point_selection.start {
282 point_selection.start.column = 0;
283 // If the selection ends at the start of the line, we don't want to include it.
284 if point_selection.end.column == 0 {
285 point_selection.end.row -= 1;
286 }
287 point_selection.end.column = snapshot.line_len(point_selection.end.row);
288 }
289
290 let codegen_kind = if point_selection.start == point_selection.end {
291 CodegenKind::Generate {
292 position: snapshot.anchor_after(point_selection.start),
293 }
294 } else {
295 CodegenKind::Transform {
296 range: snapshot.anchor_before(point_selection.start)
297 ..snapshot.anchor_after(point_selection.end),
298 }
299 };
300
301 let inline_assist_id = post_inc(&mut self.next_inline_assist_id);
302 let provider = self.completion_provider.clone();
303
304 // Retrieve Credentials Authenticates the Provider
305 provider.retrieve_credentials(cx);
306
307 let codegen = cx.build_model(|cx| {
308 Codegen::new(editor.read(cx).buffer().clone(), codegen_kind, provider, cx)
309 });
310
311 if let Some(semantic_index) = self.semantic_index.clone() {
312 let project = project.clone();
313 cx.spawn(|_, mut cx| async move {
314 let previously_indexed = semantic_index
315 .update(&mut cx, |index, cx| {
316 index.project_previously_indexed(&project, cx)
317 })?
318 .await
319 .unwrap_or(false);
320 if previously_indexed {
321 let _ = semantic_index
322 .update(&mut cx, |index, cx| {
323 index.index_project(project.clone(), cx)
324 })?
325 .await;
326 }
327 anyhow::Ok(())
328 })
329 .detach_and_log_err(cx);
330 }
331
332 let measurements = Rc::new(Cell::new(BlockMeasurements::default()));
333 let inline_assistant = cx.build_view(|cx| {
334 InlineAssistant::new(
335 inline_assist_id,
336 measurements.clone(),
337 self.include_conversation_in_next_inline_assist,
338 self.inline_prompt_history.clone(),
339 codegen.clone(),
340 self.workspace.clone(),
341 cx,
342 self.retrieve_context_in_next_inline_assist,
343 self.semantic_index.clone(),
344 project.clone(),
345 )
346 });
347 let block_id = editor.update(cx, |editor, cx| {
348 editor.change_selections(None, cx, |selections| {
349 selections.select_anchor_ranges([selection.head()..selection.head()])
350 });
351 editor.insert_blocks(
352 [BlockProperties {
353 style: BlockStyle::Flex,
354 position: snapshot.anchor_before(point_selection.head()),
355 height: 2,
356 render: Arc::new({
357 let inline_assistant = inline_assistant.clone();
358 move |cx: &mut BlockContext| {
359 measurements.set(BlockMeasurements {
360 anchor_x: cx.anchor_x,
361 gutter_width: cx.gutter_width,
362 });
363 inline_assistant.clone().into_any_element()
364 }
365 }),
366 disposition: if selection.reversed {
367 BlockDisposition::Above
368 } else {
369 BlockDisposition::Below
370 },
371 }],
372 Some(Autoscroll::Strategy(AutoscrollStrategy::Newest)),
373 cx,
374 )[0]
375 });
376
377 self.pending_inline_assists.insert(
378 inline_assist_id,
379 PendingInlineAssist {
380 editor: editor.downgrade(),
381 inline_assistant: Some((block_id, inline_assistant.clone())),
382 codegen: codegen.clone(),
383 project: project.downgrade(),
384 _subscriptions: vec![
385 cx.subscribe(&inline_assistant, Self::handle_inline_assistant_event),
386 cx.subscribe(editor, {
387 let inline_assistant = inline_assistant.downgrade();
388 move |_, editor, event, cx| {
389 if let Some(inline_assistant) = inline_assistant.upgrade() {
390 if let EditorEvent::SelectionsChanged { local } = event {
391 if *local
392 && inline_assistant.focus_handle(cx).contains_focused(cx)
393 {
394 cx.focus_view(&editor);
395 }
396 }
397 }
398 }
399 }),
400 cx.observe(&codegen, {
401 let editor = editor.downgrade();
402 move |this, _, cx| {
403 if let Some(editor) = editor.upgrade() {
404 this.update_highlights_for_editor(&editor, cx);
405 }
406 }
407 }),
408 cx.subscribe(&codegen, move |this, codegen, event, cx| match event {
409 codegen::Event::Undone => {
410 this.finish_inline_assist(inline_assist_id, false, cx)
411 }
412 codegen::Event::Finished => {
413 let pending_assist = if let Some(pending_assist) =
414 this.pending_inline_assists.get(&inline_assist_id)
415 {
416 pending_assist
417 } else {
418 return;
419 };
420
421 let error = codegen
422 .read(cx)
423 .error()
424 .map(|error| format!("Inline assistant error: {}", error));
425 if let Some(error) = error {
426 if pending_assist.inline_assistant.is_none() {
427 if let Some(workspace) = this.workspace.upgrade() {
428 workspace.update(cx, |workspace, cx| {
429 workspace.show_toast(
430 Toast::new(inline_assist_id, error),
431 cx,
432 );
433 })
434 }
435
436 this.finish_inline_assist(inline_assist_id, false, cx);
437 }
438 } else {
439 this.finish_inline_assist(inline_assist_id, false, cx);
440 }
441 }
442 }),
443 ],
444 },
445 );
446 self.pending_inline_assist_ids_by_editor
447 .entry(editor.downgrade())
448 .or_default()
449 .push(inline_assist_id);
450 self.update_highlights_for_editor(&editor, cx);
451 }
452
453 fn handle_inline_assistant_event(
454 &mut self,
455 inline_assistant: View<InlineAssistant>,
456 event: &InlineAssistantEvent,
457 cx: &mut ViewContext<Self>,
458 ) {
459 let assist_id = inline_assistant.read(cx).id;
460 match event {
461 InlineAssistantEvent::Confirmed {
462 prompt,
463 include_conversation,
464 retrieve_context,
465 } => {
466 self.confirm_inline_assist(
467 assist_id,
468 prompt,
469 *include_conversation,
470 cx,
471 *retrieve_context,
472 );
473 }
474 InlineAssistantEvent::Canceled => {
475 self.finish_inline_assist(assist_id, true, cx);
476 }
477 InlineAssistantEvent::Dismissed => {
478 self.hide_inline_assist(assist_id, cx);
479 }
480 InlineAssistantEvent::IncludeConversationToggled {
481 include_conversation,
482 } => {
483 self.include_conversation_in_next_inline_assist = *include_conversation;
484 }
485 InlineAssistantEvent::RetrieveContextToggled { retrieve_context } => {
486 self.retrieve_context_in_next_inline_assist = *retrieve_context
487 }
488 }
489 }
490
491 fn cancel_last_inline_assist(
492 workspace: &mut Workspace,
493 _: &editor::Cancel,
494 cx: &mut ViewContext<Workspace>,
495 ) {
496 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
497 if let Some(editor) = workspace
498 .active_item(cx)
499 .and_then(|item| item.downcast::<Editor>())
500 {
501 let handled = panel.update(cx, |panel, cx| {
502 if let Some(assist_id) = panel
503 .pending_inline_assist_ids_by_editor
504 .get(&editor.downgrade())
505 .and_then(|assist_ids| assist_ids.last().copied())
506 {
507 panel.finish_inline_assist(assist_id, true, cx);
508 true
509 } else {
510 false
511 }
512 });
513 if handled {
514 return;
515 }
516 }
517 }
518
519 cx.propagate();
520 }
521
522 fn finish_inline_assist(&mut self, assist_id: usize, undo: bool, cx: &mut ViewContext<Self>) {
523 self.hide_inline_assist(assist_id, cx);
524
525 if let Some(pending_assist) = self.pending_inline_assists.remove(&assist_id) {
526 if let hash_map::Entry::Occupied(mut entry) = self
527 .pending_inline_assist_ids_by_editor
528 .entry(pending_assist.editor.clone())
529 {
530 entry.get_mut().retain(|id| *id != assist_id);
531 if entry.get().is_empty() {
532 entry.remove();
533 }
534 }
535
536 if let Some(editor) = pending_assist.editor.upgrade() {
537 self.update_highlights_for_editor(&editor, cx);
538
539 if undo {
540 pending_assist
541 .codegen
542 .update(cx, |codegen, cx| codegen.undo(cx));
543 }
544 }
545 }
546 }
547
548 fn hide_inline_assist(&mut self, assist_id: usize, cx: &mut ViewContext<Self>) {
549 if let Some(pending_assist) = self.pending_inline_assists.get_mut(&assist_id) {
550 if let Some(editor) = pending_assist.editor.upgrade() {
551 if let Some((block_id, inline_assistant)) = pending_assist.inline_assistant.take() {
552 editor.update(cx, |editor, cx| {
553 editor.remove_blocks(HashSet::from_iter([block_id]), None, cx);
554 if inline_assistant.focus_handle(cx).contains_focused(cx) {
555 editor.focus(cx);
556 }
557 });
558 }
559 }
560 }
561 }
562
563 fn confirm_inline_assist(
564 &mut self,
565 inline_assist_id: usize,
566 user_prompt: &str,
567 include_conversation: bool,
568 cx: &mut ViewContext<Self>,
569 retrieve_context: bool,
570 ) {
571 let conversation = if include_conversation {
572 self.active_editor()
573 .map(|editor| editor.read(cx).conversation.clone())
574 } else {
575 None
576 };
577
578 let pending_assist =
579 if let Some(pending_assist) = self.pending_inline_assists.get_mut(&inline_assist_id) {
580 pending_assist
581 } else {
582 return;
583 };
584
585 let editor = if let Some(editor) = pending_assist.editor.upgrade() {
586 editor
587 } else {
588 return;
589 };
590
591 let project = pending_assist.project.clone();
592
593 let project_name = if let Some(project) = project.upgrade() {
594 Some(
595 project
596 .read(cx)
597 .worktree_root_names(cx)
598 .collect::<Vec<&str>>()
599 .join("/"),
600 )
601 } else {
602 None
603 };
604
605 self.inline_prompt_history
606 .retain(|prompt| prompt != user_prompt);
607 self.inline_prompt_history.push_back(user_prompt.into());
608 if self.inline_prompt_history.len() > Self::INLINE_PROMPT_HISTORY_MAX_LEN {
609 self.inline_prompt_history.pop_front();
610 }
611
612 let codegen = pending_assist.codegen.clone();
613 let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
614 let range = codegen.read(cx).range();
615 let start = snapshot.point_to_buffer_offset(range.start);
616 let end = snapshot.point_to_buffer_offset(range.end);
617 let (buffer, range) = if let Some((start, end)) = start.zip(end) {
618 let (start_buffer, start_buffer_offset) = start;
619 let (end_buffer, end_buffer_offset) = end;
620 if start_buffer.remote_id() == end_buffer.remote_id() {
621 (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
622 } else {
623 self.finish_inline_assist(inline_assist_id, false, cx);
624 return;
625 }
626 } else {
627 self.finish_inline_assist(inline_assist_id, false, cx);
628 return;
629 };
630
631 let language = buffer.language_at(range.start);
632 let language_name = if let Some(language) = language.as_ref() {
633 if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
634 None
635 } else {
636 Some(language.name())
637 }
638 } else {
639 None
640 };
641
642 // Higher Temperature increases the randomness of model outputs.
643 // If Markdown or No Language is Known, increase the randomness for more creative output
644 // If Code, decrease temperature to get more deterministic outputs
645 let temperature = if let Some(language) = language_name.clone() {
646 if language.to_string() != "Markdown".to_string() {
647 0.5
648 } else {
649 1.0
650 }
651 } else {
652 1.0
653 };
654
655 let user_prompt = user_prompt.to_string();
656
657 let snippets = if retrieve_context {
658 let Some(project) = project.upgrade() else {
659 return;
660 };
661
662 let search_results = if let Some(semantic_index) = self.semantic_index.clone() {
663 let search_results = semantic_index.update(cx, |this, cx| {
664 this.search_project(project, user_prompt.to_string(), 10, vec![], vec![], cx)
665 });
666
667 cx.background_executor()
668 .spawn(async move { search_results.await.unwrap_or_default() })
669 } else {
670 Task::ready(Vec::new())
671 };
672
673 let snippets = cx.spawn(|_, mut cx| async move {
674 let mut snippets = Vec::new();
675 for result in search_results.await {
676 snippets.push(PromptCodeSnippet::new(
677 result.buffer,
678 result.range,
679 &mut cx,
680 )?);
681 }
682 anyhow::Ok(snippets)
683 });
684 snippets
685 } else {
686 Task::ready(Ok(Vec::new()))
687 };
688
689 let mut model = AssistantSettings::get_global(cx)
690 .default_open_ai_model
691 .clone();
692 let model_name = model.full_name();
693
694 let prompt = cx.background_executor().spawn(async move {
695 let snippets = snippets.await?;
696
697 let language_name = language_name.as_deref();
698 generate_content_prompt(
699 user_prompt,
700 language_name,
701 buffer,
702 range,
703 snippets,
704 model_name,
705 project_name,
706 )
707 });
708
709 let mut messages = Vec::new();
710 if let Some(conversation) = conversation {
711 let conversation = conversation.read(cx);
712 let buffer = conversation.buffer.read(cx);
713 messages.extend(
714 conversation
715 .messages(cx)
716 .map(|message| message.to_open_ai_message(buffer)),
717 );
718 model = conversation.model.clone();
719 }
720
721 cx.spawn(|_, mut cx| async move {
722 // I Don't know if we want to return a ? here.
723 let prompt = prompt.await?;
724
725 messages.push(RequestMessage {
726 role: Role::User,
727 content: prompt,
728 });
729
730 let request = Box::new(OpenAIRequest {
731 model: model.full_name().into(),
732 messages,
733 stream: true,
734 stop: vec!["|END|>".to_string()],
735 temperature,
736 });
737
738 codegen.update(&mut cx, |codegen, cx| codegen.start(request, cx))?;
739 anyhow::Ok(())
740 })
741 .detach();
742 }
743
744 fn update_highlights_for_editor(&self, editor: &View<Editor>, cx: &mut ViewContext<Self>) {
745 let mut background_ranges = Vec::new();
746 let mut foreground_ranges = Vec::new();
747 let empty_inline_assist_ids = Vec::new();
748 let inline_assist_ids = self
749 .pending_inline_assist_ids_by_editor
750 .get(&editor.downgrade())
751 .unwrap_or(&empty_inline_assist_ids);
752
753 for inline_assist_id in inline_assist_ids {
754 if let Some(pending_assist) = self.pending_inline_assists.get(inline_assist_id) {
755 let codegen = pending_assist.codegen.read(cx);
756 background_ranges.push(codegen.range());
757 foreground_ranges.extend(codegen.last_equal_ranges().iter().cloned());
758 }
759 }
760
761 let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
762 merge_ranges(&mut background_ranges, &snapshot);
763 merge_ranges(&mut foreground_ranges, &snapshot);
764 editor.update(cx, |editor, cx| {
765 if background_ranges.is_empty() {
766 editor.clear_background_highlights::<PendingInlineAssist>(cx);
767 } else {
768 editor.highlight_background::<PendingInlineAssist>(
769 background_ranges,
770 |theme| theme.editor_active_line_background, // todo!("use the appropriate color")
771 cx,
772 );
773 }
774
775 if foreground_ranges.is_empty() {
776 editor.clear_highlights::<PendingInlineAssist>(cx);
777 } else {
778 editor.highlight_text::<PendingInlineAssist>(
779 foreground_ranges,
780 HighlightStyle {
781 fade_out: Some(0.6),
782 ..Default::default()
783 },
784 cx,
785 );
786 }
787 });
788 }
789
790 fn new_conversation(&mut self, cx: &mut ViewContext<Self>) -> View<ConversationEditor> {
791 let editor = cx.build_view(|cx| {
792 ConversationEditor::new(
793 self.completion_provider.clone(),
794 self.languages.clone(),
795 self.fs.clone(),
796 self.workspace.clone(),
797 cx,
798 )
799 });
800 self.add_conversation(editor.clone(), cx);
801 editor
802 }
803
804 fn add_conversation(&mut self, editor: View<ConversationEditor>, cx: &mut ViewContext<Self>) {
805 self.subscriptions
806 .push(cx.subscribe(&editor, Self::handle_conversation_editor_event));
807
808 let conversation = editor.read(cx).conversation.clone();
809 self.subscriptions
810 .push(cx.observe(&conversation, |_, _, cx| cx.notify()));
811
812 let index = self.editors.len();
813 self.editors.push(editor);
814 self.set_active_editor_index(Some(index), cx);
815 }
816
817 fn set_active_editor_index(&mut self, index: Option<usize>, cx: &mut ViewContext<Self>) {
818 self.prev_active_editor_index = self.active_editor_index;
819 self.active_editor_index = index;
820 if let Some(editor) = self.active_editor() {
821 let editor = editor.read(cx).editor.clone();
822 self.toolbar.update(cx, |toolbar, cx| {
823 toolbar.set_active_item(Some(&editor), cx);
824 });
825 if self.focus_handle.contains_focused(cx) {
826 cx.focus_view(&editor);
827 }
828 } else {
829 self.toolbar.update(cx, |toolbar, cx| {
830 toolbar.set_active_item(None, cx);
831 });
832 }
833
834 cx.notify();
835 }
836
837 fn handle_conversation_editor_event(
838 &mut self,
839 _: View<ConversationEditor>,
840 event: &ConversationEditorEvent,
841 cx: &mut ViewContext<Self>,
842 ) {
843 match event {
844 ConversationEditorEvent::TabContentChanged => cx.notify(),
845 }
846 }
847
848 fn save_credentials(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
849 if let Some(api_key) = self
850 .api_key_editor
851 .as_ref()
852 .map(|editor| editor.read(cx).text(cx))
853 {
854 if !api_key.is_empty() {
855 let credential = ProviderCredential::Credentials {
856 api_key: api_key.clone(),
857 };
858
859 self.completion_provider.save_credentials(cx, credential);
860
861 self.api_key_editor.take();
862 self.focus_handle.focus(cx);
863 cx.notify();
864 }
865 } else {
866 cx.propagate();
867 }
868 }
869
870 fn reset_credentials(&mut self, _: &ResetKey, cx: &mut ViewContext<Self>) {
871 self.completion_provider.delete_credentials(cx);
872 self.api_key_editor = Some(build_api_key_editor(cx));
873 self.focus_handle.focus(cx);
874 cx.notify();
875 }
876
877 fn toggle_zoom(&mut self, _: &workspace::ToggleZoom, cx: &mut ViewContext<Self>) {
878 if self.zoomed {
879 cx.emit(PanelEvent::ZoomOut)
880 } else {
881 cx.emit(PanelEvent::ZoomIn)
882 }
883 }
884
885 fn deploy(&mut self, action: &search::buffer_search::Deploy, cx: &mut ViewContext<Self>) {
886 let mut propagate = true;
887 if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
888 search_bar.update(cx, |search_bar, cx| {
889 if search_bar.show(cx) {
890 search_bar.search_suggested(cx);
891 if action.focus {
892 let focus_handle = search_bar.focus_handle(cx);
893 search_bar.select_query(cx);
894 cx.focus(&focus_handle);
895 }
896 propagate = false
897 }
898 });
899 }
900 if propagate {
901 cx.propagate();
902 }
903 }
904
905 fn handle_editor_cancel(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
906 if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
907 if !search_bar.read(cx).is_dismissed() {
908 search_bar.update(cx, |search_bar, cx| {
909 search_bar.dismiss(&Default::default(), cx)
910 });
911 return;
912 }
913 }
914 cx.propagate();
915 }
916
917 fn select_next_match(&mut self, _: &search::SelectNextMatch, cx: &mut ViewContext<Self>) {
918 if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
919 search_bar.update(cx, |bar, cx| bar.select_match(Direction::Next, 1, cx));
920 }
921 }
922
923 fn select_prev_match(&mut self, _: &search::SelectPrevMatch, cx: &mut ViewContext<Self>) {
924 if let Some(search_bar) = self.toolbar.read(cx).item_of_type::<BufferSearchBar>() {
925 search_bar.update(cx, |bar, cx| bar.select_match(Direction::Prev, 1, cx));
926 }
927 }
928
929 fn active_editor(&self) -> Option<&View<ConversationEditor>> {
930 self.editors.get(self.active_editor_index?)
931 }
932
933 fn render_hamburger_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
934 IconButton::new("hamburger_button", Icon::Menu)
935 .on_click(cx.listener(|this, _event, cx| {
936 if this.active_editor().is_some() {
937 this.set_active_editor_index(None, cx);
938 } else {
939 this.set_active_editor_index(this.prev_active_editor_index, cx);
940 }
941 }))
942 .tooltip(|cx| Tooltip::text("History", cx))
943 }
944
945 fn render_editor_tools(&self, cx: &mut ViewContext<Self>) -> Vec<AnyElement> {
946 if self.active_editor().is_some() {
947 vec![
948 Self::render_split_button(cx).into_any_element(),
949 Self::render_quote_button(cx).into_any_element(),
950 Self::render_assist_button(cx).into_any_element(),
951 ]
952 } else {
953 Default::default()
954 }
955 }
956
957 fn render_split_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
958 IconButton::new("split_button", Icon::SplitMessage)
959 .on_click(cx.listener(|this, _event, cx| {
960 if let Some(active_editor) = this.active_editor() {
961 active_editor.update(cx, |editor, cx| editor.split(&Default::default(), cx));
962 }
963 }))
964 .tooltip(|cx| Tooltip::for_action("Split Message", &Split, cx))
965 }
966
967 fn render_assist_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
968 IconButton::new("assist_button", Icon::MagicWand)
969 .on_click(cx.listener(|this, _event, cx| {
970 if let Some(active_editor) = this.active_editor() {
971 active_editor.update(cx, |editor, cx| editor.assist(&Default::default(), cx));
972 }
973 }))
974 .tooltip(|cx| Tooltip::for_action("Assist", &Assist, cx))
975 }
976
977 fn render_quote_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
978 IconButton::new("quote_button", Icon::Quote)
979 .on_click(cx.listener(|this, _event, cx| {
980 if let Some(workspace) = this.workspace.upgrade() {
981 cx.window_context().defer(move |cx| {
982 workspace.update(cx, |workspace, cx| {
983 ConversationEditor::quote_selection(workspace, &Default::default(), cx)
984 });
985 });
986 }
987 }))
988 .tooltip(|cx| Tooltip::for_action("Quote Seleciton", &QuoteSelection, cx))
989 }
990
991 fn render_plus_button(cx: &mut ViewContext<Self>) -> impl IntoElement {
992 IconButton::new("plus_button", Icon::Plus)
993 .on_click(cx.listener(|this, _event, cx| {
994 this.new_conversation(cx);
995 }))
996 .tooltip(|cx| Tooltip::for_action("New Conversation", &NewConversation, cx))
997 }
998
999 fn render_zoom_button(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1000 let zoomed = self.zoomed;
1001 IconButton::new("zoom_button", Icon::MagnifyingGlass)
1002 .on_click(cx.listener(|this, _event, cx| {
1003 this.toggle_zoom(&ToggleZoom, cx);
1004 }))
1005 .tooltip(move |cx| {
1006 Tooltip::for_action(if zoomed { "Zoom Out" } else { "Zoom In" }, &ToggleZoom, cx)
1007 })
1008 }
1009
1010 fn render_saved_conversation(
1011 &mut self,
1012 index: usize,
1013 cx: &mut ViewContext<Self>,
1014 ) -> impl IntoElement {
1015 let conversation = &self.saved_conversations[index];
1016 let path = conversation.path.clone();
1017
1018 ButtonLike::new(index)
1019 .on_click(cx.listener(move |this, _, cx| {
1020 this.open_conversation(path.clone(), cx)
1021 .detach_and_log_err(cx)
1022 }))
1023 .child(Label::new(
1024 conversation.mtime.format("%F %I:%M%p").to_string(),
1025 ))
1026 .child(Label::new(conversation.title.clone()))
1027 }
1028
1029 fn open_conversation(&mut self, path: PathBuf, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
1030 cx.focus(&self.focus_handle);
1031
1032 if let Some(ix) = self.editor_index_for_path(&path, cx) {
1033 self.set_active_editor_index(Some(ix), cx);
1034 return Task::ready(Ok(()));
1035 }
1036
1037 let fs = self.fs.clone();
1038 let workspace = self.workspace.clone();
1039 let languages = self.languages.clone();
1040 cx.spawn(|this, mut cx| async move {
1041 let saved_conversation = fs.load(&path).await?;
1042 let saved_conversation = serde_json::from_str(&saved_conversation)?;
1043 let conversation = cx.build_model(|cx| {
1044 Conversation::deserialize(saved_conversation, path.clone(), languages, cx)
1045 })?;
1046 this.update(&mut cx, |this, cx| {
1047 // If, by the time we've loaded the conversation, the user has already opened
1048 // the same conversation, we don't want to open it again.
1049 if let Some(ix) = this.editor_index_for_path(&path, cx) {
1050 this.set_active_editor_index(Some(ix), cx);
1051 } else {
1052 let editor = cx.build_view(|cx| {
1053 ConversationEditor::for_conversation(conversation, fs, workspace, cx)
1054 });
1055 this.add_conversation(editor, cx);
1056 }
1057 })?;
1058 Ok(())
1059 })
1060 }
1061
1062 fn editor_index_for_path(&self, path: &Path, cx: &AppContext) -> Option<usize> {
1063 self.editors
1064 .iter()
1065 .position(|editor| editor.read(cx).conversation.read(cx).path.as_deref() == Some(path))
1066 }
1067
1068 fn has_credentials(&mut self) -> bool {
1069 self.completion_provider.has_credentials()
1070 }
1071
1072 fn load_credentials(&mut self, cx: &mut ViewContext<Self>) {
1073 self.completion_provider.retrieve_credentials(cx);
1074 }
1075}
1076
1077fn build_api_key_editor(cx: &mut ViewContext<AssistantPanel>) -> View<Editor> {
1078 cx.build_view(|cx| {
1079 let mut editor = Editor::single_line(cx);
1080 editor.set_placeholder_text("sk-000000000000000000000000000000000000000000000000", cx);
1081 editor
1082 })
1083}
1084
1085impl Render for AssistantPanel {
1086 type Element = Focusable<Div>;
1087
1088 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1089 if let Some(api_key_editor) = self.api_key_editor.clone() {
1090 v_stack()
1091 .on_action(cx.listener(AssistantPanel::save_credentials))
1092 .track_focus(&self.focus_handle)
1093 .child(Label::new(
1094 "To use the assistant panel or inline assistant, you need to add your OpenAI api key.",
1095 ))
1096 .child(Label::new(
1097 " - Having a subscription for another service like GitHub Copilot won't work."
1098 ))
1099 .child(Label::new(
1100 " - You can create a api key at: platform.openai.com/api-keys"
1101 ))
1102 .child(Label::new(
1103 " "
1104 ))
1105 .child(Label::new(
1106 "Paste your OpenAI API key and press Enter to use the assistant"
1107 ))
1108 .child(api_key_editor)
1109 .child(Label::new(
1110 "Click on the Z button in the status bar to close this panel."
1111 ))
1112 .border()
1113 .border_color(gpui::red())
1114 } else {
1115 let title = self
1116 .active_editor()
1117 .map(|editor| Label::new(editor.read(cx).title(cx)));
1118
1119 let mut header = h_stack()
1120 .child(Self::render_hamburger_button(cx))
1121 .children(title);
1122
1123 if self.focus_handle.contains_focused(cx) {
1124 header = header
1125 .children(self.render_editor_tools(cx))
1126 .child(Self::render_plus_button(cx))
1127 .child(self.render_zoom_button(cx));
1128 }
1129
1130 v_stack()
1131 .size_full()
1132 .on_action(cx.listener(|this, _: &workspace::NewFile, cx| {
1133 this.new_conversation(cx);
1134 }))
1135 .on_action(cx.listener(AssistantPanel::reset_credentials))
1136 .on_action(cx.listener(AssistantPanel::toggle_zoom))
1137 .on_action(cx.listener(AssistantPanel::deploy))
1138 .on_action(cx.listener(AssistantPanel::select_next_match))
1139 .on_action(cx.listener(AssistantPanel::select_prev_match))
1140 .on_action(cx.listener(AssistantPanel::handle_editor_cancel))
1141 .track_focus(&self.focus_handle)
1142 .child(header)
1143 .children(if self.toolbar.read(cx).hidden() {
1144 None
1145 } else {
1146 Some(self.toolbar.clone())
1147 })
1148 .child(
1149 div()
1150 .flex_1()
1151 .child(if let Some(editor) = self.active_editor() {
1152 editor.clone().into_any_element()
1153 } else {
1154 uniform_list(
1155 cx.view().clone(),
1156 "saved_conversations",
1157 self.saved_conversations.len(),
1158 |this, range, cx| {
1159 range
1160 .map(|ix| this.render_saved_conversation(ix, cx))
1161 .collect()
1162 },
1163 )
1164 .track_scroll(self.saved_conversations_scroll_handle.clone())
1165 .into_any_element()
1166 }),
1167 )
1168 .border()
1169 .border_color(gpui::red())
1170 }
1171 }
1172}
1173
1174impl Panel for AssistantPanel {
1175 fn persistent_name() -> &'static str {
1176 "AssistantPanel"
1177 }
1178
1179 fn position(&self, cx: &WindowContext) -> DockPosition {
1180 match AssistantSettings::get_global(cx).dock {
1181 AssistantDockPosition::Left => DockPosition::Left,
1182 AssistantDockPosition::Bottom => DockPosition::Bottom,
1183 AssistantDockPosition::Right => DockPosition::Right,
1184 }
1185 }
1186
1187 fn position_is_valid(&self, _: DockPosition) -> bool {
1188 true
1189 }
1190
1191 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1192 settings::update_settings_file::<AssistantSettings>(self.fs.clone(), cx, move |settings| {
1193 let dock = match position {
1194 DockPosition::Left => AssistantDockPosition::Left,
1195 DockPosition::Bottom => AssistantDockPosition::Bottom,
1196 DockPosition::Right => AssistantDockPosition::Right,
1197 };
1198 settings.dock = Some(dock);
1199 });
1200 }
1201
1202 fn size(&self, cx: &WindowContext) -> f32 {
1203 let settings = AssistantSettings::get_global(cx);
1204 match self.position(cx) {
1205 DockPosition::Left | DockPosition::Right => {
1206 self.width.unwrap_or_else(|| settings.default_width)
1207 }
1208 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
1209 }
1210 }
1211
1212 fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
1213 match self.position(cx) {
1214 DockPosition::Left | DockPosition::Right => self.width = size,
1215 DockPosition::Bottom => self.height = size,
1216 }
1217 cx.notify();
1218 }
1219
1220 fn is_zoomed(&self, _: &WindowContext) -> bool {
1221 self.zoomed
1222 }
1223
1224 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1225 self.zoomed = zoomed;
1226 cx.notify();
1227 }
1228
1229 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1230 if active {
1231 self.load_credentials(cx);
1232
1233 if self.editors.is_empty() {
1234 self.new_conversation(cx);
1235 }
1236 }
1237 }
1238
1239 fn icon(&self, _cx: &WindowContext) -> Option<Icon> {
1240 Some(Icon::Ai)
1241 }
1242
1243 fn toggle_action(&self) -> Box<dyn Action> {
1244 Box::new(ToggleFocus)
1245 }
1246}
1247
1248impl EventEmitter<PanelEvent> for AssistantPanel {}
1249
1250impl FocusableView for AssistantPanel {
1251 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1252 self.focus_handle.clone()
1253 }
1254}
1255
1256enum ConversationEvent {
1257 MessagesEdited,
1258 SummaryChanged,
1259 StreamedCompletion,
1260}
1261
1262#[derive(Default)]
1263struct Summary {
1264 text: String,
1265 done: bool,
1266}
1267
1268struct Conversation {
1269 id: Option<String>,
1270 buffer: Model<Buffer>,
1271 message_anchors: Vec<MessageAnchor>,
1272 messages_metadata: HashMap<MessageId, MessageMetadata>,
1273 next_message_id: MessageId,
1274 summary: Option<Summary>,
1275 pending_summary: Task<Option<()>>,
1276 completion_count: usize,
1277 pending_completions: Vec<PendingCompletion>,
1278 model: OpenAIModel,
1279 token_count: Option<usize>,
1280 max_token_count: usize,
1281 pending_token_count: Task<Option<()>>,
1282 pending_save: Task<Result<()>>,
1283 path: Option<PathBuf>,
1284 _subscriptions: Vec<Subscription>,
1285 completion_provider: Arc<dyn CompletionProvider>,
1286}
1287
1288impl EventEmitter<ConversationEvent> for Conversation {}
1289
1290impl Conversation {
1291 fn new(
1292 language_registry: Arc<LanguageRegistry>,
1293 cx: &mut ModelContext<Self>,
1294 completion_provider: Arc<dyn CompletionProvider>,
1295 ) -> Self {
1296 let markdown = language_registry.language_for_name("Markdown");
1297 let buffer = cx.build_model(|cx| {
1298 let mut buffer = Buffer::new(0, cx.entity_id().as_u64(), "");
1299 buffer.set_language_registry(language_registry);
1300 cx.spawn(|buffer, mut cx| async move {
1301 let markdown = markdown.await?;
1302 buffer.update(&mut cx, |buffer: &mut Buffer, cx| {
1303 buffer.set_language(Some(markdown), cx)
1304 })?;
1305 anyhow::Ok(())
1306 })
1307 .detach_and_log_err(cx);
1308 buffer
1309 });
1310
1311 let settings = AssistantSettings::get_global(cx);
1312 let model = settings.default_open_ai_model.clone();
1313
1314 let mut this = Self {
1315 id: Some(Uuid::new_v4().to_string()),
1316 message_anchors: Default::default(),
1317 messages_metadata: Default::default(),
1318 next_message_id: Default::default(),
1319 summary: None,
1320 pending_summary: Task::ready(None),
1321 completion_count: Default::default(),
1322 pending_completions: Default::default(),
1323 token_count: None,
1324 max_token_count: tiktoken_rs::model::get_context_size(&model.full_name()),
1325 pending_token_count: Task::ready(None),
1326 model: model.clone(),
1327 _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
1328 pending_save: Task::ready(Ok(())),
1329 path: None,
1330 buffer,
1331 completion_provider,
1332 };
1333 let message = MessageAnchor {
1334 id: MessageId(post_inc(&mut this.next_message_id.0)),
1335 start: language::Anchor::MIN,
1336 };
1337 this.message_anchors.push(message.clone());
1338 this.messages_metadata.insert(
1339 message.id,
1340 MessageMetadata {
1341 role: Role::User,
1342 sent_at: Local::now(),
1343 status: MessageStatus::Done,
1344 },
1345 );
1346
1347 this.count_remaining_tokens(cx);
1348 this
1349 }
1350
1351 fn serialize(&self, cx: &AppContext) -> SavedConversation {
1352 SavedConversation {
1353 id: self.id.clone(),
1354 zed: "conversation".into(),
1355 version: SavedConversation::VERSION.into(),
1356 text: self.buffer.read(cx).text(),
1357 message_metadata: self.messages_metadata.clone(),
1358 messages: self
1359 .messages(cx)
1360 .map(|message| SavedMessage {
1361 id: message.id,
1362 start: message.offset_range.start,
1363 })
1364 .collect(),
1365 summary: self
1366 .summary
1367 .as_ref()
1368 .map(|summary| summary.text.clone())
1369 .unwrap_or_default(),
1370 model: self.model.clone(),
1371 }
1372 }
1373
1374 fn deserialize(
1375 saved_conversation: SavedConversation,
1376 path: PathBuf,
1377 language_registry: Arc<LanguageRegistry>,
1378 cx: &mut ModelContext<Self>,
1379 ) -> Self {
1380 let id = match saved_conversation.id {
1381 Some(id) => Some(id),
1382 None => Some(Uuid::new_v4().to_string()),
1383 };
1384 let model = saved_conversation.model;
1385 let completion_provider: Arc<dyn CompletionProvider> = Arc::new(
1386 OpenAICompletionProvider::new(model.full_name(), cx.background_executor().clone()),
1387 );
1388 completion_provider.retrieve_credentials(cx);
1389 let markdown = language_registry.language_for_name("Markdown");
1390 let mut message_anchors = Vec::new();
1391 let mut next_message_id = MessageId(0);
1392 let buffer = cx.build_model(|cx| {
1393 let mut buffer = Buffer::new(0, cx.entity_id().as_u64(), saved_conversation.text);
1394 for message in saved_conversation.messages {
1395 message_anchors.push(MessageAnchor {
1396 id: message.id,
1397 start: buffer.anchor_before(message.start),
1398 });
1399 next_message_id = cmp::max(next_message_id, MessageId(message.id.0 + 1));
1400 }
1401 buffer.set_language_registry(language_registry);
1402 cx.spawn(|buffer, mut cx| async move {
1403 let markdown = markdown.await?;
1404 buffer.update(&mut cx, |buffer: &mut Buffer, cx| {
1405 buffer.set_language(Some(markdown), cx)
1406 })?;
1407 anyhow::Ok(())
1408 })
1409 .detach_and_log_err(cx);
1410 buffer
1411 });
1412
1413 let mut this = Self {
1414 id,
1415 message_anchors,
1416 messages_metadata: saved_conversation.message_metadata,
1417 next_message_id,
1418 summary: Some(Summary {
1419 text: saved_conversation.summary,
1420 done: true,
1421 }),
1422 pending_summary: Task::ready(None),
1423 completion_count: Default::default(),
1424 pending_completions: Default::default(),
1425 token_count: None,
1426 max_token_count: tiktoken_rs::model::get_context_size(&model.full_name()),
1427 pending_token_count: Task::ready(None),
1428 model,
1429 _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)],
1430 pending_save: Task::ready(Ok(())),
1431 path: Some(path),
1432 buffer,
1433 completion_provider,
1434 };
1435 this.count_remaining_tokens(cx);
1436 this
1437 }
1438
1439 fn handle_buffer_event(
1440 &mut self,
1441 _: Model<Buffer>,
1442 event: &language::Event,
1443 cx: &mut ModelContext<Self>,
1444 ) {
1445 match event {
1446 language::Event::Edited => {
1447 self.count_remaining_tokens(cx);
1448 cx.emit(ConversationEvent::MessagesEdited);
1449 }
1450 _ => {}
1451 }
1452 }
1453
1454 fn count_remaining_tokens(&mut self, cx: &mut ModelContext<Self>) {
1455 let messages = self
1456 .messages(cx)
1457 .into_iter()
1458 .filter_map(|message| {
1459 Some(tiktoken_rs::ChatCompletionRequestMessage {
1460 role: match message.role {
1461 Role::User => "user".into(),
1462 Role::Assistant => "assistant".into(),
1463 Role::System => "system".into(),
1464 },
1465 content: Some(
1466 self.buffer
1467 .read(cx)
1468 .text_for_range(message.offset_range)
1469 .collect(),
1470 ),
1471 name: None,
1472 function_call: None,
1473 })
1474 })
1475 .collect::<Vec<_>>();
1476 let model = self.model.clone();
1477 self.pending_token_count = cx.spawn(|this, mut cx| {
1478 async move {
1479 cx.background_executor()
1480 .timer(Duration::from_millis(200))
1481 .await;
1482 let token_count = cx
1483 .background_executor()
1484 .spawn(async move {
1485 tiktoken_rs::num_tokens_from_messages(&model.full_name(), &messages)
1486 })
1487 .await?;
1488
1489 this.update(&mut cx, |this, cx| {
1490 this.max_token_count =
1491 tiktoken_rs::model::get_context_size(&this.model.full_name());
1492 this.token_count = Some(token_count);
1493 cx.notify()
1494 })?;
1495 anyhow::Ok(())
1496 }
1497 .log_err()
1498 });
1499 }
1500
1501 fn remaining_tokens(&self) -> Option<isize> {
1502 Some(self.max_token_count as isize - self.token_count? as isize)
1503 }
1504
1505 fn set_model(&mut self, model: OpenAIModel, cx: &mut ModelContext<Self>) {
1506 self.model = model;
1507 self.count_remaining_tokens(cx);
1508 cx.notify();
1509 }
1510
1511 fn assist(
1512 &mut self,
1513 selected_messages: HashSet<MessageId>,
1514 cx: &mut ModelContext<Self>,
1515 ) -> Vec<MessageAnchor> {
1516 let mut user_messages = Vec::new();
1517
1518 let last_message_id = if let Some(last_message_id) =
1519 self.message_anchors.iter().rev().find_map(|message| {
1520 message
1521 .start
1522 .is_valid(self.buffer.read(cx))
1523 .then_some(message.id)
1524 }) {
1525 last_message_id
1526 } else {
1527 return Default::default();
1528 };
1529
1530 let mut should_assist = false;
1531 for selected_message_id in selected_messages {
1532 let selected_message_role =
1533 if let Some(metadata) = self.messages_metadata.get(&selected_message_id) {
1534 metadata.role
1535 } else {
1536 continue;
1537 };
1538
1539 if selected_message_role == Role::Assistant {
1540 if let Some(user_message) = self.insert_message_after(
1541 selected_message_id,
1542 Role::User,
1543 MessageStatus::Done,
1544 cx,
1545 ) {
1546 user_messages.push(user_message);
1547 }
1548 } else {
1549 should_assist = true;
1550 }
1551 }
1552
1553 if should_assist {
1554 if !self.completion_provider.has_credentials() {
1555 return Default::default();
1556 }
1557
1558 let request: Box<dyn CompletionRequest> = Box::new(OpenAIRequest {
1559 model: self.model.full_name().to_string(),
1560 messages: self
1561 .messages(cx)
1562 .filter(|message| matches!(message.status, MessageStatus::Done))
1563 .map(|message| message.to_open_ai_message(self.buffer.read(cx)))
1564 .collect(),
1565 stream: true,
1566 stop: vec![],
1567 temperature: 1.0,
1568 });
1569
1570 let stream = self.completion_provider.complete(request);
1571 let assistant_message = self
1572 .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
1573 .unwrap();
1574
1575 // Queue up the user's next reply.
1576 let user_message = self
1577 .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
1578 .unwrap();
1579 user_messages.push(user_message);
1580
1581 let task = cx.spawn({
1582 |this, mut cx| async move {
1583 let assistant_message_id = assistant_message.id;
1584 let stream_completion = async {
1585 let mut messages = stream.await?;
1586
1587 while let Some(message) = messages.next().await {
1588 let text = message?;
1589
1590 this.update(&mut cx, |this, cx| {
1591 let message_ix = this
1592 .message_anchors
1593 .iter()
1594 .position(|message| message.id == assistant_message_id)?;
1595 this.buffer.update(cx, |buffer, cx| {
1596 let offset = this.message_anchors[message_ix + 1..]
1597 .iter()
1598 .find(|message| message.start.is_valid(buffer))
1599 .map_or(buffer.len(), |message| {
1600 message.start.to_offset(buffer).saturating_sub(1)
1601 });
1602 buffer.edit([(offset..offset, text)], None, cx);
1603 });
1604 cx.emit(ConversationEvent::StreamedCompletion);
1605
1606 Some(())
1607 })?;
1608 smol::future::yield_now().await;
1609 }
1610
1611 this.update(&mut cx, |this, cx| {
1612 this.pending_completions
1613 .retain(|completion| completion.id != this.completion_count);
1614 this.summarize(cx);
1615 })?;
1616
1617 anyhow::Ok(())
1618 };
1619
1620 let result = stream_completion.await;
1621
1622 this.update(&mut cx, |this, cx| {
1623 if let Some(metadata) =
1624 this.messages_metadata.get_mut(&assistant_message.id)
1625 {
1626 match result {
1627 Ok(_) => {
1628 metadata.status = MessageStatus::Done;
1629 }
1630 Err(error) => {
1631 metadata.status =
1632 MessageStatus::Error(error.to_string().trim().into());
1633 }
1634 }
1635 cx.notify();
1636 }
1637 })
1638 .ok();
1639 }
1640 });
1641
1642 self.pending_completions.push(PendingCompletion {
1643 id: post_inc(&mut self.completion_count),
1644 _task: task,
1645 });
1646 }
1647
1648 user_messages
1649 }
1650
1651 fn cancel_last_assist(&mut self) -> bool {
1652 self.pending_completions.pop().is_some()
1653 }
1654
1655 fn cycle_message_roles(&mut self, ids: HashSet<MessageId>, cx: &mut ModelContext<Self>) {
1656 for id in ids {
1657 if let Some(metadata) = self.messages_metadata.get_mut(&id) {
1658 metadata.role.cycle();
1659 cx.emit(ConversationEvent::MessagesEdited);
1660 cx.notify();
1661 }
1662 }
1663 }
1664
1665 fn insert_message_after(
1666 &mut self,
1667 message_id: MessageId,
1668 role: Role,
1669 status: MessageStatus,
1670 cx: &mut ModelContext<Self>,
1671 ) -> Option<MessageAnchor> {
1672 if let Some(prev_message_ix) = self
1673 .message_anchors
1674 .iter()
1675 .position(|message| message.id == message_id)
1676 {
1677 // Find the next valid message after the one we were given.
1678 let mut next_message_ix = prev_message_ix + 1;
1679 while let Some(next_message) = self.message_anchors.get(next_message_ix) {
1680 if next_message.start.is_valid(self.buffer.read(cx)) {
1681 break;
1682 }
1683 next_message_ix += 1;
1684 }
1685
1686 let start = self.buffer.update(cx, |buffer, cx| {
1687 let offset = self
1688 .message_anchors
1689 .get(next_message_ix)
1690 .map_or(buffer.len(), |message| message.start.to_offset(buffer) - 1);
1691 buffer.edit([(offset..offset, "\n")], None, cx);
1692 buffer.anchor_before(offset + 1)
1693 });
1694 let message = MessageAnchor {
1695 id: MessageId(post_inc(&mut self.next_message_id.0)),
1696 start,
1697 };
1698 self.message_anchors
1699 .insert(next_message_ix, message.clone());
1700 self.messages_metadata.insert(
1701 message.id,
1702 MessageMetadata {
1703 role,
1704 sent_at: Local::now(),
1705 status,
1706 },
1707 );
1708 cx.emit(ConversationEvent::MessagesEdited);
1709 Some(message)
1710 } else {
1711 None
1712 }
1713 }
1714
1715 fn split_message(
1716 &mut self,
1717 range: Range<usize>,
1718 cx: &mut ModelContext<Self>,
1719 ) -> (Option<MessageAnchor>, Option<MessageAnchor>) {
1720 let start_message = self.message_for_offset(range.start, cx);
1721 let end_message = self.message_for_offset(range.end, cx);
1722 if let Some((start_message, end_message)) = start_message.zip(end_message) {
1723 // Prevent splitting when range spans multiple messages.
1724 if start_message.id != end_message.id {
1725 return (None, None);
1726 }
1727
1728 let message = start_message;
1729 let role = message.role;
1730 let mut edited_buffer = false;
1731
1732 let mut suffix_start = None;
1733 if range.start > message.offset_range.start && range.end < message.offset_range.end - 1
1734 {
1735 if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') {
1736 suffix_start = Some(range.end + 1);
1737 } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') {
1738 suffix_start = Some(range.end);
1739 }
1740 }
1741
1742 let suffix = if let Some(suffix_start) = suffix_start {
1743 MessageAnchor {
1744 id: MessageId(post_inc(&mut self.next_message_id.0)),
1745 start: self.buffer.read(cx).anchor_before(suffix_start),
1746 }
1747 } else {
1748 self.buffer.update(cx, |buffer, cx| {
1749 buffer.edit([(range.end..range.end, "\n")], None, cx);
1750 });
1751 edited_buffer = true;
1752 MessageAnchor {
1753 id: MessageId(post_inc(&mut self.next_message_id.0)),
1754 start: self.buffer.read(cx).anchor_before(range.end + 1),
1755 }
1756 };
1757
1758 self.message_anchors
1759 .insert(message.index_range.end + 1, suffix.clone());
1760 self.messages_metadata.insert(
1761 suffix.id,
1762 MessageMetadata {
1763 role,
1764 sent_at: Local::now(),
1765 status: MessageStatus::Done,
1766 },
1767 );
1768
1769 let new_messages =
1770 if range.start == range.end || range.start == message.offset_range.start {
1771 (None, Some(suffix))
1772 } else {
1773 let mut prefix_end = None;
1774 if range.start > message.offset_range.start
1775 && range.end < message.offset_range.end - 1
1776 {
1777 if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') {
1778 prefix_end = Some(range.start + 1);
1779 } else if self.buffer.read(cx).reversed_chars_at(range.start).next()
1780 == Some('\n')
1781 {
1782 prefix_end = Some(range.start);
1783 }
1784 }
1785
1786 let selection = if let Some(prefix_end) = prefix_end {
1787 cx.emit(ConversationEvent::MessagesEdited);
1788 MessageAnchor {
1789 id: MessageId(post_inc(&mut self.next_message_id.0)),
1790 start: self.buffer.read(cx).anchor_before(prefix_end),
1791 }
1792 } else {
1793 self.buffer.update(cx, |buffer, cx| {
1794 buffer.edit([(range.start..range.start, "\n")], None, cx)
1795 });
1796 edited_buffer = true;
1797 MessageAnchor {
1798 id: MessageId(post_inc(&mut self.next_message_id.0)),
1799 start: self.buffer.read(cx).anchor_before(range.end + 1),
1800 }
1801 };
1802
1803 self.message_anchors
1804 .insert(message.index_range.end + 1, selection.clone());
1805 self.messages_metadata.insert(
1806 selection.id,
1807 MessageMetadata {
1808 role,
1809 sent_at: Local::now(),
1810 status: MessageStatus::Done,
1811 },
1812 );
1813 (Some(selection), Some(suffix))
1814 };
1815
1816 if !edited_buffer {
1817 cx.emit(ConversationEvent::MessagesEdited);
1818 }
1819 new_messages
1820 } else {
1821 (None, None)
1822 }
1823 }
1824
1825 fn summarize(&mut self, cx: &mut ModelContext<Self>) {
1826 if self.message_anchors.len() >= 2 && self.summary.is_none() {
1827 if !self.completion_provider.has_credentials() {
1828 return;
1829 }
1830
1831 let messages = self
1832 .messages(cx)
1833 .take(2)
1834 .map(|message| message.to_open_ai_message(self.buffer.read(cx)))
1835 .chain(Some(RequestMessage {
1836 role: Role::User,
1837 content: "Summarize the conversation into a short title without punctuation"
1838 .into(),
1839 }));
1840 let request: Box<dyn CompletionRequest> = Box::new(OpenAIRequest {
1841 model: self.model.full_name().to_string(),
1842 messages: messages.collect(),
1843 stream: true,
1844 stop: vec![],
1845 temperature: 1.0,
1846 });
1847
1848 let stream = self.completion_provider.complete(request);
1849 self.pending_summary = cx.spawn(|this, mut cx| {
1850 async move {
1851 let mut messages = stream.await?;
1852
1853 while let Some(message) = messages.next().await {
1854 let text = message?;
1855 this.update(&mut cx, |this, cx| {
1856 this.summary
1857 .get_or_insert(Default::default())
1858 .text
1859 .push_str(&text);
1860 cx.emit(ConversationEvent::SummaryChanged);
1861 })?;
1862 }
1863
1864 this.update(&mut cx, |this, cx| {
1865 if let Some(summary) = this.summary.as_mut() {
1866 summary.done = true;
1867 cx.emit(ConversationEvent::SummaryChanged);
1868 }
1869 })?;
1870
1871 anyhow::Ok(())
1872 }
1873 .log_err()
1874 });
1875 }
1876 }
1877
1878 fn message_for_offset(&self, offset: usize, cx: &AppContext) -> Option<Message> {
1879 self.messages_for_offsets([offset], cx).pop()
1880 }
1881
1882 fn messages_for_offsets(
1883 &self,
1884 offsets: impl IntoIterator<Item = usize>,
1885 cx: &AppContext,
1886 ) -> Vec<Message> {
1887 let mut result = Vec::new();
1888
1889 let mut messages = self.messages(cx).peekable();
1890 let mut offsets = offsets.into_iter().peekable();
1891 let mut current_message = messages.next();
1892 while let Some(offset) = offsets.next() {
1893 // Locate the message that contains the offset.
1894 while current_message.as_ref().map_or(false, |message| {
1895 !message.offset_range.contains(&offset) && messages.peek().is_some()
1896 }) {
1897 current_message = messages.next();
1898 }
1899 let Some(message) = current_message.as_ref() else {
1900 break;
1901 };
1902
1903 // Skip offsets that are in the same message.
1904 while offsets.peek().map_or(false, |offset| {
1905 message.offset_range.contains(offset) || messages.peek().is_none()
1906 }) {
1907 offsets.next();
1908 }
1909
1910 result.push(message.clone());
1911 }
1912 result
1913 }
1914
1915 fn messages<'a>(&'a self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Message> {
1916 let buffer = self.buffer.read(cx);
1917 let mut message_anchors = self.message_anchors.iter().enumerate().peekable();
1918 iter::from_fn(move || {
1919 while let Some((start_ix, message_anchor)) = message_anchors.next() {
1920 let metadata = self.messages_metadata.get(&message_anchor.id)?;
1921 let message_start = message_anchor.start.to_offset(buffer);
1922 let mut message_end = None;
1923 let mut end_ix = start_ix;
1924 while let Some((_, next_message)) = message_anchors.peek() {
1925 if next_message.start.is_valid(buffer) {
1926 message_end = Some(next_message.start);
1927 break;
1928 } else {
1929 end_ix += 1;
1930 message_anchors.next();
1931 }
1932 }
1933 let message_end = message_end
1934 .unwrap_or(language::Anchor::MAX)
1935 .to_offset(buffer);
1936 return Some(Message {
1937 index_range: start_ix..end_ix,
1938 offset_range: message_start..message_end,
1939 id: message_anchor.id,
1940 anchor: message_anchor.start,
1941 role: metadata.role,
1942 sent_at: metadata.sent_at,
1943 status: metadata.status.clone(),
1944 });
1945 }
1946 None
1947 })
1948 }
1949
1950 fn save(
1951 &mut self,
1952 debounce: Option<Duration>,
1953 fs: Arc<dyn Fs>,
1954 cx: &mut ModelContext<Conversation>,
1955 ) {
1956 self.pending_save = cx.spawn(|this, mut cx| async move {
1957 if let Some(debounce) = debounce {
1958 cx.background_executor().timer(debounce).await;
1959 }
1960
1961 let (old_path, summary) = this.read_with(&cx, |this, _| {
1962 let path = this.path.clone();
1963 let summary = if let Some(summary) = this.summary.as_ref() {
1964 if summary.done {
1965 Some(summary.text.clone())
1966 } else {
1967 None
1968 }
1969 } else {
1970 None
1971 };
1972 (path, summary)
1973 })?;
1974
1975 if let Some(summary) = summary {
1976 let conversation = this.read_with(&cx, |this, cx| this.serialize(cx))?;
1977 let path = if let Some(old_path) = old_path {
1978 old_path
1979 } else {
1980 let mut discriminant = 1;
1981 let mut new_path;
1982 loop {
1983 new_path = CONVERSATIONS_DIR.join(&format!(
1984 "{} - {}.zed.json",
1985 summary.trim(),
1986 discriminant
1987 ));
1988 if fs.is_file(&new_path).await {
1989 discriminant += 1;
1990 } else {
1991 break;
1992 }
1993 }
1994 new_path
1995 };
1996
1997 fs.create_dir(CONVERSATIONS_DIR.as_ref()).await?;
1998 fs.atomic_write(path.clone(), serde_json::to_string(&conversation).unwrap())
1999 .await?;
2000 this.update(&mut cx, |this, _| this.path = Some(path))?;
2001 }
2002
2003 Ok(())
2004 });
2005 }
2006}
2007
2008struct PendingCompletion {
2009 id: usize,
2010 _task: Task<()>,
2011}
2012
2013enum ConversationEditorEvent {
2014 TabContentChanged,
2015}
2016
2017#[derive(Copy, Clone, Debug, PartialEq)]
2018struct ScrollPosition {
2019 offset_before_cursor: gpui::Point<f32>,
2020 cursor: Anchor,
2021}
2022
2023struct ConversationEditor {
2024 conversation: Model<Conversation>,
2025 fs: Arc<dyn Fs>,
2026 workspace: WeakView<Workspace>,
2027 editor: View<Editor>,
2028 blocks: HashSet<BlockId>,
2029 scroll_position: Option<ScrollPosition>,
2030 _subscriptions: Vec<Subscription>,
2031}
2032
2033impl ConversationEditor {
2034 fn new(
2035 completion_provider: Arc<dyn CompletionProvider>,
2036 language_registry: Arc<LanguageRegistry>,
2037 fs: Arc<dyn Fs>,
2038 workspace: WeakView<Workspace>,
2039 cx: &mut ViewContext<Self>,
2040 ) -> Self {
2041 let conversation =
2042 cx.build_model(|cx| Conversation::new(language_registry, cx, completion_provider));
2043 Self::for_conversation(conversation, fs, workspace, cx)
2044 }
2045
2046 fn for_conversation(
2047 conversation: Model<Conversation>,
2048 fs: Arc<dyn Fs>,
2049 workspace: WeakView<Workspace>,
2050 cx: &mut ViewContext<Self>,
2051 ) -> Self {
2052 let editor = cx.build_view(|cx| {
2053 let mut editor = Editor::for_buffer(conversation.read(cx).buffer.clone(), None, cx);
2054 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
2055 editor.set_show_gutter(false, cx);
2056 editor.set_show_wrap_guides(false, cx);
2057 editor
2058 });
2059
2060 let _subscriptions = vec![
2061 cx.observe(&conversation, |_, _, cx| cx.notify()),
2062 cx.subscribe(&conversation, Self::handle_conversation_event),
2063 cx.subscribe(&editor, Self::handle_editor_event),
2064 ];
2065
2066 let mut this = Self {
2067 conversation,
2068 editor,
2069 blocks: Default::default(),
2070 scroll_position: None,
2071 fs,
2072 workspace,
2073 _subscriptions,
2074 };
2075 this.update_message_headers(cx);
2076 this
2077 }
2078
2079 fn assist(&mut self, _: &Assist, cx: &mut ViewContext<Self>) {
2080 report_assistant_event(
2081 self.workspace.clone(),
2082 self.conversation.read(cx).id.clone(),
2083 AssistantKind::Panel,
2084 cx,
2085 );
2086
2087 let cursors = self.cursors(cx);
2088
2089 let user_messages = self.conversation.update(cx, |conversation, cx| {
2090 let selected_messages = conversation
2091 .messages_for_offsets(cursors, cx)
2092 .into_iter()
2093 .map(|message| message.id)
2094 .collect();
2095 conversation.assist(selected_messages, cx)
2096 });
2097 let new_selections = user_messages
2098 .iter()
2099 .map(|message| {
2100 let cursor = message
2101 .start
2102 .to_offset(self.conversation.read(cx).buffer.read(cx));
2103 cursor..cursor
2104 })
2105 .collect::<Vec<_>>();
2106 if !new_selections.is_empty() {
2107 self.editor.update(cx, |editor, cx| {
2108 editor.change_selections(
2109 Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
2110 cx,
2111 |selections| selections.select_ranges(new_selections),
2112 );
2113 });
2114 // Avoid scrolling to the new cursor position so the assistant's output is stable.
2115 cx.defer(|this, _| this.scroll_position = None);
2116 }
2117 }
2118
2119 fn cancel_last_assist(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
2120 if !self
2121 .conversation
2122 .update(cx, |conversation, _| conversation.cancel_last_assist())
2123 {
2124 cx.propagate();
2125 }
2126 }
2127
2128 fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext<Self>) {
2129 let cursors = self.cursors(cx);
2130 self.conversation.update(cx, |conversation, cx| {
2131 let messages = conversation
2132 .messages_for_offsets(cursors, cx)
2133 .into_iter()
2134 .map(|message| message.id)
2135 .collect();
2136 conversation.cycle_message_roles(messages, cx)
2137 });
2138 }
2139
2140 fn cursors(&self, cx: &AppContext) -> Vec<usize> {
2141 let selections = self.editor.read(cx).selections.all::<usize>(cx);
2142 selections
2143 .into_iter()
2144 .map(|selection| selection.head())
2145 .collect()
2146 }
2147
2148 fn handle_conversation_event(
2149 &mut self,
2150 _: Model<Conversation>,
2151 event: &ConversationEvent,
2152 cx: &mut ViewContext<Self>,
2153 ) {
2154 match event {
2155 ConversationEvent::MessagesEdited => {
2156 self.update_message_headers(cx);
2157 self.conversation.update(cx, |conversation, cx| {
2158 conversation.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
2159 });
2160 }
2161 ConversationEvent::SummaryChanged => {
2162 cx.emit(ConversationEditorEvent::TabContentChanged);
2163 self.conversation.update(cx, |conversation, cx| {
2164 conversation.save(None, self.fs.clone(), cx);
2165 });
2166 }
2167 ConversationEvent::StreamedCompletion => {
2168 self.editor.update(cx, |editor, cx| {
2169 if let Some(scroll_position) = self.scroll_position {
2170 let snapshot = editor.snapshot(cx);
2171 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
2172 let scroll_top =
2173 cursor_point.row() as f32 - scroll_position.offset_before_cursor.y;
2174 editor.set_scroll_position(
2175 point(scroll_position.offset_before_cursor.x, scroll_top),
2176 cx,
2177 );
2178 }
2179 });
2180 }
2181 }
2182 }
2183
2184 fn handle_editor_event(
2185 &mut self,
2186 _: View<Editor>,
2187 event: &EditorEvent,
2188 cx: &mut ViewContext<Self>,
2189 ) {
2190 match event {
2191 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
2192 let cursor_scroll_position = self.cursor_scroll_position(cx);
2193 if *autoscroll {
2194 self.scroll_position = cursor_scroll_position;
2195 } else if self.scroll_position != cursor_scroll_position {
2196 self.scroll_position = None;
2197 }
2198 }
2199 EditorEvent::SelectionsChanged { .. } => {
2200 self.scroll_position = self.cursor_scroll_position(cx);
2201 }
2202 _ => {}
2203 }
2204 }
2205
2206 fn cursor_scroll_position(&self, cx: &mut ViewContext<Self>) -> Option<ScrollPosition> {
2207 self.editor.update(cx, |editor, cx| {
2208 let snapshot = editor.snapshot(cx);
2209 let cursor = editor.selections.newest_anchor().head();
2210 let cursor_row = cursor.to_display_point(&snapshot.display_snapshot).row() as f32;
2211 let scroll_position = editor
2212 .scroll_manager
2213 .anchor()
2214 .scroll_position(&snapshot.display_snapshot);
2215
2216 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
2217 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
2218 Some(ScrollPosition {
2219 cursor,
2220 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
2221 })
2222 } else {
2223 None
2224 }
2225 })
2226 }
2227
2228 fn update_message_headers(&mut self, cx: &mut ViewContext<Self>) {
2229 self.editor.update(cx, |editor, cx| {
2230 let buffer = editor.buffer().read(cx).snapshot(cx);
2231 let excerpt_id = *buffer.as_singleton().unwrap().0;
2232 let old_blocks = std::mem::take(&mut self.blocks);
2233 let new_blocks = self
2234 .conversation
2235 .read(cx)
2236 .messages(cx)
2237 .map(|message| BlockProperties {
2238 position: buffer.anchor_in_excerpt(excerpt_id, message.anchor),
2239 height: 2,
2240 style: BlockStyle::Sticky,
2241 render: Arc::new({
2242 let conversation = self.conversation.clone();
2243 move |_cx| {
2244 let message_id = message.id;
2245 let sender = ButtonLike::new("role")
2246 .child(match message.role {
2247 Role::User => Label::new("You").color(Color::Default),
2248 Role::Assistant => {
2249 Label::new("Assistant").color(Color::Modified)
2250 }
2251 Role::System => Label::new("System").color(Color::Warning),
2252 })
2253 .on_click({
2254 let conversation = conversation.clone();
2255 move |_, cx| {
2256 conversation.update(cx, |conversation, cx| {
2257 conversation.cycle_message_roles(
2258 HashSet::from_iter(Some(message_id)),
2259 cx,
2260 )
2261 })
2262 }
2263 });
2264
2265 h_stack()
2266 .id(("message_header", message_id.0))
2267 .border()
2268 .border_color(gpui::red())
2269 .child(sender)
2270 .child(Label::new(message.sent_at.format("%I:%M%P").to_string()))
2271 .children(
2272 if let MessageStatus::Error(error) = message.status.clone() {
2273 Some(
2274 div()
2275 .id("error")
2276 .tooltip(move |cx| Tooltip::text(&error, cx))
2277 .child(IconElement::new(Icon::XCircle)),
2278 )
2279 } else {
2280 None
2281 },
2282 )
2283 .into_any_element()
2284 }
2285 }),
2286 disposition: BlockDisposition::Above,
2287 })
2288 .collect::<Vec<_>>();
2289
2290 editor.remove_blocks(old_blocks, None, cx);
2291 let ids = editor.insert_blocks(new_blocks, None, cx);
2292 self.blocks = HashSet::from_iter(ids);
2293 });
2294 }
2295
2296 fn quote_selection(
2297 workspace: &mut Workspace,
2298 _: &QuoteSelection,
2299 cx: &mut ViewContext<Workspace>,
2300 ) {
2301 let Some(panel) = workspace.panel::<AssistantPanel>(cx) else {
2302 return;
2303 };
2304 let Some(editor) = workspace
2305 .active_item(cx)
2306 .and_then(|item| item.act_as::<Editor>(cx))
2307 else {
2308 return;
2309 };
2310
2311 let editor = editor.read(cx);
2312 let range = editor.selections.newest::<usize>(cx).range();
2313 let buffer = editor.buffer().read(cx).snapshot(cx);
2314 let start_language = buffer.language_at(range.start);
2315 let end_language = buffer.language_at(range.end);
2316 let language_name = if start_language == end_language {
2317 start_language.map(|language| language.name())
2318 } else {
2319 None
2320 };
2321 let language_name = language_name.as_deref().unwrap_or("").to_lowercase();
2322
2323 let selected_text = buffer.text_for_range(range).collect::<String>();
2324 let text = if selected_text.is_empty() {
2325 None
2326 } else {
2327 Some(if language_name == "markdown" {
2328 selected_text
2329 .lines()
2330 .map(|line| format!("> {}", line))
2331 .collect::<Vec<_>>()
2332 .join("\n")
2333 } else {
2334 format!("```{language_name}\n{selected_text}\n```")
2335 })
2336 };
2337
2338 // Activate the panel
2339 if !panel.focus_handle(cx).contains_focused(cx) {
2340 workspace.toggle_panel_focus::<AssistantPanel>(cx);
2341 }
2342
2343 if let Some(text) = text {
2344 panel.update(cx, |panel, cx| {
2345 let conversation = panel
2346 .active_editor()
2347 .cloned()
2348 .unwrap_or_else(|| panel.new_conversation(cx));
2349 conversation.update(cx, |conversation, cx| {
2350 conversation
2351 .editor
2352 .update(cx, |editor, cx| editor.insert(&text, cx))
2353 });
2354 });
2355 }
2356 }
2357
2358 fn copy(&mut self, _: &editor::Copy, cx: &mut ViewContext<Self>) {
2359 let editor = self.editor.read(cx);
2360 let conversation = self.conversation.read(cx);
2361 if editor.selections.count() == 1 {
2362 let selection = editor.selections.newest::<usize>(cx);
2363 let mut copied_text = String::new();
2364 let mut spanned_messages = 0;
2365 for message in conversation.messages(cx) {
2366 if message.offset_range.start >= selection.range().end {
2367 break;
2368 } else if message.offset_range.end >= selection.range().start {
2369 let range = cmp::max(message.offset_range.start, selection.range().start)
2370 ..cmp::min(message.offset_range.end, selection.range().end);
2371 if !range.is_empty() {
2372 spanned_messages += 1;
2373 write!(&mut copied_text, "## {}\n\n", message.role).unwrap();
2374 for chunk in conversation.buffer.read(cx).text_for_range(range) {
2375 copied_text.push_str(&chunk);
2376 }
2377 copied_text.push('\n');
2378 }
2379 }
2380 }
2381
2382 if spanned_messages > 1 {
2383 cx.write_to_clipboard(ClipboardItem::new(copied_text));
2384 return;
2385 }
2386 }
2387
2388 cx.propagate();
2389 }
2390
2391 fn split(&mut self, _: &Split, cx: &mut ViewContext<Self>) {
2392 self.conversation.update(cx, |conversation, cx| {
2393 let selections = self.editor.read(cx).selections.disjoint_anchors();
2394 for selection in selections.into_iter() {
2395 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2396 let range = selection
2397 .map(|endpoint| endpoint.to_offset(&buffer))
2398 .range();
2399 conversation.split_message(range, cx);
2400 }
2401 });
2402 }
2403
2404 fn save(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
2405 self.conversation.update(cx, |conversation, cx| {
2406 conversation.save(None, self.fs.clone(), cx)
2407 });
2408 }
2409
2410 fn cycle_model(&mut self, cx: &mut ViewContext<Self>) {
2411 self.conversation.update(cx, |conversation, cx| {
2412 let new_model = conversation.model.cycle();
2413 conversation.set_model(new_model, cx);
2414 });
2415 }
2416
2417 fn title(&self, cx: &AppContext) -> String {
2418 self.conversation
2419 .read(cx)
2420 .summary
2421 .as_ref()
2422 .map(|summary| summary.text.clone())
2423 .unwrap_or_else(|| "New Conversation".into())
2424 }
2425
2426 fn render_current_model(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2427 Button::new(
2428 "current_model",
2429 self.conversation.read(cx).model.short_name(),
2430 )
2431 .tooltip(move |cx| Tooltip::text("Change Model", cx))
2432 .on_click(cx.listener(|this, _, cx| this.cycle_model(cx)))
2433 }
2434
2435 fn render_remaining_tokens(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
2436 let remaining_tokens = self.conversation.read(cx).remaining_tokens()?;
2437 let remaining_tokens_color = if remaining_tokens <= 0 {
2438 Color::Error
2439 } else if remaining_tokens <= 500 {
2440 Color::Warning
2441 } else {
2442 Color::Default
2443 };
2444 Some(
2445 div()
2446 .border()
2447 .border_color(gpui::red())
2448 .child(Label::new(remaining_tokens.to_string()).color(remaining_tokens_color)),
2449 )
2450 }
2451}
2452
2453impl EventEmitter<ConversationEditorEvent> for ConversationEditor {}
2454
2455impl Render for ConversationEditor {
2456 type Element = Div;
2457
2458 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2459 div()
2460 .key_context("ConversationEditor")
2461 .size_full()
2462 .relative()
2463 .capture_action(cx.listener(ConversationEditor::cancel_last_assist))
2464 .capture_action(cx.listener(ConversationEditor::save))
2465 .capture_action(cx.listener(ConversationEditor::copy))
2466 .capture_action(cx.listener(ConversationEditor::cycle_message_role))
2467 .on_action(cx.listener(ConversationEditor::assist))
2468 .on_action(cx.listener(ConversationEditor::split))
2469 .child(self.editor.clone())
2470 .child(
2471 h_stack()
2472 .absolute()
2473 .gap_1()
2474 .top_3()
2475 .right_5()
2476 .child(self.render_current_model(cx))
2477 .children(self.render_remaining_tokens(cx)),
2478 )
2479 }
2480}
2481
2482impl FocusableView for ConversationEditor {
2483 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2484 self.editor.focus_handle(cx)
2485 }
2486}
2487
2488#[derive(Clone, Debug)]
2489struct MessageAnchor {
2490 id: MessageId,
2491 start: language::Anchor,
2492}
2493
2494#[derive(Clone, Debug)]
2495pub struct Message {
2496 offset_range: Range<usize>,
2497 index_range: Range<usize>,
2498 id: MessageId,
2499 anchor: language::Anchor,
2500 role: Role,
2501 sent_at: DateTime<Local>,
2502 status: MessageStatus,
2503}
2504
2505impl Message {
2506 fn to_open_ai_message(&self, buffer: &Buffer) -> RequestMessage {
2507 let content = buffer
2508 .text_for_range(self.offset_range.clone())
2509 .collect::<String>();
2510 RequestMessage {
2511 role: self.role,
2512 content: content.trim_end().into(),
2513 }
2514 }
2515}
2516
2517enum InlineAssistantEvent {
2518 Confirmed {
2519 prompt: String,
2520 include_conversation: bool,
2521 retrieve_context: bool,
2522 },
2523 Canceled,
2524 Dismissed,
2525 IncludeConversationToggled {
2526 include_conversation: bool,
2527 },
2528 RetrieveContextToggled {
2529 retrieve_context: bool,
2530 },
2531}
2532
2533struct InlineAssistant {
2534 id: usize,
2535 prompt_editor: View<Editor>,
2536 workspace: WeakView<Workspace>,
2537 confirmed: bool,
2538 include_conversation: bool,
2539 measurements: Rc<Cell<BlockMeasurements>>,
2540 prompt_history: VecDeque<String>,
2541 prompt_history_ix: Option<usize>,
2542 pending_prompt: String,
2543 codegen: Model<Codegen>,
2544 _subscriptions: Vec<Subscription>,
2545 retrieve_context: bool,
2546 semantic_index: Option<Model<SemanticIndex>>,
2547 semantic_permissioned: Option<bool>,
2548 project: WeakModel<Project>,
2549 maintain_rate_limit: Option<Task<()>>,
2550}
2551
2552impl EventEmitter<InlineAssistantEvent> for InlineAssistant {}
2553
2554impl Render for InlineAssistant {
2555 type Element = Div;
2556
2557 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2558 let measurements = self.measurements.get();
2559 h_stack()
2560 .w_full()
2561 .py_2()
2562 .border_y_1()
2563 .border_color(cx.theme().colors().border)
2564 .on_action(cx.listener(Self::confirm))
2565 .on_action(cx.listener(Self::cancel))
2566 .on_action(cx.listener(Self::toggle_include_conversation))
2567 .on_action(cx.listener(Self::toggle_retrieve_context))
2568 .on_action(cx.listener(Self::move_up))
2569 .on_action(cx.listener(Self::move_down))
2570 .child(
2571 h_stack()
2572 .justify_center()
2573 .w(measurements.gutter_width)
2574 .child(
2575 IconButton::new("include_conversation", Icon::Ai)
2576 .on_click(cx.listener(|this, _, cx| {
2577 this.toggle_include_conversation(&ToggleIncludeConversation, cx)
2578 }))
2579 .selected(self.include_conversation)
2580 .tooltip(|cx| {
2581 Tooltip::for_action(
2582 "Include Conversation",
2583 &ToggleIncludeConversation,
2584 cx,
2585 )
2586 }),
2587 )
2588 .children(if SemanticIndex::enabled(cx) {
2589 Some(
2590 IconButton::new("retrieve_context", Icon::MagnifyingGlass)
2591 .on_click(cx.listener(|this, _, cx| {
2592 this.toggle_retrieve_context(&ToggleRetrieveContext, cx)
2593 }))
2594 .selected(self.retrieve_context)
2595 .tooltip(|cx| {
2596 Tooltip::for_action(
2597 "Retrieve Context",
2598 &ToggleRetrieveContext,
2599 cx,
2600 )
2601 }),
2602 )
2603 } else {
2604 None
2605 })
2606 .children(if let Some(error) = self.codegen.read(cx).error() {
2607 let error_message = SharedString::from(error.to_string());
2608 Some(
2609 div()
2610 .id("error")
2611 .tooltip(move |cx| Tooltip::text(error_message.clone(), cx))
2612 .child(IconElement::new(Icon::XCircle).color(Color::Error)),
2613 )
2614 } else {
2615 None
2616 }),
2617 )
2618 .child(
2619 h_stack()
2620 .w_full()
2621 .ml(measurements.anchor_x - measurements.gutter_width)
2622 .child(self.render_prompt_editor(cx)),
2623 )
2624 .children(if self.retrieve_context {
2625 self.retrieve_context_status(cx)
2626 } else {
2627 None
2628 })
2629 }
2630}
2631
2632impl FocusableView for InlineAssistant {
2633 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
2634 self.prompt_editor.focus_handle(cx)
2635 }
2636}
2637
2638impl InlineAssistant {
2639 fn new(
2640 id: usize,
2641 measurements: Rc<Cell<BlockMeasurements>>,
2642 include_conversation: bool,
2643 prompt_history: VecDeque<String>,
2644 codegen: Model<Codegen>,
2645 workspace: WeakView<Workspace>,
2646 cx: &mut ViewContext<Self>,
2647 retrieve_context: bool,
2648 semantic_index: Option<Model<SemanticIndex>>,
2649 project: Model<Project>,
2650 ) -> Self {
2651 let prompt_editor = cx.build_view(|cx| {
2652 let mut editor = Editor::single_line(cx);
2653 let placeholder = match codegen.read(cx).kind() {
2654 CodegenKind::Transform { .. } => "Enter transformation prompt…",
2655 CodegenKind::Generate { .. } => "Enter generation prompt…",
2656 };
2657 editor.set_placeholder_text(placeholder, cx);
2658 editor
2659 });
2660 cx.focus_view(&prompt_editor);
2661
2662 let mut subscriptions = vec![
2663 cx.observe(&codegen, Self::handle_codegen_changed),
2664 cx.subscribe(&prompt_editor, Self::handle_prompt_editor_events),
2665 ];
2666
2667 if let Some(semantic_index) = semantic_index.clone() {
2668 subscriptions.push(cx.observe(&semantic_index, Self::semantic_index_changed));
2669 }
2670
2671 let assistant = Self {
2672 id,
2673 prompt_editor,
2674 workspace,
2675 confirmed: false,
2676 include_conversation,
2677 measurements,
2678 prompt_history,
2679 prompt_history_ix: None,
2680 pending_prompt: String::new(),
2681 codegen,
2682 _subscriptions: subscriptions,
2683 retrieve_context,
2684 semantic_permissioned: None,
2685 semantic_index,
2686 project: project.downgrade(),
2687 maintain_rate_limit: None,
2688 };
2689
2690 assistant.index_project(cx).log_err();
2691
2692 assistant
2693 }
2694
2695 fn semantic_permissioned(&self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
2696 if let Some(value) = self.semantic_permissioned {
2697 return Task::ready(Ok(value));
2698 }
2699
2700 let Some(project) = self.project.upgrade() else {
2701 return Task::ready(Err(anyhow!("project was dropped")));
2702 };
2703
2704 self.semantic_index
2705 .as_ref()
2706 .map(|semantic| {
2707 semantic.update(cx, |this, cx| this.project_previously_indexed(&project, cx))
2708 })
2709 .unwrap_or(Task::ready(Ok(false)))
2710 }
2711
2712 fn handle_prompt_editor_events(
2713 &mut self,
2714 _: View<Editor>,
2715 event: &EditorEvent,
2716 cx: &mut ViewContext<Self>,
2717 ) {
2718 if let EditorEvent::Edited = event {
2719 self.pending_prompt = self.prompt_editor.read(cx).text(cx);
2720 cx.notify();
2721 }
2722 }
2723
2724 fn semantic_index_changed(
2725 &mut self,
2726 semantic_index: Model<SemanticIndex>,
2727 cx: &mut ViewContext<Self>,
2728 ) {
2729 let Some(project) = self.project.upgrade() else {
2730 return;
2731 };
2732
2733 let status = semantic_index.read(cx).status(&project);
2734 match status {
2735 SemanticIndexStatus::Indexing {
2736 rate_limit_expiry: Some(_),
2737 ..
2738 } => {
2739 if self.maintain_rate_limit.is_none() {
2740 self.maintain_rate_limit = Some(cx.spawn(|this, mut cx| async move {
2741 loop {
2742 cx.background_executor().timer(Duration::from_secs(1)).await;
2743 this.update(&mut cx, |_, cx| cx.notify()).log_err();
2744 }
2745 }));
2746 }
2747 return;
2748 }
2749 _ => {
2750 self.maintain_rate_limit = None;
2751 }
2752 }
2753 }
2754
2755 fn handle_codegen_changed(&mut self, _: Model<Codegen>, cx: &mut ViewContext<Self>) {
2756 let is_read_only = !self.codegen.read(cx).idle();
2757 self.prompt_editor.update(cx, |editor, _cx| {
2758 let was_read_only = editor.read_only();
2759 if was_read_only != is_read_only {
2760 if is_read_only {
2761 editor.set_read_only(true);
2762 } else {
2763 self.confirmed = false;
2764 editor.set_read_only(false);
2765 }
2766 }
2767 });
2768 cx.notify();
2769 }
2770
2771 fn cancel(&mut self, _: &editor::Cancel, cx: &mut ViewContext<Self>) {
2772 cx.emit(InlineAssistantEvent::Canceled);
2773 }
2774
2775 fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
2776 if self.confirmed {
2777 cx.emit(InlineAssistantEvent::Dismissed);
2778 } else {
2779 report_assistant_event(self.workspace.clone(), None, AssistantKind::Inline, cx);
2780
2781 let prompt = self.prompt_editor.read(cx).text(cx);
2782 self.prompt_editor
2783 .update(cx, |editor, _cx| editor.set_read_only(true));
2784 cx.emit(InlineAssistantEvent::Confirmed {
2785 prompt,
2786 include_conversation: self.include_conversation,
2787 retrieve_context: self.retrieve_context,
2788 });
2789 self.confirmed = true;
2790 cx.notify();
2791 }
2792 }
2793
2794 fn toggle_retrieve_context(&mut self, _: &ToggleRetrieveContext, cx: &mut ViewContext<Self>) {
2795 let semantic_permissioned = self.semantic_permissioned(cx);
2796
2797 let Some(project) = self.project.upgrade() else {
2798 return;
2799 };
2800
2801 let project_name = project
2802 .read(cx)
2803 .worktree_root_names(cx)
2804 .collect::<Vec<&str>>()
2805 .join("/");
2806 let is_plural = project_name.chars().filter(|letter| *letter == '/').count() > 0;
2807 let prompt_text = format!("Would you like to index the '{}' project{} for context retrieval? This requires sending code to the OpenAI API", project_name,
2808 if is_plural {
2809 "s"
2810 } else {""});
2811
2812 cx.spawn(|this, mut cx| async move {
2813 // If Necessary prompt user
2814 if !semantic_permissioned.await.unwrap_or(false) {
2815 let answer = this.update(&mut cx, |_, cx| {
2816 cx.prompt(
2817 PromptLevel::Info,
2818 prompt_text.as_str(),
2819 &["Continue", "Cancel"],
2820 )
2821 })?;
2822
2823 if answer.await? == 0 {
2824 this.update(&mut cx, |this, _| {
2825 this.semantic_permissioned = Some(true);
2826 })?;
2827 } else {
2828 return anyhow::Ok(());
2829 }
2830 }
2831
2832 // If permissioned, update context appropriately
2833 this.update(&mut cx, |this, cx| {
2834 this.retrieve_context = !this.retrieve_context;
2835
2836 cx.emit(InlineAssistantEvent::RetrieveContextToggled {
2837 retrieve_context: this.retrieve_context,
2838 });
2839
2840 if this.retrieve_context {
2841 this.index_project(cx).log_err();
2842 }
2843
2844 cx.notify();
2845 })?;
2846
2847 anyhow::Ok(())
2848 })
2849 .detach_and_log_err(cx);
2850 }
2851
2852 fn index_project(&self, cx: &mut ViewContext<Self>) -> anyhow::Result<()> {
2853 let Some(project) = self.project.upgrade() else {
2854 return Err(anyhow!("project was dropped!"));
2855 };
2856
2857 let semantic_permissioned = self.semantic_permissioned(cx);
2858 if let Some(semantic_index) = SemanticIndex::global(cx) {
2859 cx.spawn(|_, mut cx| async move {
2860 // This has to be updated to accomodate for semantic_permissions
2861 if semantic_permissioned.await.unwrap_or(false) {
2862 semantic_index
2863 .update(&mut cx, |index, cx| index.index_project(project, cx))?
2864 .await
2865 } else {
2866 Err(anyhow!("project is not permissioned for semantic indexing"))
2867 }
2868 })
2869 .detach_and_log_err(cx);
2870 }
2871
2872 anyhow::Ok(())
2873 }
2874
2875 fn retrieve_context_status(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
2876 let Some(project) = self.project.upgrade() else {
2877 return None;
2878 };
2879
2880 let semantic_index = SemanticIndex::global(cx)?;
2881 let status = semantic_index.update(cx, |index, _| index.status(&project));
2882 match status {
2883 SemanticIndexStatus::NotAuthenticated {} => Some(
2884 div()
2885 .id("error")
2886 .tooltip(|cx| Tooltip::text("Not Authenticated. Please ensure you have a valid 'OPENAI_API_KEY' in your environment variables.", cx))
2887 .child(IconElement::new(Icon::XCircle))
2888 .into_any_element()
2889 ),
2890
2891 SemanticIndexStatus::NotIndexed {} => Some(
2892 div()
2893 .id("error")
2894 .tooltip(|cx| Tooltip::text("Not Indexed", cx))
2895 .child(IconElement::new(Icon::XCircle))
2896 .into_any_element()
2897 ),
2898
2899 SemanticIndexStatus::Indexing {
2900 remaining_files,
2901 rate_limit_expiry,
2902 } => {
2903 let mut status_text = if remaining_files == 0 {
2904 "Indexing...".to_string()
2905 } else {
2906 format!("Remaining files to index: {remaining_files}")
2907 };
2908
2909 if let Some(rate_limit_expiry) = rate_limit_expiry {
2910 let remaining_seconds = rate_limit_expiry.duration_since(Instant::now());
2911 if remaining_seconds > Duration::from_secs(0) && remaining_files > 0 {
2912 write!(
2913 status_text,
2914 " (rate limit expires in {}s)",
2915 remaining_seconds.as_secs()
2916 )
2917 .unwrap();
2918 }
2919 }
2920
2921 let status_text = SharedString::from(status_text);
2922 Some(
2923 div()
2924 .id("update")
2925 .tooltip(move |cx| Tooltip::text(status_text.clone(), cx))
2926 .child(IconElement::new(Icon::Update).color(Color::Info))
2927 .into_any_element()
2928 )
2929 }
2930
2931 SemanticIndexStatus::Indexed {} => Some(
2932 div()
2933 .id("check")
2934 .tooltip(|cx| Tooltip::text("Index up to date", cx))
2935 .child(IconElement::new(Icon::Check).color(Color::Success))
2936 .into_any_element()
2937 ),
2938 }
2939 }
2940
2941 fn toggle_include_conversation(
2942 &mut self,
2943 _: &ToggleIncludeConversation,
2944 cx: &mut ViewContext<Self>,
2945 ) {
2946 self.include_conversation = !self.include_conversation;
2947 cx.emit(InlineAssistantEvent::IncludeConversationToggled {
2948 include_conversation: self.include_conversation,
2949 });
2950 cx.notify();
2951 }
2952
2953 fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2954 if let Some(ix) = self.prompt_history_ix {
2955 if ix > 0 {
2956 self.prompt_history_ix = Some(ix - 1);
2957 let prompt = self.prompt_history[ix - 1].clone();
2958 self.set_prompt(&prompt, cx);
2959 }
2960 } else if !self.prompt_history.is_empty() {
2961 self.prompt_history_ix = Some(self.prompt_history.len() - 1);
2962 let prompt = self.prompt_history[self.prompt_history.len() - 1].clone();
2963 self.set_prompt(&prompt, cx);
2964 }
2965 }
2966
2967 fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2968 if let Some(ix) = self.prompt_history_ix {
2969 if ix < self.prompt_history.len() - 1 {
2970 self.prompt_history_ix = Some(ix + 1);
2971 let prompt = self.prompt_history[ix + 1].clone();
2972 self.set_prompt(&prompt, cx);
2973 } else {
2974 self.prompt_history_ix = None;
2975 let pending_prompt = self.pending_prompt.clone();
2976 self.set_prompt(&pending_prompt, cx);
2977 }
2978 }
2979 }
2980
2981 fn set_prompt(&mut self, prompt: &str, cx: &mut ViewContext<Self>) {
2982 self.prompt_editor.update(cx, |editor, cx| {
2983 editor.buffer().update(cx, |buffer, cx| {
2984 let len = buffer.len(cx);
2985 buffer.edit([(0..len, prompt)], None, cx);
2986 });
2987 });
2988 }
2989
2990 fn render_prompt_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2991 let settings = ThemeSettings::get_global(cx);
2992 let text_style = TextStyle {
2993 color: if self.prompt_editor.read(cx).read_only() {
2994 cx.theme().colors().text_disabled
2995 } else {
2996 cx.theme().colors().text
2997 },
2998 font_family: settings.ui_font.family.clone(),
2999 font_features: settings.ui_font.features,
3000 font_size: rems(0.875).into(),
3001 font_weight: FontWeight::NORMAL,
3002 font_style: FontStyle::Normal,
3003 line_height: relative(1.).into(),
3004 background_color: None,
3005 underline: None,
3006 white_space: WhiteSpace::Normal,
3007 };
3008 EditorElement::new(
3009 &self.prompt_editor,
3010 EditorStyle {
3011 background: cx.theme().colors().editor_background,
3012 local_player: cx.theme().players().local(),
3013 text: text_style,
3014 ..Default::default()
3015 },
3016 )
3017 }
3018}
3019
3020// This wouldn't need to exist if we could pass parameters when rendering child views.
3021#[derive(Copy, Clone, Default)]
3022struct BlockMeasurements {
3023 anchor_x: Pixels,
3024 gutter_width: Pixels,
3025}
3026
3027struct PendingInlineAssist {
3028 editor: WeakView<Editor>,
3029 inline_assistant: Option<(BlockId, View<InlineAssistant>)>,
3030 codegen: Model<Codegen>,
3031 _subscriptions: Vec<Subscription>,
3032 project: WeakModel<Project>,
3033}
3034
3035fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3036 ranges.sort_unstable_by(|a, b| {
3037 a.start
3038 .cmp(&b.start, buffer)
3039 .then_with(|| b.end.cmp(&a.end, buffer))
3040 });
3041
3042 let mut ix = 0;
3043 while ix + 1 < ranges.len() {
3044 let b = ranges[ix + 1].clone();
3045 let a = &mut ranges[ix];
3046 if a.end.cmp(&b.start, buffer).is_gt() {
3047 if a.end.cmp(&b.end, buffer).is_lt() {
3048 a.end = b.end;
3049 }
3050 ranges.remove(ix + 1);
3051 } else {
3052 ix += 1;
3053 }
3054 }
3055}
3056
3057#[cfg(test)]
3058mod tests {
3059 use super::*;
3060 use crate::MessageId;
3061 use ai::test::FakeCompletionProvider;
3062 use gpui::AppContext;
3063
3064 #[gpui::test]
3065 fn test_inserting_and_removing_messages(cx: &mut AppContext) {
3066 let settings_store = SettingsStore::test(cx);
3067 cx.set_global(settings_store);
3068 init(cx);
3069 let registry = Arc::new(LanguageRegistry::test());
3070
3071 let completion_provider = Arc::new(FakeCompletionProvider::new());
3072 let conversation =
3073 cx.build_model(|cx| Conversation::new(registry, cx, completion_provider));
3074 let buffer = conversation.read(cx).buffer.clone();
3075
3076 let message_1 = conversation.read(cx).message_anchors[0].clone();
3077 assert_eq!(
3078 messages(&conversation, cx),
3079 vec![(message_1.id, Role::User, 0..0)]
3080 );
3081
3082 let message_2 = conversation.update(cx, |conversation, cx| {
3083 conversation
3084 .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx)
3085 .unwrap()
3086 });
3087 assert_eq!(
3088 messages(&conversation, cx),
3089 vec![
3090 (message_1.id, Role::User, 0..1),
3091 (message_2.id, Role::Assistant, 1..1)
3092 ]
3093 );
3094
3095 buffer.update(cx, |buffer, cx| {
3096 buffer.edit([(0..0, "1"), (1..1, "2")], None, cx)
3097 });
3098 assert_eq!(
3099 messages(&conversation, cx),
3100 vec![
3101 (message_1.id, Role::User, 0..2),
3102 (message_2.id, Role::Assistant, 2..3)
3103 ]
3104 );
3105
3106 let message_3 = conversation.update(cx, |conversation, cx| {
3107 conversation
3108 .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3109 .unwrap()
3110 });
3111 assert_eq!(
3112 messages(&conversation, cx),
3113 vec![
3114 (message_1.id, Role::User, 0..2),
3115 (message_2.id, Role::Assistant, 2..4),
3116 (message_3.id, Role::User, 4..4)
3117 ]
3118 );
3119
3120 let message_4 = conversation.update(cx, |conversation, cx| {
3121 conversation
3122 .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3123 .unwrap()
3124 });
3125 assert_eq!(
3126 messages(&conversation, cx),
3127 vec![
3128 (message_1.id, Role::User, 0..2),
3129 (message_2.id, Role::Assistant, 2..4),
3130 (message_4.id, Role::User, 4..5),
3131 (message_3.id, Role::User, 5..5),
3132 ]
3133 );
3134
3135 buffer.update(cx, |buffer, cx| {
3136 buffer.edit([(4..4, "C"), (5..5, "D")], None, cx)
3137 });
3138 assert_eq!(
3139 messages(&conversation, cx),
3140 vec![
3141 (message_1.id, Role::User, 0..2),
3142 (message_2.id, Role::Assistant, 2..4),
3143 (message_4.id, Role::User, 4..6),
3144 (message_3.id, Role::User, 6..7),
3145 ]
3146 );
3147
3148 // Deleting across message boundaries merges the messages.
3149 buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx));
3150 assert_eq!(
3151 messages(&conversation, cx),
3152 vec![
3153 (message_1.id, Role::User, 0..3),
3154 (message_3.id, Role::User, 3..4),
3155 ]
3156 );
3157
3158 // Undoing the deletion should also undo the merge.
3159 buffer.update(cx, |buffer, cx| buffer.undo(cx));
3160 assert_eq!(
3161 messages(&conversation, cx),
3162 vec![
3163 (message_1.id, Role::User, 0..2),
3164 (message_2.id, Role::Assistant, 2..4),
3165 (message_4.id, Role::User, 4..6),
3166 (message_3.id, Role::User, 6..7),
3167 ]
3168 );
3169
3170 // Redoing the deletion should also redo the merge.
3171 buffer.update(cx, |buffer, cx| buffer.redo(cx));
3172 assert_eq!(
3173 messages(&conversation, cx),
3174 vec![
3175 (message_1.id, Role::User, 0..3),
3176 (message_3.id, Role::User, 3..4),
3177 ]
3178 );
3179
3180 // Ensure we can still insert after a merged message.
3181 let message_5 = conversation.update(cx, |conversation, cx| {
3182 conversation
3183 .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3184 .unwrap()
3185 });
3186 assert_eq!(
3187 messages(&conversation, cx),
3188 vec![
3189 (message_1.id, Role::User, 0..3),
3190 (message_5.id, Role::System, 3..4),
3191 (message_3.id, Role::User, 4..5)
3192 ]
3193 );
3194 }
3195
3196 #[gpui::test]
3197 fn test_message_splitting(cx: &mut AppContext) {
3198 let settings_store = SettingsStore::test(cx);
3199 cx.set_global(settings_store);
3200 init(cx);
3201 let registry = Arc::new(LanguageRegistry::test());
3202 let completion_provider = Arc::new(FakeCompletionProvider::new());
3203
3204 let conversation =
3205 cx.build_model(|cx| Conversation::new(registry, cx, completion_provider));
3206 let buffer = conversation.read(cx).buffer.clone();
3207
3208 let message_1 = conversation.read(cx).message_anchors[0].clone();
3209 assert_eq!(
3210 messages(&conversation, cx),
3211 vec![(message_1.id, Role::User, 0..0)]
3212 );
3213
3214 buffer.update(cx, |buffer, cx| {
3215 buffer.edit([(0..0, "aaa\nbbb\nccc\nddd\n")], None, cx)
3216 });
3217
3218 let (_, message_2) =
3219 conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx));
3220 let message_2 = message_2.unwrap();
3221
3222 // We recycle newlines in the middle of a split message
3223 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n");
3224 assert_eq!(
3225 messages(&conversation, cx),
3226 vec![
3227 (message_1.id, Role::User, 0..4),
3228 (message_2.id, Role::User, 4..16),
3229 ]
3230 );
3231
3232 let (_, message_3) =
3233 conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx));
3234 let message_3 = message_3.unwrap();
3235
3236 // We don't recycle newlines at the end of a split message
3237 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
3238 assert_eq!(
3239 messages(&conversation, cx),
3240 vec![
3241 (message_1.id, Role::User, 0..4),
3242 (message_3.id, Role::User, 4..5),
3243 (message_2.id, Role::User, 5..17),
3244 ]
3245 );
3246
3247 let (_, message_4) =
3248 conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx));
3249 let message_4 = message_4.unwrap();
3250 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n");
3251 assert_eq!(
3252 messages(&conversation, cx),
3253 vec![
3254 (message_1.id, Role::User, 0..4),
3255 (message_3.id, Role::User, 4..5),
3256 (message_2.id, Role::User, 5..9),
3257 (message_4.id, Role::User, 9..17),
3258 ]
3259 );
3260
3261 let (_, message_5) =
3262 conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx));
3263 let message_5 = message_5.unwrap();
3264 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n");
3265 assert_eq!(
3266 messages(&conversation, cx),
3267 vec![
3268 (message_1.id, Role::User, 0..4),
3269 (message_3.id, Role::User, 4..5),
3270 (message_2.id, Role::User, 5..9),
3271 (message_4.id, Role::User, 9..10),
3272 (message_5.id, Role::User, 10..18),
3273 ]
3274 );
3275
3276 let (message_6, message_7) = conversation.update(cx, |conversation, cx| {
3277 conversation.split_message(14..16, cx)
3278 });
3279 let message_6 = message_6.unwrap();
3280 let message_7 = message_7.unwrap();
3281 assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n");
3282 assert_eq!(
3283 messages(&conversation, cx),
3284 vec![
3285 (message_1.id, Role::User, 0..4),
3286 (message_3.id, Role::User, 4..5),
3287 (message_2.id, Role::User, 5..9),
3288 (message_4.id, Role::User, 9..10),
3289 (message_5.id, Role::User, 10..14),
3290 (message_6.id, Role::User, 14..17),
3291 (message_7.id, Role::User, 17..19),
3292 ]
3293 );
3294 }
3295
3296 #[gpui::test]
3297 fn test_messages_for_offsets(cx: &mut AppContext) {
3298 let settings_store = SettingsStore::test(cx);
3299 cx.set_global(settings_store);
3300 init(cx);
3301 let registry = Arc::new(LanguageRegistry::test());
3302 let completion_provider = Arc::new(FakeCompletionProvider::new());
3303 let conversation =
3304 cx.build_model(|cx| Conversation::new(registry, cx, completion_provider));
3305 let buffer = conversation.read(cx).buffer.clone();
3306
3307 let message_1 = conversation.read(cx).message_anchors[0].clone();
3308 assert_eq!(
3309 messages(&conversation, cx),
3310 vec![(message_1.id, Role::User, 0..0)]
3311 );
3312
3313 buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx));
3314 let message_2 = conversation
3315 .update(cx, |conversation, cx| {
3316 conversation.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx)
3317 })
3318 .unwrap();
3319 buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx));
3320
3321 let message_3 = conversation
3322 .update(cx, |conversation, cx| {
3323 conversation.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx)
3324 })
3325 .unwrap();
3326 buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx));
3327
3328 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc");
3329 assert_eq!(
3330 messages(&conversation, cx),
3331 vec![
3332 (message_1.id, Role::User, 0..4),
3333 (message_2.id, Role::User, 4..8),
3334 (message_3.id, Role::User, 8..11)
3335 ]
3336 );
3337
3338 assert_eq!(
3339 message_ids_for_offsets(&conversation, &[0, 4, 9], cx),
3340 [message_1.id, message_2.id, message_3.id]
3341 );
3342 assert_eq!(
3343 message_ids_for_offsets(&conversation, &[0, 1, 11], cx),
3344 [message_1.id, message_3.id]
3345 );
3346
3347 let message_4 = conversation
3348 .update(cx, |conversation, cx| {
3349 conversation.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx)
3350 })
3351 .unwrap();
3352 assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n");
3353 assert_eq!(
3354 messages(&conversation, cx),
3355 vec![
3356 (message_1.id, Role::User, 0..4),
3357 (message_2.id, Role::User, 4..8),
3358 (message_3.id, Role::User, 8..12),
3359 (message_4.id, Role::User, 12..12)
3360 ]
3361 );
3362 assert_eq!(
3363 message_ids_for_offsets(&conversation, &[0, 4, 8, 12], cx),
3364 [message_1.id, message_2.id, message_3.id, message_4.id]
3365 );
3366
3367 fn message_ids_for_offsets(
3368 conversation: &Model<Conversation>,
3369 offsets: &[usize],
3370 cx: &AppContext,
3371 ) -> Vec<MessageId> {
3372 conversation
3373 .read(cx)
3374 .messages_for_offsets(offsets.iter().copied(), cx)
3375 .into_iter()
3376 .map(|message| message.id)
3377 .collect()
3378 }
3379 }
3380
3381 #[gpui::test]
3382 fn test_serialization(cx: &mut AppContext) {
3383 let settings_store = SettingsStore::test(cx);
3384 cx.set_global(settings_store);
3385 init(cx);
3386 let registry = Arc::new(LanguageRegistry::test());
3387 let completion_provider = Arc::new(FakeCompletionProvider::new());
3388 let conversation =
3389 cx.build_model(|cx| Conversation::new(registry.clone(), cx, completion_provider));
3390 let buffer = conversation.read(cx).buffer.clone();
3391 let message_0 = conversation.read(cx).message_anchors[0].id;
3392 let message_1 = conversation.update(cx, |conversation, cx| {
3393 conversation
3394 .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx)
3395 .unwrap()
3396 });
3397 let message_2 = conversation.update(cx, |conversation, cx| {
3398 conversation
3399 .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx)
3400 .unwrap()
3401 });
3402 buffer.update(cx, |buffer, cx| {
3403 buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx);
3404 buffer.finalize_last_transaction();
3405 });
3406 let _message_3 = conversation.update(cx, |conversation, cx| {
3407 conversation
3408 .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx)
3409 .unwrap()
3410 });
3411 buffer.update(cx, |buffer, cx| buffer.undo(cx));
3412 assert_eq!(buffer.read(cx).text(), "a\nb\nc\n");
3413 assert_eq!(
3414 messages(&conversation, cx),
3415 [
3416 (message_0, Role::User, 0..2),
3417 (message_1.id, Role::Assistant, 2..6),
3418 (message_2.id, Role::System, 6..6),
3419 ]
3420 );
3421
3422 let deserialized_conversation = cx.build_model(|cx| {
3423 Conversation::deserialize(
3424 conversation.read(cx).serialize(cx),
3425 Default::default(),
3426 registry.clone(),
3427 cx,
3428 )
3429 });
3430 let deserialized_buffer = deserialized_conversation.read(cx).buffer.clone();
3431 assert_eq!(deserialized_buffer.read(cx).text(), "a\nb\nc\n");
3432 assert_eq!(
3433 messages(&deserialized_conversation, cx),
3434 [
3435 (message_0, Role::User, 0..2),
3436 (message_1.id, Role::Assistant, 2..6),
3437 (message_2.id, Role::System, 6..6),
3438 ]
3439 );
3440 }
3441
3442 fn messages(
3443 conversation: &Model<Conversation>,
3444 cx: &AppContext,
3445 ) -> Vec<(MessageId, Role, Range<usize>)> {
3446 conversation
3447 .read(cx)
3448 .messages(cx)
3449 .map(|message| (message.id, message.role, message.offset_range))
3450 .collect()
3451 }
3452}
3453
3454fn report_assistant_event(
3455 workspace: WeakView<Workspace>,
3456 conversation_id: Option<String>,
3457 assistant_kind: AssistantKind,
3458 cx: &AppContext,
3459) {
3460 let Some(workspace) = workspace.upgrade() else {
3461 return;
3462 };
3463
3464 let client = workspace.read(cx).project().read(cx).client();
3465 let telemetry = client.telemetry();
3466
3467 let model = AssistantSettings::get_global(cx)
3468 .default_open_ai_model
3469 .clone();
3470
3471 let telemetry_settings = TelemetrySettings::get_global(cx).clone();
3472
3473 telemetry.report_assistant_event(
3474 telemetry_settings,
3475 conversation_id,
3476 assistant_kind,
3477 model.full_name(),
3478 )
3479}