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: &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(|cx| PlatformTitleBar::new("rules-library-title-bar", cx)))
 418            } else {
 419                None
 420            },
 421            store,
 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        {
 462            self.load_rule(metadata.id, true, window, cx);
 463            return;
 464        }
 465
 466        let prompt_id = PromptId::new();
 467        let save = self.store.update(cx, |store, cx| {
 468            store.save(prompt_id, None, false, "".into(), cx)
 469        });
 470        self.picker
 471            .update(cx, |picker, cx| picker.refresh(window, cx));
 472        cx.spawn_in(window, async move |this, cx| {
 473            save.await?;
 474            this.update_in(cx, |this, window, cx| {
 475                this.load_rule(prompt_id, true, window, cx)
 476            })
 477        })
 478        .detach_and_log_err(cx);
 479    }
 480
 481    pub fn save_rule(&mut self, prompt_id: PromptId, window: &mut Window, cx: &mut Context<Self>) {
 482        const SAVE_THROTTLE: Duration = Duration::from_millis(500);
 483
 484        if prompt_id.is_built_in() {
 485            return;
 486        }
 487
 488        let rule_metadata = self.store.read(cx).metadata(prompt_id).unwrap();
 489        let rule_editor = self.rule_editors.get_mut(&prompt_id).unwrap();
 490        let title = rule_editor.title_editor.read(cx).text(cx);
 491        let body = rule_editor.body_editor.update(cx, |editor, cx| {
 492            editor
 493                .buffer()
 494                .read(cx)
 495                .as_singleton()
 496                .unwrap()
 497                .read(cx)
 498                .as_rope()
 499                .clone()
 500        });
 501
 502        let store = self.store.clone();
 503        let executor = cx.background_executor().clone();
 504
 505        rule_editor.next_title_and_body_to_save = Some((title, body));
 506        if rule_editor.pending_save.is_none() {
 507            rule_editor.pending_save = Some(cx.spawn_in(window, async move |this, cx| {
 508                async move {
 509                    loop {
 510                        let title_and_body = this.update(cx, |this, _| {
 511                            this.rule_editors
 512                                .get_mut(&prompt_id)?
 513                                .next_title_and_body_to_save
 514                                .take()
 515                        })?;
 516
 517                        if let Some((title, body)) = title_and_body {
 518                            let title = if title.trim().is_empty() {
 519                                None
 520                            } else {
 521                                Some(SharedString::from(title))
 522                            };
 523                            cx.update(|_window, cx| {
 524                                store.update(cx, |store, cx| {
 525                                    store.save(prompt_id, title, rule_metadata.default, body, cx)
 526                                })
 527                            })?
 528                            .await
 529                            .log_err();
 530                            this.update_in(cx, |this, window, cx| {
 531                                this.picker
 532                                    .update(cx, |picker, cx| picker.refresh(window, cx));
 533                                cx.notify();
 534                            })?;
 535
 536                            executor.timer(SAVE_THROTTLE).await;
 537                        } else {
 538                            break;
 539                        }
 540                    }
 541
 542                    this.update(cx, |this, _cx| {
 543                        if let Some(rule_editor) = this.rule_editors.get_mut(&prompt_id) {
 544                            rule_editor.pending_save = None;
 545                        }
 546                    })
 547                }
 548                .log_err()
 549                .await
 550            }));
 551        }
 552    }
 553
 554    pub fn delete_active_rule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 555        if let Some(active_rule_id) = self.active_rule_id {
 556            self.delete_rule(active_rule_id, window, cx);
 557        }
 558    }
 559
 560    pub fn duplicate_active_rule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 561        if let Some(active_rule_id) = self.active_rule_id {
 562            self.duplicate_rule(active_rule_id, window, cx);
 563        }
 564    }
 565
 566    pub fn toggle_default_for_active_rule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 567        if let Some(active_rule_id) = self.active_rule_id {
 568            self.toggle_default_for_rule(active_rule_id, window, cx);
 569        }
 570    }
 571
 572    pub fn toggle_default_for_rule(
 573        &mut self,
 574        prompt_id: PromptId,
 575        window: &mut Window,
 576        cx: &mut Context<Self>,
 577    ) {
 578        self.store.update(cx, move |store, cx| {
 579            if let Some(rule_metadata) = store.metadata(prompt_id) {
 580                store
 581                    .save_metadata(prompt_id, rule_metadata.title, !rule_metadata.default, cx)
 582                    .detach_and_log_err(cx);
 583            }
 584        });
 585        self.picker
 586            .update(cx, |picker, cx| picker.refresh(window, cx));
 587        cx.notify();
 588    }
 589
 590    pub fn load_rule(
 591        &mut self,
 592        prompt_id: PromptId,
 593        focus: bool,
 594        window: &mut Window,
 595        cx: &mut Context<Self>,
 596    ) {
 597        if let Some(rule_editor) = self.rule_editors.get(&prompt_id) {
 598            if focus {
 599                rule_editor
 600                    .body_editor
 601                    .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)));
 602            }
 603            self.set_active_rule(Some(prompt_id), window, cx);
 604        } else if let Some(rule_metadata) = self.store.read(cx).metadata(prompt_id) {
 605            let language_registry = self.language_registry.clone();
 606            let rule = self.store.read(cx).load(prompt_id, cx);
 607            let make_completion_provider = self.make_completion_provider.clone();
 608            self.pending_load = cx.spawn_in(window, async move |this, cx| {
 609                let rule = rule.await;
 610                let markdown = language_registry.language_for_name("Markdown").await;
 611                this.update_in(cx, |this, window, cx| match rule {
 612                    Ok(rule) => {
 613                        let title_editor = cx.new(|cx| {
 614                            let mut editor = Editor::single_line(window, cx);
 615                            editor.set_placeholder_text("Untitled", cx);
 616                            editor.set_text(rule_metadata.title.unwrap_or_default(), window, cx);
 617                            if prompt_id.is_built_in() {
 618                                editor.set_read_only(true);
 619                                editor.set_show_edit_predictions(Some(false), window, cx);
 620                            }
 621                            editor
 622                        });
 623                        let body_editor = cx.new(|cx| {
 624                            let buffer = cx.new(|cx| {
 625                                let mut buffer = Buffer::local(rule, cx);
 626                                buffer.set_language(markdown.log_err(), cx);
 627                                buffer.set_language_registry(language_registry);
 628                                buffer
 629                            });
 630
 631                            let mut editor = Editor::for_buffer(buffer, None, window, cx);
 632                            if prompt_id.is_built_in() {
 633                                editor.set_read_only(true);
 634                                editor.set_show_edit_predictions(Some(false), window, cx);
 635                            }
 636                            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
 637                            editor.set_show_gutter(false, cx);
 638                            editor.set_show_wrap_guides(false, cx);
 639                            editor.set_show_indent_guides(false, cx);
 640                            editor.set_use_modal_editing(false);
 641                            editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
 642                            editor.set_completion_provider(Some(make_completion_provider()));
 643                            if focus {
 644                                window.focus(&editor.focus_handle(cx));
 645                            }
 646                            editor
 647                        });
 648                        let _subscriptions = vec![
 649                            cx.subscribe_in(
 650                                &title_editor,
 651                                window,
 652                                move |this, editor, event, window, cx| {
 653                                    this.handle_rule_title_editor_event(
 654                                        prompt_id, editor, event, window, cx,
 655                                    )
 656                                },
 657                            ),
 658                            cx.subscribe_in(
 659                                &body_editor,
 660                                window,
 661                                move |this, editor, event, window, cx| {
 662                                    this.handle_rule_body_editor_event(
 663                                        prompt_id, editor, event, window, cx,
 664                                    )
 665                                },
 666                            ),
 667                        ];
 668                        this.rule_editors.insert(
 669                            prompt_id,
 670                            RuleEditor {
 671                                title_editor,
 672                                body_editor,
 673                                next_title_and_body_to_save: None,
 674                                pending_save: None,
 675                                token_count: None,
 676                                pending_token_count: Task::ready(None),
 677                                _subscriptions,
 678                            },
 679                        );
 680                        this.set_active_rule(Some(prompt_id), window, cx);
 681                        this.count_tokens(prompt_id, window, cx);
 682                    }
 683                    Err(error) => {
 684                        // TODO: we should show the error in the UI.
 685                        log::error!("error while loading rule: {:?}", error);
 686                    }
 687                })
 688                .ok();
 689            });
 690        }
 691    }
 692
 693    fn set_active_rule(
 694        &mut self,
 695        prompt_id: Option<PromptId>,
 696        window: &mut Window,
 697        cx: &mut Context<Self>,
 698    ) {
 699        self.active_rule_id = prompt_id;
 700        self.picker.update(cx, |picker, cx| {
 701            if let Some(prompt_id) = prompt_id {
 702                if picker
 703                    .delegate
 704                    .matches
 705                    .get(picker.delegate.selected_index())
 706                    .is_none_or(|old_selected_prompt| old_selected_prompt.id != prompt_id)
 707                    && let Some(ix) = picker
 708                        .delegate
 709                        .matches
 710                        .iter()
 711                        .position(|mat| mat.id == prompt_id)
 712                {
 713                    picker.set_selected_index(ix, None, true, window, cx);
 714                }
 715            } else {
 716                picker.focus(window, cx);
 717            }
 718        });
 719        cx.notify();
 720    }
 721
 722    pub fn delete_rule(
 723        &mut self,
 724        prompt_id: PromptId,
 725        window: &mut Window,
 726        cx: &mut Context<Self>,
 727    ) {
 728        if let Some(metadata) = self.store.read(cx).metadata(prompt_id) {
 729            let confirmation = window.prompt(
 730                PromptLevel::Warning,
 731                &format!(
 732                    "Are you sure you want to delete {}",
 733                    metadata.title.unwrap_or("Untitled".into())
 734                ),
 735                None,
 736                &["Delete", "Cancel"],
 737                cx,
 738            );
 739
 740            cx.spawn_in(window, async move |this, cx| {
 741                if confirmation.await.ok() == Some(0) {
 742                    this.update_in(cx, |this, window, cx| {
 743                        if this.active_rule_id == Some(prompt_id) {
 744                            this.set_active_rule(None, window, cx);
 745                        }
 746                        this.rule_editors.remove(&prompt_id);
 747                        this.store
 748                            .update(cx, |store, cx| store.delete(prompt_id, cx))
 749                            .detach_and_log_err(cx);
 750                        this.picker
 751                            .update(cx, |picker, cx| picker.refresh(window, cx));
 752                        cx.notify();
 753                    })?;
 754                }
 755                anyhow::Ok(())
 756            })
 757            .detach_and_log_err(cx);
 758        }
 759    }
 760
 761    pub fn duplicate_rule(
 762        &mut self,
 763        prompt_id: PromptId,
 764        window: &mut Window,
 765        cx: &mut Context<Self>,
 766    ) {
 767        if let Some(rule) = self.rule_editors.get(&prompt_id) {
 768            const DUPLICATE_SUFFIX: &str = " copy";
 769            let title_to_duplicate = rule.title_editor.read(cx).text(cx);
 770            let existing_titles = self
 771                .rule_editors
 772                .iter()
 773                .filter(|&(&id, _)| id != prompt_id)
 774                .map(|(_, rule_editor)| rule_editor.title_editor.read(cx).text(cx))
 775                .filter(|title| title.starts_with(&title_to_duplicate))
 776                .collect::<HashSet<_>>();
 777
 778            let title = if existing_titles.is_empty() {
 779                title_to_duplicate + DUPLICATE_SUFFIX
 780            } else {
 781                let mut i = 1;
 782                loop {
 783                    let new_title = format!("{title_to_duplicate}{DUPLICATE_SUFFIX} {i}");
 784                    if !existing_titles.contains(&new_title) {
 785                        break new_title;
 786                    }
 787                    i += 1;
 788                }
 789            };
 790
 791            let new_id = PromptId::new();
 792            let body = rule.body_editor.read(cx).text(cx);
 793            let save = self.store.update(cx, |store, cx| {
 794                store.save(new_id, Some(title.into()), false, body.into(), cx)
 795            });
 796            self.picker
 797                .update(cx, |picker, cx| picker.refresh(window, cx));
 798            cx.spawn_in(window, async move |this, cx| {
 799                save.await?;
 800                this.update_in(cx, |rules_library, window, cx| {
 801                    rules_library.load_rule(new_id, true, window, cx)
 802                })
 803            })
 804            .detach_and_log_err(cx);
 805        }
 806    }
 807
 808    fn focus_active_rule(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 809        if let Some(active_rule) = self.active_rule_id {
 810            self.rule_editors[&active_rule]
 811                .body_editor
 812                .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)));
 813            cx.stop_propagation();
 814        }
 815    }
 816
 817    fn focus_picker(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 818        self.picker
 819            .update(cx, |picker, cx| picker.focus(window, cx));
 820    }
 821
 822    pub fn inline_assist(
 823        &mut self,
 824        action: &InlineAssist,
 825        window: &mut Window,
 826        cx: &mut Context<Self>,
 827    ) {
 828        let Some(active_rule_id) = self.active_rule_id else {
 829            cx.propagate();
 830            return;
 831        };
 832
 833        let rule_editor = &self.rule_editors[&active_rule_id].body_editor;
 834        let Some(ConfiguredModel { provider, .. }) =
 835            LanguageModelRegistry::read_global(cx).inline_assistant_model()
 836        else {
 837            return;
 838        };
 839
 840        let initial_prompt = action.prompt.clone();
 841        if provider.is_authenticated(cx) {
 842            self.inline_assist_delegate
 843                .assist(rule_editor, initial_prompt, window, cx);
 844        } else {
 845            for window in cx.windows() {
 846                if let Some(workspace) = window.downcast::<Workspace>() {
 847                    let panel = workspace
 848                        .update(cx, |workspace, window, cx| {
 849                            window.activate_window();
 850                            self.inline_assist_delegate
 851                                .focus_agent_panel(workspace, window, cx)
 852                        })
 853                        .ok();
 854                    if panel == Some(true) {
 855                        return;
 856                    }
 857                }
 858            }
 859        }
 860    }
 861
 862    fn move_down_from_title(
 863        &mut self,
 864        _: &editor::actions::MoveDown,
 865        window: &mut Window,
 866        cx: &mut Context<Self>,
 867    ) {
 868        if let Some(rule_id) = self.active_rule_id
 869            && let Some(rule_editor) = self.rule_editors.get(&rule_id)
 870        {
 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        {
 884            window.focus(&rule_editor.title_editor.focus_handle(cx));
 885        }
 886    }
 887
 888    fn handle_rule_title_editor_event(
 889        &mut self,
 890        prompt_id: PromptId,
 891        title_editor: &Entity<Editor>,
 892        event: &EditorEvent,
 893        window: &mut Window,
 894        cx: &mut Context<Self>,
 895    ) {
 896        match event {
 897            EditorEvent::BufferEdited => {
 898                self.save_rule(prompt_id, window, cx);
 899                self.count_tokens(prompt_id, window, cx);
 900            }
 901            EditorEvent::Blurred => {
 902                title_editor.update(cx, |title_editor, cx| {
 903                    title_editor.change_selections(
 904                        SelectionEffects::no_scroll(),
 905                        window,
 906                        cx,
 907                        |selections| {
 908                            let cursor = selections.oldest_anchor().head();
 909                            selections.select_anchor_ranges([cursor..cursor]);
 910                        },
 911                    );
 912                });
 913            }
 914            _ => {}
 915        }
 916    }
 917
 918    fn handle_rule_body_editor_event(
 919        &mut self,
 920        prompt_id: PromptId,
 921        body_editor: &Entity<Editor>,
 922        event: &EditorEvent,
 923        window: &mut Window,
 924        cx: &mut Context<Self>,
 925    ) {
 926        match event {
 927            EditorEvent::BufferEdited => {
 928                self.save_rule(prompt_id, window, cx);
 929                self.count_tokens(prompt_id, window, cx);
 930            }
 931            EditorEvent::Blurred => {
 932                body_editor.update(cx, |body_editor, cx| {
 933                    body_editor.change_selections(
 934                        SelectionEffects::no_scroll(),
 935                        window,
 936                        cx,
 937                        |selections| {
 938                            let cursor = selections.oldest_anchor().head();
 939                            selections.select_anchor_ranges([cursor..cursor]);
 940                        },
 941                    );
 942                });
 943            }
 944            _ => {}
 945        }
 946    }
 947
 948    fn count_tokens(&mut self, prompt_id: PromptId, window: &mut Window, cx: &mut Context<Self>) {
 949        let Some(ConfiguredModel { model, .. }) =
 950            LanguageModelRegistry::read_global(cx).default_model()
 951        else {
 952            return;
 953        };
 954        if let Some(rule) = self.rule_editors.get_mut(&prompt_id) {
 955            let editor = &rule.body_editor.read(cx);
 956            let buffer = &editor.buffer().read(cx).as_singleton().unwrap().read(cx);
 957            let body = buffer.as_rope().clone();
 958            rule.pending_token_count = cx.spawn_in(window, async move |this, cx| {
 959                async move {
 960                    const DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
 961
 962                    cx.background_executor().timer(DEBOUNCE_TIMEOUT).await;
 963                    let token_count = cx
 964                        .update(|_, cx| {
 965                            model.count_tokens(
 966                                LanguageModelRequest {
 967                                    thread_id: None,
 968                                    prompt_id: None,
 969                                    intent: None,
 970                                    mode: None,
 971                                    messages: vec![LanguageModelRequestMessage {
 972                                        role: Role::System,
 973                                        content: vec![body.to_string().into()],
 974                                        cache: false,
 975                                    }],
 976                                    tools: Vec::new(),
 977                                    tool_choice: None,
 978                                    stop: Vec::new(),
 979                                    temperature: None,
 980                                    thinking_allowed: true,
 981                                },
 982                                cx,
 983                            )
 984                        })?
 985                        .await?;
 986
 987                    this.update(cx, |this, cx| {
 988                        let rule_editor = this.rule_editors.get_mut(&prompt_id).unwrap();
 989                        rule_editor.token_count = Some(token_count);
 990                        cx.notify();
 991                    })
 992                }
 993                .log_err()
 994                .await
 995            });
 996        }
 997    }
 998
 999    fn render_rule_list(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
1000        v_flex()
1001            .id("rule-list")
1002            .capture_action(cx.listener(Self::focus_active_rule))
1003            .bg(cx.theme().colors().panel_background)
1004            .h_full()
1005            .px_1()
1006            .w_1_3()
1007            .overflow_x_hidden()
1008            .child(
1009                h_flex()
1010                    .p(DynamicSpacing::Base04.rems(cx))
1011                    .h_9()
1012                    .w_full()
1013                    .flex_none()
1014                    .justify_end()
1015                    .child(
1016                        IconButton::new("new-rule", IconName::Plus)
1017                            .style(ButtonStyle::Transparent)
1018                            .shape(IconButtonShape::Square)
1019                            .tooltip(move |window, cx| {
1020                                Tooltip::for_action("New Rule", &NewRule, window, cx)
1021                            })
1022                            .on_click(|_, window, cx| {
1023                                window.dispatch_action(Box::new(NewRule), cx);
1024                            }),
1025                    ),
1026            )
1027            .child(div().flex_grow().child(self.picker.clone()))
1028    }
1029
1030    fn render_active_rule(&mut self, cx: &mut Context<RulesLibrary>) -> gpui::Stateful<Div> {
1031        div()
1032            .w_2_3()
1033            .h_full()
1034            .id("rule-editor")
1035            .border_l_1()
1036            .border_color(cx.theme().colors().border)
1037            .bg(cx.theme().colors().editor_background)
1038            .flex_none()
1039            .min_w_64()
1040            .children(self.active_rule_id.and_then(|prompt_id| {
1041                let rule_metadata = self.store.read(cx).metadata(prompt_id)?;
1042                let rule_editor = &self.rule_editors[&prompt_id];
1043                let focus_handle = rule_editor.body_editor.focus_handle(cx);
1044                let model = LanguageModelRegistry::read_global(cx)
1045                    .default_model()
1046                    .map(|default| default.model);
1047                let settings = ThemeSettings::get_global(cx);
1048
1049                Some(
1050                    v_flex()
1051                        .id("rule-editor-inner")
1052                        .size_full()
1053                        .relative()
1054                        .overflow_hidden()
1055                        .on_click(cx.listener(move |_, _, window, _| {
1056                            window.focus(&focus_handle);
1057                        }))
1058                        .child(
1059                            h_flex()
1060                                .group("active-editor-header")
1061                                .pt_2()
1062                                .px_2p5()
1063                                .gap_2()
1064                                .justify_between()
1065                                .child(
1066                                    div()
1067                                        .w_full()
1068                                        .on_action(cx.listener(Self::move_down_from_title))
1069                                        .border_1()
1070                                        .border_color(transparent_black())
1071                                        .rounded_sm()
1072                                        .group_hover("active-editor-header", |this| {
1073                                            this.border_color(cx.theme().colors().border_variant)
1074                                        })
1075                                        .child(EditorElement::new(
1076                                            &rule_editor.title_editor,
1077                                            EditorStyle {
1078                                                background: cx.theme().system().transparent,
1079                                                local_player: cx.theme().players().local(),
1080                                                text: TextStyle {
1081                                                    color: cx.theme().colors().editor_foreground,
1082                                                    font_family: settings.ui_font.family.clone(),
1083                                                    font_features: settings
1084                                                        .ui_font
1085                                                        .features
1086                                                        .clone(),
1087                                                    font_size: HeadlineSize::Large.rems().into(),
1088                                                    font_weight: settings.ui_font.weight,
1089                                                    line_height: relative(
1090                                                        settings.buffer_line_height.value(),
1091                                                    ),
1092                                                    ..Default::default()
1093                                                },
1094                                                scrollbar_width: Pixels::ZERO,
1095                                                syntax: cx.theme().syntax().clone(),
1096                                                status: cx.theme().status().clone(),
1097                                                inlay_hints_style: editor::make_inlay_hints_style(
1098                                                    cx,
1099                                                ),
1100                                                edit_prediction_styles:
1101                                                    editor::make_suggestion_styles(cx),
1102                                                ..EditorStyle::default()
1103                                            },
1104                                        )),
1105                                )
1106                                .child(
1107                                    h_flex()
1108                                        .h_full()
1109                                        .flex_shrink_0()
1110                                        .gap(DynamicSpacing::Base04.rems(cx))
1111                                        .children(rule_editor.token_count.map(|token_count| {
1112                                            let token_count: SharedString =
1113                                                token_count.to_string().into();
1114                                            let label_token_count: SharedString =
1115                                                token_count.to_string().into();
1116
1117                                            div()
1118                                                .id("token_count")
1119                                                .mr_1()
1120                                                .flex_shrink_0()
1121                                                .tooltip(move |window, cx| {
1122                                                    Tooltip::with_meta(
1123                                                        "Token Estimation",
1124                                                        None,
1125                                                        format!(
1126                                                            "Model: {}",
1127                                                            model
1128                                                                .as_ref()
1129                                                                .map(|model| model.name().0)
1130                                                                .unwrap_or_default()
1131                                                        ),
1132                                                        window,
1133                                                        cx,
1134                                                    )
1135                                                })
1136                                                .child(
1137                                                    Label::new(format!(
1138                                                        "{} tokens",
1139                                                        label_token_count
1140                                                    ))
1141                                                    .color(Color::Muted),
1142                                                )
1143                                        }))
1144                                        .child(if prompt_id.is_built_in() {
1145                                            div()
1146                                                .id("built-in-rule")
1147                                                .child(
1148                                                    Icon::new(IconName::FileLock)
1149                                                        .color(Color::Muted),
1150                                                )
1151                                                .tooltip(move |window, cx| {
1152                                                    Tooltip::with_meta(
1153                                                        "Built-in rule",
1154                                                        None,
1155                                                        BUILT_IN_TOOLTIP_TEXT,
1156                                                        window,
1157                                                        cx,
1158                                                    )
1159                                                })
1160                                                .into_any()
1161                                        } else {
1162                                            IconButton::new("delete-rule", IconName::Trash)
1163                                                .icon_size(IconSize::Small)
1164                                                .tooltip(move |window, cx| {
1165                                                    Tooltip::for_action(
1166                                                        "Delete Rule",
1167                                                        &DeleteRule,
1168                                                        window,
1169                                                        cx,
1170                                                    )
1171                                                })
1172                                                .on_click(|_, window, cx| {
1173                                                    window
1174                                                        .dispatch_action(Box::new(DeleteRule), cx);
1175                                                })
1176                                                .into_any_element()
1177                                        })
1178                                        .child(
1179                                            IconButton::new("duplicate-rule", IconName::BookCopy)
1180                                                .icon_size(IconSize::Small)
1181                                                .tooltip(move |window, cx| {
1182                                                    Tooltip::for_action(
1183                                                        "Duplicate Rule",
1184                                                        &DuplicateRule,
1185                                                        window,
1186                                                        cx,
1187                                                    )
1188                                                })
1189                                                .on_click(|_, window, cx| {
1190                                                    window.dispatch_action(
1191                                                        Box::new(DuplicateRule),
1192                                                        cx,
1193                                                    );
1194                                                }),
1195                                        )
1196                                        .child(
1197                                            IconButton::new("toggle-default-rule", IconName::Star)
1198                                                .icon_size(IconSize::Small)
1199                                                .toggle_state(rule_metadata.default)
1200                                                .selected_icon(IconName::StarFilled)
1201                                                .icon_color(if rule_metadata.default {
1202                                                    Color::Accent
1203                                                } else {
1204                                                    Color::Muted
1205                                                })
1206                                                .map(|this| {
1207                                                    if rule_metadata.default {
1208                                                        this.tooltip(Tooltip::text(
1209                                                            "Remove from Default Rules",
1210                                                        ))
1211                                                    } else {
1212                                                        this.tooltip(move |window, cx| {
1213                                                            Tooltip::with_meta(
1214                                                                "Add to Default Rules",
1215                                                                None,
1216                                                                "Always included in every thread.",
1217                                                                window,
1218                                                                cx,
1219                                                            )
1220                                                        })
1221                                                    }
1222                                                })
1223                                                .on_click(|_, window, cx| {
1224                                                    window.dispatch_action(
1225                                                        Box::new(ToggleDefaultRule),
1226                                                        cx,
1227                                                    );
1228                                                }),
1229                                        ),
1230                                ),
1231                        )
1232                        .child(
1233                            div()
1234                                .on_action(cx.listener(Self::focus_picker))
1235                                .on_action(cx.listener(Self::inline_assist))
1236                                .on_action(cx.listener(Self::move_up_from_body))
1237                                .flex_grow()
1238                                .h_full()
1239                                .child(
1240                                    h_flex()
1241                                        .py_2()
1242                                        .pl_2p5()
1243                                        .h_full()
1244                                        .flex_1()
1245                                        .child(rule_editor.body_editor.clone()),
1246                                ),
1247                        ),
1248                )
1249            }))
1250    }
1251}
1252
1253impl Render for RulesLibrary {
1254    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1255        let ui_font = theme::setup_ui_font(window, cx);
1256        let theme = cx.theme().clone();
1257
1258        client_side_decorations(
1259            v_flex()
1260                .id("rules-library")
1261                .key_context("PromptLibrary")
1262                .on_action(cx.listener(|this, &NewRule, window, cx| this.new_rule(window, cx)))
1263                .on_action(
1264                    cx.listener(|this, &DeleteRule, window, cx| {
1265                        this.delete_active_rule(window, cx)
1266                    }),
1267                )
1268                .on_action(cx.listener(|this, &DuplicateRule, window, cx| {
1269                    this.duplicate_active_rule(window, cx)
1270                }))
1271                .on_action(cx.listener(|this, &ToggleDefaultRule, window, cx| {
1272                    this.toggle_default_for_active_rule(window, cx)
1273                }))
1274                .size_full()
1275                .overflow_hidden()
1276                .font(ui_font)
1277                .text_color(theme.colors().text)
1278                .children(self.title_bar.clone())
1279                .child(
1280                    h_flex()
1281                        .flex_1()
1282                        .child(self.render_rule_list(cx))
1283                        .map(|el| {
1284                            if self.store.read(cx).prompt_count() == 0 {
1285                                el.child(
1286                                    v_flex()
1287                                        .w_2_3()
1288                                        .h_full()
1289                                        .items_center()
1290                                        .justify_center()
1291                                        .gap_4()
1292                                        .bg(cx.theme().colors().editor_background)
1293                                        .child(
1294                                            h_flex()
1295                                                .gap_2()
1296                                                .child(
1297                                                    Icon::new(IconName::Book)
1298                                                        .size(IconSize::Medium)
1299                                                        .color(Color::Muted),
1300                                                )
1301                                                .child(
1302                                                    Label::new("No rules yet")
1303                                                        .size(LabelSize::Large)
1304                                                        .color(Color::Muted),
1305                                                ),
1306                                        )
1307                                        .child(
1308                                            h_flex()
1309                                                .child(h_flex())
1310                                                .child(
1311                                                    v_flex()
1312                                                        .gap_1()
1313                                                        .child(Label::new(
1314                                                            "Create your first rule:",
1315                                                        ))
1316                                                        .child(
1317                                                            Button::new("create-rule", "New Rule")
1318                                                                .full_width()
1319                                                                .key_binding(
1320                                                                    KeyBinding::for_action(
1321                                                                        &NewRule, window, cx,
1322                                                                    ),
1323                                                                )
1324                                                                .on_click(|_, window, cx| {
1325                                                                    window.dispatch_action(
1326                                                                        NewRule.boxed_clone(),
1327                                                                        cx,
1328                                                                    )
1329                                                                }),
1330                                                        ),
1331                                                )
1332                                                .child(h_flex()),
1333                                        ),
1334                                )
1335                            } else {
1336                                el.child(self.render_active_rule(cx))
1337                            }
1338                        }),
1339                ),
1340            window,
1341            cx,
1342        )
1343    }
1344}