prompt_library.rs

   1use crate::{
   2    slash_command::SlashCommandCompletionProvider, AssistantPanel, CompletionProvider,
   3    InlineAssist, InlineAssistant, LanguageModelRequest, LanguageModelRequestMessage, Role,
   4};
   5use anyhow::{anyhow, Result};
   6use assistant_slash_command::SlashCommandRegistry;
   7use chrono::{DateTime, Utc};
   8use collections::HashMap;
   9use editor::{actions::Tab, CurrentLineHighlight, Editor, EditorElement, EditorEvent, EditorStyle};
  10use futures::{
  11    future::{self, BoxFuture, Shared},
  12    FutureExt,
  13};
  14use fuzzy::StringMatchCandidate;
  15use gpui::{
  16    actions, point, size, transparent_black, AppContext, BackgroundExecutor, Bounds, EventEmitter,
  17    Global, HighlightStyle, PromptLevel, ReadGlobal, Subscription, Task, TextStyle,
  18    TitlebarOptions, UpdateGlobal, View, WindowBounds, WindowHandle, WindowOptions,
  19};
  20use heed::{types::SerdeBincode, Database, RoTxn};
  21use language::{language_settings::SoftWrap, Buffer, LanguageRegistry};
  22use parking_lot::RwLock;
  23use picker::{Picker, PickerDelegate};
  24use rope::Rope;
  25use serde::{Deserialize, Serialize};
  26use settings::Settings;
  27use std::{
  28    cmp::Reverse,
  29    future::Future,
  30    path::PathBuf,
  31    sync::{atomic::AtomicBool, Arc},
  32    time::Duration,
  33};
  34use theme::ThemeSettings;
  35use ui::{
  36    div, prelude::*, IconButtonShape, ListItem, ListItemSpacing, ParentElement, Render,
  37    SharedString, Styled, TitleBar, Tooltip, ViewContext, VisualContext,
  38};
  39use util::{ResultExt, TryFutureExt};
  40use uuid::Uuid;
  41use workspace::Workspace;
  42
  43actions!(
  44    prompt_library,
  45    [
  46        NewPrompt,
  47        DeletePrompt,
  48        DuplicatePrompt,
  49        ToggleDefaultPrompt
  50    ]
  51);
  52
  53/// Init starts loading the PromptStore in the background and assigns
  54/// a shared future to a global.
  55pub fn init(cx: &mut AppContext) {
  56    let db_path = paths::prompts_dir().join("prompts-library-db.0.mdb");
  57    let prompt_store_future = PromptStore::new(db_path, cx.background_executor().clone())
  58        .then(|result| future::ready(result.map(Arc::new).map_err(Arc::new)))
  59        .boxed()
  60        .shared();
  61    cx.set_global(GlobalPromptStore(prompt_store_future))
  62}
  63
  64/// This function opens a new prompt library window if one doesn't exist already.
  65/// If one exists, it brings it to the foreground.
  66///
  67/// Note that, when opening a new window, this waits for the PromptStore to be
  68/// initialized. If it was initialized successfully, it returns a window handle
  69/// to a prompt library.
  70pub fn open_prompt_library(
  71    language_registry: Arc<LanguageRegistry>,
  72    cx: &mut AppContext,
  73) -> Task<Result<WindowHandle<PromptLibrary>>> {
  74    let existing_window = cx
  75        .windows()
  76        .into_iter()
  77        .find_map(|window| window.downcast::<PromptLibrary>());
  78    if let Some(existing_window) = existing_window {
  79        existing_window
  80            .update(cx, |_, cx| cx.activate_window())
  81            .ok();
  82        Task::ready(Ok(existing_window))
  83    } else {
  84        let store = PromptStore::global(cx);
  85        cx.spawn(|cx| async move {
  86            let store = store.await?;
  87            cx.update(|cx| {
  88                let bounds = Bounds::centered(None, size(px(1024.0), px(768.0)), cx);
  89                cx.open_window(
  90                    WindowOptions {
  91                        titlebar: Some(TitlebarOptions {
  92                            title: Some("Prompt Library".into()),
  93                            appears_transparent: true,
  94                            traffic_light_position: Some(point(px(9.0), px(9.0))),
  95                        }),
  96                        window_bounds: Some(WindowBounds::Windowed(bounds)),
  97                        ..Default::default()
  98                    },
  99                    |cx| cx.new_view(|cx| PromptLibrary::new(store, language_registry, cx)),
 100                )
 101            })?
 102        })
 103    }
 104}
 105
 106pub struct PromptLibrary {
 107    store: Arc<PromptStore>,
 108    language_registry: Arc<LanguageRegistry>,
 109    prompt_editors: HashMap<PromptId, PromptEditor>,
 110    active_prompt_id: Option<PromptId>,
 111    picker: View<Picker<PromptPickerDelegate>>,
 112    pending_load: Task<()>,
 113    _subscriptions: Vec<Subscription>,
 114}
 115
 116struct PromptEditor {
 117    title_editor: View<Editor>,
 118    body_editor: View<Editor>,
 119    token_count: Option<usize>,
 120    pending_token_count: Task<Option<()>>,
 121    next_title_and_body_to_save: Option<(String, Rope)>,
 122    pending_save: Option<Task<Option<()>>>,
 123    _subscriptions: Vec<Subscription>,
 124}
 125
 126struct PromptPickerDelegate {
 127    store: Arc<PromptStore>,
 128    selected_index: usize,
 129    matches: Vec<PromptMetadata>,
 130}
 131
 132enum PromptPickerEvent {
 133    Selected { prompt_id: PromptId },
 134    Confirmed { prompt_id: PromptId },
 135    Deleted { prompt_id: PromptId },
 136    ToggledDefault { prompt_id: PromptId },
 137}
 138
 139impl EventEmitter<PromptPickerEvent> for Picker<PromptPickerDelegate> {}
 140
 141impl PickerDelegate for PromptPickerDelegate {
 142    type ListItem = ListItem;
 143
 144    fn match_count(&self) -> usize {
 145        self.matches.len()
 146    }
 147
 148    fn selected_index(&self) -> usize {
 149        self.selected_index
 150    }
 151
 152    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
 153        self.selected_index = ix;
 154        if let Some(prompt) = self.matches.get(self.selected_index) {
 155            cx.emit(PromptPickerEvent::Selected {
 156                prompt_id: prompt.id,
 157            });
 158        }
 159    }
 160
 161    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 162        "Search...".into()
 163    }
 164
 165    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
 166        let search = self.store.search(query);
 167        let prev_prompt_id = self.matches.get(self.selected_index).map(|mat| mat.id);
 168        cx.spawn(|this, mut cx| async move {
 169            let (matches, selected_index) = cx
 170                .background_executor()
 171                .spawn(async move {
 172                    let matches = search.await;
 173
 174                    let selected_index = prev_prompt_id
 175                        .and_then(|prev_prompt_id| {
 176                            matches.iter().position(|entry| entry.id == prev_prompt_id)
 177                        })
 178                        .unwrap_or(0);
 179                    (matches, selected_index)
 180                })
 181                .await;
 182
 183            this.update(&mut cx, |this, cx| {
 184                this.delegate.matches = matches;
 185                this.delegate.set_selected_index(selected_index, cx);
 186                cx.notify();
 187            })
 188            .ok();
 189        })
 190    }
 191
 192    fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
 193        if let Some(prompt) = self.matches.get(self.selected_index) {
 194            cx.emit(PromptPickerEvent::Confirmed {
 195                prompt_id: prompt.id,
 196            });
 197        }
 198    }
 199
 200    fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
 201
 202    fn render_match(
 203        &self,
 204        ix: usize,
 205        selected: bool,
 206        cx: &mut ViewContext<Picker<Self>>,
 207    ) -> Option<Self::ListItem> {
 208        let prompt = self.matches.get(ix)?;
 209        let default = prompt.default;
 210        let prompt_id = prompt.id;
 211        let element = ListItem::new(ix)
 212            .inset(true)
 213            .spacing(ListItemSpacing::Sparse)
 214            .selected(selected)
 215            .child(h_flex().h_5().line_height(relative(1.)).child(Label::new(
 216                prompt.title.clone().unwrap_or("Untitled".into()),
 217            )))
 218            .end_slot::<IconButton>(default.then(|| {
 219                IconButton::new("toggle-default-prompt", IconName::SparkleFilled)
 220                    .selected(true)
 221                    .icon_color(Color::Accent)
 222                    .shape(IconButtonShape::Square)
 223                    .tooltip(move |cx| Tooltip::text("Remove from Default Prompt", cx))
 224                    .on_click(cx.listener(move |_, _, cx| {
 225                        cx.emit(PromptPickerEvent::ToggledDefault { prompt_id })
 226                    }))
 227            }))
 228            .end_hover_slot(
 229                h_flex()
 230                    .gap_2()
 231                    .child(
 232                        IconButton::new("delete-prompt", IconName::Trash)
 233                            .icon_color(Color::Muted)
 234                            .shape(IconButtonShape::Square)
 235                            .tooltip(move |cx| Tooltip::text("Delete Prompt", cx))
 236                            .on_click(cx.listener(move |_, _, cx| {
 237                                cx.emit(PromptPickerEvent::Deleted { prompt_id })
 238                            })),
 239                    )
 240                    .child(
 241                        IconButton::new("toggle-default-prompt", IconName::Sparkle)
 242                            .selected(default)
 243                            .selected_icon(IconName::SparkleFilled)
 244                            .icon_color(if default { Color::Accent } else { Color::Muted })
 245                            .shape(IconButtonShape::Square)
 246                            .tooltip(move |cx| {
 247                                Tooltip::text(
 248                                    if default {
 249                                        "Remove from Default Prompt"
 250                                    } else {
 251                                        "Add to Default Prompt"
 252                                    },
 253                                    cx,
 254                                )
 255                            })
 256                            .on_click(cx.listener(move |_, _, cx| {
 257                                cx.emit(PromptPickerEvent::ToggledDefault { prompt_id })
 258                            })),
 259                    ),
 260            );
 261        Some(element)
 262    }
 263
 264    fn render_editor(&self, editor: &View<Editor>, cx: &mut ViewContext<Picker<Self>>) -> Div {
 265        h_flex()
 266            .bg(cx.theme().colors().editor_background)
 267            .rounded_md()
 268            .overflow_hidden()
 269            .flex_none()
 270            .py_1()
 271            .px_2()
 272            .mx_2()
 273            .child(editor.clone())
 274    }
 275}
 276
 277impl PromptLibrary {
 278    fn new(
 279        store: Arc<PromptStore>,
 280        language_registry: Arc<LanguageRegistry>,
 281        cx: &mut ViewContext<Self>,
 282    ) -> Self {
 283        let delegate = PromptPickerDelegate {
 284            store: store.clone(),
 285            selected_index: 0,
 286            matches: Vec::new(),
 287        };
 288
 289        let picker = cx.new_view(|cx| {
 290            let picker = Picker::uniform_list(delegate, cx)
 291                .modal(false)
 292                .max_height(None);
 293            picker.focus(cx);
 294            picker
 295        });
 296        Self {
 297            store: store.clone(),
 298            language_registry,
 299            prompt_editors: HashMap::default(),
 300            active_prompt_id: None,
 301            pending_load: Task::ready(()),
 302            _subscriptions: vec![cx.subscribe(&picker, Self::handle_picker_event)],
 303            picker,
 304        }
 305    }
 306
 307    fn handle_picker_event(
 308        &mut self,
 309        _: View<Picker<PromptPickerDelegate>>,
 310        event: &PromptPickerEvent,
 311        cx: &mut ViewContext<Self>,
 312    ) {
 313        match event {
 314            PromptPickerEvent::Selected { prompt_id } => {
 315                self.load_prompt(*prompt_id, false, cx);
 316            }
 317            PromptPickerEvent::Confirmed { prompt_id } => {
 318                self.load_prompt(*prompt_id, true, cx);
 319            }
 320            PromptPickerEvent::ToggledDefault { prompt_id } => {
 321                self.toggle_default_for_prompt(*prompt_id, cx);
 322            }
 323            PromptPickerEvent::Deleted { prompt_id } => {
 324                self.delete_prompt(*prompt_id, cx);
 325            }
 326        }
 327    }
 328
 329    pub fn new_prompt(&mut self, cx: &mut ViewContext<Self>) {
 330        // If we already have an untitled prompt, use that instead
 331        // of creating a new one.
 332        if let Some(metadata) = self.store.first() {
 333            if metadata.title.is_none() {
 334                self.load_prompt(metadata.id, true, cx);
 335                return;
 336            }
 337        }
 338
 339        let prompt_id = PromptId::new();
 340        let save = self.store.save(prompt_id, None, false, "".into());
 341        self.picker.update(cx, |picker, cx| picker.refresh(cx));
 342        cx.spawn(|this, mut cx| async move {
 343            save.await?;
 344            this.update(&mut cx, |this, cx| this.load_prompt(prompt_id, true, cx))
 345        })
 346        .detach_and_log_err(cx);
 347    }
 348
 349    pub fn save_prompt(&mut self, prompt_id: PromptId, cx: &mut ViewContext<Self>) {
 350        const SAVE_THROTTLE: Duration = Duration::from_millis(500);
 351
 352        let prompt_metadata = self.store.metadata(prompt_id).unwrap();
 353        let prompt_editor = self.prompt_editors.get_mut(&prompt_id).unwrap();
 354        let title = prompt_editor.title_editor.read(cx).text(cx);
 355        let body = prompt_editor.body_editor.update(cx, |editor, cx| {
 356            editor
 357                .buffer()
 358                .read(cx)
 359                .as_singleton()
 360                .unwrap()
 361                .read(cx)
 362                .as_rope()
 363                .clone()
 364        });
 365
 366        let store = self.store.clone();
 367        let executor = cx.background_executor().clone();
 368
 369        prompt_editor.next_title_and_body_to_save = Some((title, body));
 370        if prompt_editor.pending_save.is_none() {
 371            prompt_editor.pending_save = Some(cx.spawn(|this, mut cx| {
 372                async move {
 373                    loop {
 374                        let title_and_body = this.update(&mut cx, |this, _| {
 375                            this.prompt_editors
 376                                .get_mut(&prompt_id)?
 377                                .next_title_and_body_to_save
 378                                .take()
 379                        })?;
 380
 381                        if let Some((title, body)) = title_and_body {
 382                            let title = if title.trim().is_empty() {
 383                                None
 384                            } else {
 385                                Some(SharedString::from(title))
 386                            };
 387                            store
 388                                .save(prompt_id, title, prompt_metadata.default, body)
 389                                .await
 390                                .log_err();
 391                            this.update(&mut cx, |this, cx| {
 392                                this.picker.update(cx, |picker, cx| picker.refresh(cx));
 393                                cx.notify();
 394                            })?;
 395
 396                            executor.timer(SAVE_THROTTLE).await;
 397                        } else {
 398                            break;
 399                        }
 400                    }
 401
 402                    this.update(&mut cx, |this, _cx| {
 403                        if let Some(prompt_editor) = this.prompt_editors.get_mut(&prompt_id) {
 404                            prompt_editor.pending_save = None;
 405                        }
 406                    })
 407                }
 408                .log_err()
 409            }));
 410        }
 411    }
 412
 413    pub fn delete_active_prompt(&mut self, cx: &mut ViewContext<Self>) {
 414        if let Some(active_prompt_id) = self.active_prompt_id {
 415            self.delete_prompt(active_prompt_id, cx);
 416        }
 417    }
 418
 419    pub fn duplicate_active_prompt(&mut self, cx: &mut ViewContext<Self>) {
 420        if let Some(active_prompt_id) = self.active_prompt_id {
 421            self.duplicate_prompt(active_prompt_id, cx);
 422        }
 423    }
 424
 425    pub fn toggle_default_for_active_prompt(&mut self, cx: &mut ViewContext<Self>) {
 426        if let Some(active_prompt_id) = self.active_prompt_id {
 427            self.toggle_default_for_prompt(active_prompt_id, cx);
 428        }
 429    }
 430
 431    pub fn toggle_default_for_prompt(&mut self, prompt_id: PromptId, cx: &mut ViewContext<Self>) {
 432        if let Some(prompt_metadata) = self.store.metadata(prompt_id) {
 433            self.store
 434                .save_metadata(prompt_id, prompt_metadata.title, !prompt_metadata.default)
 435                .detach_and_log_err(cx);
 436            self.picker.update(cx, |picker, cx| picker.refresh(cx));
 437            cx.notify();
 438        }
 439    }
 440
 441    pub fn load_prompt(&mut self, prompt_id: PromptId, focus: bool, cx: &mut ViewContext<Self>) {
 442        if let Some(prompt_editor) = self.prompt_editors.get(&prompt_id) {
 443            if focus {
 444                prompt_editor
 445                    .body_editor
 446                    .update(cx, |editor, cx| editor.focus(cx));
 447            }
 448            self.set_active_prompt(Some(prompt_id), cx);
 449        } else if let Some(prompt_metadata) = self.store.metadata(prompt_id) {
 450            let language_registry = self.language_registry.clone();
 451            let commands = SlashCommandRegistry::global(cx);
 452            let prompt = self.store.load(prompt_id);
 453            self.pending_load = cx.spawn(|this, mut cx| async move {
 454                let prompt = prompt.await;
 455                let markdown = language_registry.language_for_name("Markdown").await;
 456                this.update(&mut cx, |this, cx| match prompt {
 457                    Ok(prompt) => {
 458                        let title_editor = cx.new_view(|cx| {
 459                            let mut editor = Editor::auto_width(cx);
 460                            editor.set_placeholder_text("Untitled", cx);
 461                            editor.set_text(prompt_metadata.title.unwrap_or_default(), cx);
 462                            editor
 463                        });
 464                        let body_editor = cx.new_view(|cx| {
 465                            let buffer = cx.new_model(|cx| {
 466                                let mut buffer = Buffer::local(prompt, cx);
 467                                buffer.set_language(markdown.log_err(), cx);
 468                                buffer.set_language_registry(language_registry);
 469                                buffer
 470                            });
 471
 472                            let mut editor = Editor::for_buffer(buffer, None, cx);
 473                            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
 474                            editor.set_show_gutter(false, cx);
 475                            editor.set_show_wrap_guides(false, cx);
 476                            editor.set_show_indent_guides(false, cx);
 477                            editor.set_use_modal_editing(false);
 478                            editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
 479                            editor.set_completion_provider(Box::new(
 480                                SlashCommandCompletionProvider::new(commands, None, None),
 481                            ));
 482                            if focus {
 483                                editor.focus(cx);
 484                            }
 485                            editor
 486                        });
 487                        let _subscriptions = vec![
 488                            cx.subscribe(&title_editor, move |this, editor, event, cx| {
 489                                this.handle_prompt_title_editor_event(prompt_id, editor, event, cx)
 490                            }),
 491                            cx.subscribe(&body_editor, move |this, editor, event, cx| {
 492                                this.handle_prompt_body_editor_event(prompt_id, editor, event, cx)
 493                            }),
 494                        ];
 495                        this.prompt_editors.insert(
 496                            prompt_id,
 497                            PromptEditor {
 498                                title_editor,
 499                                body_editor,
 500                                next_title_and_body_to_save: None,
 501                                pending_save: None,
 502                                token_count: None,
 503                                pending_token_count: Task::ready(None),
 504                                _subscriptions,
 505                            },
 506                        );
 507                        this.set_active_prompt(Some(prompt_id), cx);
 508                        this.count_tokens(prompt_id, cx);
 509                    }
 510                    Err(error) => {
 511                        // TODO: we should show the error in the UI.
 512                        log::error!("error while loading prompt: {:?}", error);
 513                    }
 514                })
 515                .ok();
 516            });
 517        }
 518    }
 519
 520    fn set_active_prompt(&mut self, prompt_id: Option<PromptId>, cx: &mut ViewContext<Self>) {
 521        self.active_prompt_id = prompt_id;
 522        self.picker.update(cx, |picker, cx| {
 523            if let Some(prompt_id) = prompt_id {
 524                if picker
 525                    .delegate
 526                    .matches
 527                    .get(picker.delegate.selected_index())
 528                    .map_or(true, |old_selected_prompt| {
 529                        old_selected_prompt.id != prompt_id
 530                    })
 531                {
 532                    if let Some(ix) = picker
 533                        .delegate
 534                        .matches
 535                        .iter()
 536                        .position(|mat| mat.id == prompt_id)
 537                    {
 538                        picker.set_selected_index(ix, true, cx);
 539                    }
 540                }
 541            } else {
 542                picker.focus(cx);
 543            }
 544        });
 545        cx.notify();
 546    }
 547
 548    pub fn delete_prompt(&mut self, prompt_id: PromptId, cx: &mut ViewContext<Self>) {
 549        if let Some(metadata) = self.store.metadata(prompt_id) {
 550            let confirmation = cx.prompt(
 551                PromptLevel::Warning,
 552                &format!(
 553                    "Are you sure you want to delete {}",
 554                    metadata.title.unwrap_or("Untitled".into())
 555                ),
 556                None,
 557                &["Delete", "Cancel"],
 558            );
 559
 560            cx.spawn(|this, mut cx| async move {
 561                if confirmation.await.ok() == Some(0) {
 562                    this.update(&mut cx, |this, cx| {
 563                        if this.active_prompt_id == Some(prompt_id) {
 564                            this.set_active_prompt(None, cx);
 565                        }
 566                        this.prompt_editors.remove(&prompt_id);
 567                        this.store.delete(prompt_id).detach_and_log_err(cx);
 568                        this.picker.update(cx, |picker, cx| picker.refresh(cx));
 569                        cx.notify();
 570                    })?;
 571                }
 572                anyhow::Ok(())
 573            })
 574            .detach_and_log_err(cx);
 575        }
 576    }
 577
 578    pub fn duplicate_prompt(&mut self, prompt_id: PromptId, cx: &mut ViewContext<Self>) {
 579        if let Some(prompt) = self.prompt_editors.get(&prompt_id) {
 580            let new_id = PromptId::new();
 581            let title = prompt.title_editor.read(cx).text(cx);
 582            let body = prompt.body_editor.read(cx).text(cx);
 583            let save = self
 584                .store
 585                .save(new_id, Some(title.into()), false, body.into());
 586            self.picker.update(cx, |picker, cx| picker.refresh(cx));
 587            cx.spawn(|this, mut cx| async move {
 588                save.await?;
 589                this.update(&mut cx, |prompt_library, cx| {
 590                    prompt_library.load_prompt(new_id, true, cx)
 591                })
 592            })
 593            .detach_and_log_err(cx);
 594        }
 595    }
 596
 597    fn focus_active_prompt(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 598        if let Some(active_prompt) = self.active_prompt_id {
 599            self.prompt_editors[&active_prompt]
 600                .body_editor
 601                .update(cx, |editor, cx| editor.focus(cx));
 602            cx.stop_propagation();
 603        }
 604    }
 605
 606    fn focus_picker(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
 607        self.picker.update(cx, |picker, cx| picker.focus(cx));
 608    }
 609
 610    pub fn inline_assist(&mut self, _: &InlineAssist, cx: &mut ViewContext<Self>) {
 611        let Some(active_prompt_id) = self.active_prompt_id else {
 612            cx.propagate();
 613            return;
 614        };
 615
 616        let prompt_editor = &self.prompt_editors[&active_prompt_id].body_editor;
 617        let provider = CompletionProvider::global(cx);
 618        if provider.is_authenticated() {
 619            InlineAssistant::update_global(cx, |assistant, cx| {
 620                assistant.assist(&prompt_editor, None, None, cx)
 621            })
 622        } else {
 623            for window in cx.windows() {
 624                if let Some(workspace) = window.downcast::<Workspace>() {
 625                    let panel = workspace
 626                        .update(cx, |workspace, cx| {
 627                            cx.activate_window();
 628                            workspace.focus_panel::<AssistantPanel>(cx)
 629                        })
 630                        .ok()
 631                        .flatten();
 632                    if panel.is_some() {
 633                        return;
 634                    }
 635                }
 636            }
 637        }
 638    }
 639
 640    fn move_down_from_title(&mut self, _: &editor::actions::MoveDown, cx: &mut ViewContext<Self>) {
 641        if let Some(prompt_id) = self.active_prompt_id {
 642            if let Some(prompt_editor) = self.prompt_editors.get(&prompt_id) {
 643                cx.focus_view(&prompt_editor.body_editor);
 644            }
 645        }
 646    }
 647
 648    fn move_up_from_body(&mut self, _: &editor::actions::MoveUp, cx: &mut ViewContext<Self>) {
 649        if let Some(prompt_id) = self.active_prompt_id {
 650            if let Some(prompt_editor) = self.prompt_editors.get(&prompt_id) {
 651                cx.focus_view(&prompt_editor.title_editor);
 652            }
 653        }
 654    }
 655
 656    fn handle_prompt_title_editor_event(
 657        &mut self,
 658        prompt_id: PromptId,
 659        title_editor: View<Editor>,
 660        event: &EditorEvent,
 661        cx: &mut ViewContext<Self>,
 662    ) {
 663        match event {
 664            EditorEvent::BufferEdited => {
 665                self.save_prompt(prompt_id, cx);
 666                self.count_tokens(prompt_id, cx);
 667            }
 668            EditorEvent::Blurred => {
 669                title_editor.update(cx, |title_editor, cx| {
 670                    title_editor.change_selections(None, cx, |selections| {
 671                        let cursor = selections.oldest_anchor().head();
 672                        selections.select_anchor_ranges([cursor..cursor]);
 673                    });
 674                });
 675            }
 676            _ => {}
 677        }
 678    }
 679
 680    fn handle_prompt_body_editor_event(
 681        &mut self,
 682        prompt_id: PromptId,
 683        body_editor: View<Editor>,
 684        event: &EditorEvent,
 685        cx: &mut ViewContext<Self>,
 686    ) {
 687        match event {
 688            EditorEvent::BufferEdited => {
 689                self.save_prompt(prompt_id, cx);
 690                self.count_tokens(prompt_id, cx);
 691            }
 692            EditorEvent::Blurred => {
 693                body_editor.update(cx, |body_editor, cx| {
 694                    body_editor.change_selections(None, cx, |selections| {
 695                        let cursor = selections.oldest_anchor().head();
 696                        selections.select_anchor_ranges([cursor..cursor]);
 697                    });
 698                });
 699            }
 700            _ => {}
 701        }
 702    }
 703
 704    fn count_tokens(&mut self, prompt_id: PromptId, cx: &mut ViewContext<Self>) {
 705        if let Some(prompt) = self.prompt_editors.get_mut(&prompt_id) {
 706            let editor = &prompt.body_editor.read(cx);
 707            let buffer = &editor.buffer().read(cx).as_singleton().unwrap().read(cx);
 708            let body = buffer.as_rope().clone();
 709            prompt.pending_token_count = cx.spawn(|this, mut cx| {
 710                async move {
 711                    const DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
 712
 713                    cx.background_executor().timer(DEBOUNCE_TIMEOUT).await;
 714                    let token_count = cx
 715                        .update(|cx| {
 716                            let provider = CompletionProvider::global(cx);
 717                            let model = provider.model();
 718                            provider.count_tokens(
 719                                LanguageModelRequest {
 720                                    model,
 721                                    messages: vec![LanguageModelRequestMessage {
 722                                        role: Role::System,
 723                                        content: body.to_string(),
 724                                    }],
 725                                    stop: Vec::new(),
 726                                    temperature: 1.,
 727                                },
 728                                cx,
 729                            )
 730                        })?
 731                        .await?;
 732                    this.update(&mut cx, |this, cx| {
 733                        let prompt_editor = this.prompt_editors.get_mut(&prompt_id).unwrap();
 734                        prompt_editor.token_count = Some(token_count);
 735                        cx.notify();
 736                    })
 737                }
 738                .log_err()
 739            });
 740        }
 741    }
 742
 743    fn render_prompt_list(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 744        v_flex()
 745            .id("prompt-list")
 746            .capture_action(cx.listener(Self::focus_active_prompt))
 747            .bg(cx.theme().colors().panel_background)
 748            .h_full()
 749            .w_1_3()
 750            .overflow_x_hidden()
 751            .child(
 752                h_flex()
 753                    .p(Spacing::Small.rems(cx))
 754                    .h(TitleBar::height(cx))
 755                    .w_full()
 756                    .flex_none()
 757                    .justify_end()
 758                    .child(
 759                        IconButton::new("new-prompt", IconName::Plus)
 760                            .style(ButtonStyle::Transparent)
 761                            .shape(IconButtonShape::Square)
 762                            .tooltip(move |cx| Tooltip::for_action("New Prompt", &NewPrompt, cx))
 763                            .on_click(|_, cx| {
 764                                cx.dispatch_action(Box::new(NewPrompt));
 765                            }),
 766                    ),
 767            )
 768            .child(div().flex_grow().child(self.picker.clone()))
 769    }
 770
 771    fn render_active_prompt(&mut self, cx: &mut ViewContext<PromptLibrary>) -> gpui::Stateful<Div> {
 772        div()
 773            .w_2_3()
 774            .h_full()
 775            .id("prompt-editor")
 776            .border_l_1()
 777            .border_color(cx.theme().colors().border)
 778            .bg(cx.theme().colors().editor_background)
 779            .flex_none()
 780            .min_w_64()
 781            .children(self.active_prompt_id.and_then(|prompt_id| {
 782                let prompt_metadata = self.store.metadata(prompt_id)?;
 783                let prompt_editor = &self.prompt_editors[&prompt_id];
 784                let focus_handle = prompt_editor.body_editor.focus_handle(cx);
 785                let current_model = CompletionProvider::global(cx).model();
 786                let settings = ThemeSettings::get_global(cx);
 787
 788                Some(
 789                    v_flex()
 790                        .id("prompt-editor-inner")
 791                        .size_full()
 792                        .relative()
 793                        .overflow_hidden()
 794                        .pl(Spacing::XXLarge.rems(cx))
 795                        .pt(Spacing::Large.rems(cx))
 796                        .on_click(cx.listener(move |_, _, cx| {
 797                            cx.focus(&focus_handle);
 798                        }))
 799                        .child(
 800                            h_flex()
 801                                .group("active-editor-header")
 802                                .pr(Spacing::XXLarge.rems(cx))
 803                                .pt(Spacing::XSmall.rems(cx))
 804                                .pb(Spacing::Large.rems(cx))
 805                                .justify_between()
 806                                .child(
 807                                    h_flex().gap_1().child(
 808                                        div()
 809                                            .max_w_80()
 810                                            .on_action(cx.listener(Self::move_down_from_title))
 811                                            .border_1()
 812                                            .border_color(transparent_black())
 813                                            .rounded_md()
 814                                            .group_hover("active-editor-header", |this| {
 815                                                this.border_color(
 816                                                    cx.theme().colors().border_variant,
 817                                                )
 818                                            })
 819                                            .child(EditorElement::new(
 820                                                &prompt_editor.title_editor,
 821                                                EditorStyle {
 822                                                    background: cx.theme().system().transparent,
 823                                                    local_player: cx.theme().players().local(),
 824                                                    text: TextStyle {
 825                                                        color: cx
 826                                                            .theme()
 827                                                            .colors()
 828                                                            .editor_foreground,
 829                                                        font_family: settings
 830                                                            .ui_font
 831                                                            .family
 832                                                            .clone(),
 833                                                        font_features: settings
 834                                                            .ui_font
 835                                                            .features
 836                                                            .clone(),
 837                                                        font_size: HeadlineSize::Large
 838                                                            .size()
 839                                                            .into(),
 840                                                        font_weight: settings.ui_font.weight,
 841                                                        line_height: relative(
 842                                                            settings.buffer_line_height.value(),
 843                                                        ),
 844                                                        ..Default::default()
 845                                                    },
 846                                                    scrollbar_width: Pixels::ZERO,
 847                                                    syntax: cx.theme().syntax().clone(),
 848                                                    status: cx.theme().status().clone(),
 849                                                    inlay_hints_style: HighlightStyle {
 850                                                        color: Some(cx.theme().status().hint),
 851                                                        ..HighlightStyle::default()
 852                                                    },
 853                                                    suggestions_style: HighlightStyle {
 854                                                        color: Some(cx.theme().status().predictive),
 855                                                        ..HighlightStyle::default()
 856                                                    },
 857                                                },
 858                                            )),
 859                                    ),
 860                                )
 861                                .child(
 862                                    h_flex()
 863                                        .h_full()
 864                                        .child(
 865                                            h_flex()
 866                                                .h_full()
 867                                                .gap(Spacing::XXLarge.rems(cx))
 868                                                .child(div()),
 869                                        )
 870                                        .child(
 871                                            h_flex()
 872                                                .h_full()
 873                                                .gap(Spacing::XXLarge.rems(cx))
 874                                                .children(prompt_editor.token_count.map(
 875                                                    |token_count| {
 876                                                        let token_count: SharedString =
 877                                                            token_count.to_string().into();
 878                                                        let label_token_count: SharedString =
 879                                                            token_count.to_string().into();
 880
 881                                                        h_flex()
 882                                                            .id("token_count")
 883                                                            .tooltip(move |cx| {
 884                                                                let token_count =
 885                                                                    token_count.clone();
 886
 887                                                                Tooltip::with_meta(
 888                                                                    format!(
 889                                                                        "{} tokens",
 890                                                                        token_count.clone()
 891                                                                    ),
 892                                                                    None,
 893                                                                    format!(
 894                                                                        "Model: {}",
 895                                                                        current_model
 896                                                                            .display_name()
 897                                                                    ),
 898                                                                    cx,
 899                                                                )
 900                                                            })
 901                                                            .child(
 902                                                                Label::new(format!(
 903                                                                    "{} tokens",
 904                                                                    label_token_count.clone()
 905                                                                ))
 906                                                                .color(Color::Muted),
 907                                                            )
 908                                                    },
 909                                                ))
 910                                                .child(
 911                                                    IconButton::new(
 912                                                        "delete-prompt",
 913                                                        IconName::Trash,
 914                                                    )
 915                                                    .size(ButtonSize::Large)
 916                                                    .style(ButtonStyle::Transparent)
 917                                                    .shape(IconButtonShape::Square)
 918                                                    .size(ButtonSize::Large)
 919                                                    .tooltip(move |cx| {
 920                                                        Tooltip::for_action(
 921                                                            "Delete Prompt",
 922                                                            &DeletePrompt,
 923                                                            cx,
 924                                                        )
 925                                                    })
 926                                                    .on_click(|_, cx| {
 927                                                        cx.dispatch_action(Box::new(DeletePrompt));
 928                                                    }),
 929                                                )
 930                                                .child(
 931                                                    IconButton::new(
 932                                                        "duplicate-prompt",
 933                                                        IconName::BookCopy,
 934                                                    )
 935                                                    .size(ButtonSize::Large)
 936                                                    .style(ButtonStyle::Transparent)
 937                                                    .shape(IconButtonShape::Square)
 938                                                    .size(ButtonSize::Large)
 939                                                    .tooltip(move |cx| {
 940                                                        Tooltip::for_action(
 941                                                            "Duplicate Prompt",
 942                                                            &DuplicatePrompt,
 943                                                            cx,
 944                                                        )
 945                                                    })
 946                                                    .on_click(|_, cx| {
 947                                                        cx.dispatch_action(Box::new(
 948                                                            DuplicatePrompt,
 949                                                        ));
 950                                                    }),
 951                                                )
 952                                                .child(
 953                                                    IconButton::new(
 954                                                        "toggle-default-prompt",
 955                                                        IconName::Sparkle,
 956                                                    )
 957                                                    .style(ButtonStyle::Transparent)
 958                                                    .selected(prompt_metadata.default)
 959                                                    .selected_icon(IconName::SparkleFilled)
 960                                                    .icon_color(if prompt_metadata.default {
 961                                                        Color::Accent
 962                                                    } else {
 963                                                        Color::Muted
 964                                                    })
 965                                                    .shape(IconButtonShape::Square)
 966                                                    .size(ButtonSize::Large)
 967                                                    .tooltip(move |cx| {
 968                                                        Tooltip::text(
 969                                                            if prompt_metadata.default {
 970                                                                "Remove from Default Prompt"
 971                                                            } else {
 972                                                                "Add to Default Prompt"
 973                                                            },
 974                                                            cx,
 975                                                        )
 976                                                    })
 977                                                    .on_click(|_, cx| {
 978                                                        cx.dispatch_action(Box::new(
 979                                                            ToggleDefaultPrompt,
 980                                                        ));
 981                                                    }),
 982                                                ),
 983                                        ),
 984                                ),
 985                        )
 986                        .child(
 987                            div()
 988                                .on_action(cx.listener(Self::focus_picker))
 989                                .on_action(cx.listener(Self::inline_assist))
 990                                .on_action(cx.listener(Self::move_up_from_body))
 991                                .flex_grow()
 992                                .h_full()
 993                                .child(prompt_editor.body_editor.clone()),
 994                        ),
 995                )
 996            }))
 997    }
 998}
 999
1000impl Render for PromptLibrary {
1001    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1002        let ui_font = theme::setup_ui_font(cx);
1003        let theme = cx.theme().clone();
1004
1005        h_flex()
1006            .id("prompt-manager")
1007            .key_context("PromptLibrary")
1008            .on_action(cx.listener(|this, &NewPrompt, cx| this.new_prompt(cx)))
1009            .on_action(cx.listener(|this, &DeletePrompt, cx| this.delete_active_prompt(cx)))
1010            .on_action(cx.listener(|this, &DuplicatePrompt, cx| this.duplicate_active_prompt(cx)))
1011            .on_action(cx.listener(|this, &ToggleDefaultPrompt, cx| {
1012                this.toggle_default_for_active_prompt(cx)
1013            }))
1014            .size_full()
1015            .overflow_hidden()
1016            .font(ui_font)
1017            .text_color(theme.colors().text)
1018            .child(self.render_prompt_list(cx))
1019            .child(self.render_active_prompt(cx))
1020    }
1021}
1022
1023#[derive(Clone, Debug, Serialize, Deserialize)]
1024pub struct PromptMetadata {
1025    pub id: PromptId,
1026    pub title: Option<SharedString>,
1027    pub default: bool,
1028    pub saved_at: DateTime<Utc>,
1029}
1030
1031#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1032pub struct PromptId(Uuid);
1033
1034impl PromptId {
1035    pub fn new() -> PromptId {
1036        PromptId(Uuid::new_v4())
1037    }
1038}
1039
1040pub struct PromptStore {
1041    executor: BackgroundExecutor,
1042    env: heed::Env,
1043    bodies: Database<SerdeBincode<PromptId>, SerdeBincode<String>>,
1044    metadata: Database<SerdeBincode<PromptId>, SerdeBincode<PromptMetadata>>,
1045    metadata_cache: RwLock<MetadataCache>,
1046}
1047
1048#[derive(Default)]
1049struct MetadataCache {
1050    metadata: Vec<PromptMetadata>,
1051    metadata_by_id: HashMap<PromptId, PromptMetadata>,
1052}
1053
1054impl MetadataCache {
1055    fn from_db(
1056        db: Database<SerdeBincode<PromptId>, SerdeBincode<PromptMetadata>>,
1057        txn: &RoTxn,
1058    ) -> Result<Self> {
1059        let mut cache = MetadataCache::default();
1060        for result in db.iter(txn)? {
1061            let (prompt_id, metadata) = result?;
1062            cache.metadata.push(metadata.clone());
1063            cache.metadata_by_id.insert(prompt_id, metadata);
1064        }
1065        cache.sort();
1066        Ok(cache)
1067    }
1068
1069    fn insert(&mut self, metadata: PromptMetadata) {
1070        self.metadata_by_id.insert(metadata.id, metadata.clone());
1071        if let Some(old_metadata) = self.metadata.iter_mut().find(|m| m.id == metadata.id) {
1072            *old_metadata = metadata;
1073        } else {
1074            self.metadata.push(metadata);
1075        }
1076        self.sort();
1077    }
1078
1079    fn remove(&mut self, id: PromptId) {
1080        self.metadata.retain(|metadata| metadata.id != id);
1081        self.metadata_by_id.remove(&id);
1082    }
1083
1084    fn sort(&mut self) {
1085        self.metadata.sort_unstable_by(|a, b| {
1086            a.title
1087                .cmp(&b.title)
1088                .then_with(|| b.saved_at.cmp(&a.saved_at))
1089        });
1090    }
1091}
1092
1093impl PromptStore {
1094    pub fn global(cx: &AppContext) -> impl Future<Output = Result<Arc<Self>>> {
1095        let store = GlobalPromptStore::global(cx).0.clone();
1096        async move { store.await.map_err(|err| anyhow!(err)) }
1097    }
1098
1099    pub fn new(db_path: PathBuf, executor: BackgroundExecutor) -> Task<Result<Self>> {
1100        executor.spawn({
1101            let executor = executor.clone();
1102            async move {
1103                std::fs::create_dir_all(&db_path)?;
1104
1105                let db_env = unsafe {
1106                    heed::EnvOpenOptions::new()
1107                        .map_size(1024 * 1024 * 1024) // 1GB
1108                        .max_dbs(2) // bodies and metadata
1109                        .open(db_path)?
1110                };
1111
1112                let mut txn = db_env.write_txn()?;
1113                let bodies = db_env.create_database(&mut txn, Some("bodies"))?;
1114                let metadata = db_env.create_database(&mut txn, Some("metadata"))?;
1115                let metadata_cache = MetadataCache::from_db(metadata, &txn)?;
1116                txn.commit()?;
1117
1118                Ok(PromptStore {
1119                    executor,
1120                    env: db_env,
1121                    bodies,
1122                    metadata,
1123                    metadata_cache: RwLock::new(metadata_cache),
1124                })
1125            }
1126        })
1127    }
1128
1129    pub fn load(&self, id: PromptId) -> Task<Result<String>> {
1130        let env = self.env.clone();
1131        let bodies = self.bodies;
1132        self.executor.spawn(async move {
1133            let txn = env.read_txn()?;
1134            bodies
1135                .get(&txn, &id)?
1136                .ok_or_else(|| anyhow!("prompt not found"))
1137        })
1138    }
1139
1140    pub fn default_prompt_metadata(&self) -> Vec<PromptMetadata> {
1141        return self
1142            .metadata_cache
1143            .read()
1144            .metadata
1145            .iter()
1146            .filter(|metadata| metadata.default)
1147            .cloned()
1148            .collect::<Vec<_>>();
1149    }
1150
1151    pub fn delete(&self, id: PromptId) -> Task<Result<()>> {
1152        self.metadata_cache.write().remove(id);
1153
1154        let db_connection = self.env.clone();
1155        let bodies = self.bodies;
1156        let metadata = self.metadata;
1157
1158        self.executor.spawn(async move {
1159            let mut txn = db_connection.write_txn()?;
1160
1161            metadata.delete(&mut txn, &id)?;
1162            bodies.delete(&mut txn, &id)?;
1163
1164            txn.commit()?;
1165            Ok(())
1166        })
1167    }
1168
1169    fn metadata(&self, id: PromptId) -> Option<PromptMetadata> {
1170        self.metadata_cache.read().metadata_by_id.get(&id).cloned()
1171    }
1172
1173    pub fn id_for_title(&self, title: &str) -> Option<PromptId> {
1174        let metadata_cache = self.metadata_cache.read();
1175        let metadata = metadata_cache
1176            .metadata
1177            .iter()
1178            .find(|metadata| metadata.title.as_ref().map(|title| &***title) == Some(title))?;
1179        Some(metadata.id)
1180    }
1181
1182    pub fn search(&self, query: String) -> Task<Vec<PromptMetadata>> {
1183        let cached_metadata = self.metadata_cache.read().metadata.clone();
1184        let executor = self.executor.clone();
1185        self.executor.spawn(async move {
1186            let mut matches = if query.is_empty() {
1187                cached_metadata
1188            } else {
1189                let candidates = cached_metadata
1190                    .iter()
1191                    .enumerate()
1192                    .filter_map(|(ix, metadata)| {
1193                        Some(StringMatchCandidate::new(
1194                            ix,
1195                            metadata.title.as_ref()?.to_string(),
1196                        ))
1197                    })
1198                    .collect::<Vec<_>>();
1199                let matches = fuzzy::match_strings(
1200                    &candidates,
1201                    &query,
1202                    false,
1203                    100,
1204                    &AtomicBool::default(),
1205                    executor,
1206                )
1207                .await;
1208                matches
1209                    .into_iter()
1210                    .map(|mat| cached_metadata[mat.candidate_id].clone())
1211                    .collect()
1212            };
1213            matches.sort_by_key(|metadata| Reverse(metadata.default));
1214            matches
1215        })
1216    }
1217
1218    fn save(
1219        &self,
1220        id: PromptId,
1221        title: Option<SharedString>,
1222        default: bool,
1223        body: Rope,
1224    ) -> Task<Result<()>> {
1225        let prompt_metadata = PromptMetadata {
1226            id,
1227            title,
1228            default,
1229            saved_at: Utc::now(),
1230        };
1231        self.metadata_cache.write().insert(prompt_metadata.clone());
1232
1233        let db_connection = self.env.clone();
1234        let bodies = self.bodies;
1235        let metadata = self.metadata;
1236
1237        self.executor.spawn(async move {
1238            let mut txn = db_connection.write_txn()?;
1239
1240            metadata.put(&mut txn, &id, &prompt_metadata)?;
1241            bodies.put(&mut txn, &id, &body.to_string())?;
1242
1243            txn.commit()?;
1244
1245            Ok(())
1246        })
1247    }
1248
1249    fn save_metadata(
1250        &self,
1251        id: PromptId,
1252        title: Option<SharedString>,
1253        default: bool,
1254    ) -> Task<Result<()>> {
1255        let prompt_metadata = PromptMetadata {
1256            id,
1257            title,
1258            default,
1259            saved_at: Utc::now(),
1260        };
1261        self.metadata_cache.write().insert(prompt_metadata.clone());
1262
1263        let db_connection = self.env.clone();
1264        let metadata = self.metadata;
1265
1266        self.executor.spawn(async move {
1267            let mut txn = db_connection.write_txn()?;
1268            metadata.put(&mut txn, &id, &prompt_metadata)?;
1269            txn.commit()?;
1270
1271            Ok(())
1272        })
1273    }
1274
1275    fn first(&self) -> Option<PromptMetadata> {
1276        self.metadata_cache.read().metadata.first().cloned()
1277    }
1278}
1279
1280/// Wraps a shared future to a prompt store so it can be assigned as a context global.
1281pub struct GlobalPromptStore(
1282    Shared<BoxFuture<'static, Result<Arc<PromptStore>, Arc<anyhow::Error>>>>,
1283);
1284
1285impl Global for GlobalPromptStore {}