rules_library.rs

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