Skip to content

A platform for community discussion. Free, open, simple.

19.8 KB
Raw Blame
# frozen_string_literal: true

RSpec.describe "AI Composer helper" do
  fab!(:user) { Fabricate(:admin, refresh_auto_groups: true) }
  fab!(:non_member_group, :group)
  fab!(:embedding_definition)

  fab!(:custom_prompts_agent) do
    Fabricate(:ai_agent, allowed_group_ids: [Group::AUTO_GROUPS[:admins]])
  end

  before do
    enable_current_plugin
    Group.find_by(id: Group::AUTO_GROUPS[:admins]).add(user)
    assign_fake_provider_to(:ai_default_llm_model)
    SiteSetting.ai_helper_custom_prompt_agent = custom_prompts_agent.id
    DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
    SiteSetting.ai_helper_enabled = true
    DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
    Jobs.run_immediately!
    sign_in(user)
  end

  after { DiscourseAi::AiHelper::Assistant.clear_prompt_cache! }

  let(:input) { "The rain in spain stays mainly in the Plane." }
  let(:composer) { PageObjects::Components::Composer.new }
  let(:ai_helper_menu) { PageObjects::Components::AiComposerHelperMenu.new }
  let(:diff_modal) { PageObjects::Modals::DiffModal.new }
  let(:ai_suggestion_dropdown) { PageObjects::Components::AiSuggestionDropdown.new }
  let(:toasts) { PageObjects::Components::Toasts.new }
  let(:topic_page) { PageObjects::Pages::Topic.new }

  fab!(:category)
  fab!(:category_2, :category)
  fab!(:video, :tag)
  fab!(:music, :tag)
  fab!(:cloud, :tag)
  fab!(:feedback, :tag)
  fab!(:review, :tag)
  fab!(:topic) { Fabricate(:topic, category: category, tags: [video, music]) }
  fab!(:post) do
    Fabricate(
      :post,
      topic: topic,
      raw:
        "I like to eat pie. It is a very good dessert. Some people are wasteful by throwing pie at others but I do not do that. I always eat the pie.",
    )
  end

  def trigger_composer_helper(content)
    visit("/latest")
    page.find("#create-topic").click
    composer.fill_content(content)
    composer.click_toolbar_button("ai-helper-trigger")
  end

  context "when triggering composer AI helper" do
    it "shows the context menu when clicking the AI button in the composer toolbar" do
      trigger_composer_helper(input)
      expect(ai_helper_menu).to have_context_menu
    end

    it "shows a toast error when clicking the AI button without content" do
      trigger_composer_helper("")
      expect(ai_helper_menu).to have_no_context_menu
      expect(toasts).to have_error(I18n.t("js.discourse_ai.ai_helper.no_content_error"))
    end

    it "shows prompt options in menu when AI button is clicked" do
      trigger_composer_helper(input)
      expect(ai_helper_menu).to be_showing_options
    end

    context "when using custom prompt" do
      let(:mode) { DiscourseAi::AiHelper::Assistant::CUSTOM_PROMPT }

      let(:custom_prompt_input) { "Translate to French" }
      let(:custom_prompt_response) { "La pluie en Espagne reste principalement dans l'avion." }

      it "shows custom prompt option" do
        trigger_composer_helper(input)
        expect(ai_helper_menu).to have_custom_prompt
      end

      it "enables the custom prompt button when input is filled" do
        trigger_composer_helper(input)
        expect(ai_helper_menu).to have_custom_prompt_button_disabled
        ai_helper_menu.fill_custom_prompt(custom_prompt_input)
        expect(ai_helper_menu).to have_custom_prompt_button_enabled
      end

      it "replaces the composed message with AI generated content" do
        trigger_composer_helper(input)
        ai_helper_menu.fill_custom_prompt(custom_prompt_input)

        DiscourseAi::Completions::Llm.with_prepared_responses([custom_prompt_response]) do
          ai_helper_menu.click_custom_prompt_button
          diff_modal.confirm_changes
          wait_for { composer.composer_input.value == custom_prompt_response }
          expect(composer.composer_input.value).to eq(custom_prompt_response)
        end
      end
    end

    context "when not a member of custom prompt group" do
      let(:mode) { DiscourseAi::AiHelper::Assistant::CUSTOM_PROMPT }

      before { custom_prompts_agent.update!(allowed_group_ids: [non_member_group.id]) }

      it "does not show custom prompt option" do
        trigger_composer_helper(input)
        expect(ai_helper_menu).to have_no_custom_prompt
      end
    end

    context "when using translation mode" do
      let(:mode) { DiscourseAi::AiHelper::Assistant::TRANSLATE }

      let(:spanish_input) { "La lluvia en España se queda principalmente en el avión." }

      it "replaces the composed message with AI generated content" do
        trigger_composer_helper(spanish_input)

        DiscourseAi::Completions::Llm.with_prepared_responses([input]) do
          ai_helper_menu.select_helper_model(mode)
          diff_modal.confirm_changes
          wait_for { composer.composer_input.value == input }
          expect(composer.composer_input.value).to eq(input)
        end
      end

      it "reverts results when Ctrl/Cmd + Z is pressed on the keyboard" do
        trigger_composer_helper(spanish_input)

        DiscourseAi::Completions::Llm.with_prepared_responses([input]) do
          ai_helper_menu.select_helper_model(mode)
          diff_modal.confirm_changes
          wait_for { composer.composer_input.value == input }
          ai_helper_menu.press_undo_keys
          expect(composer.composer_input.value).to eq(spanish_input)
        end
      end

      it "shows the changes in a modal" do
        trigger_composer_helper(spanish_input)

        DiscourseAi::Completions::Llm.with_prepared_responses([input]) do
          ai_helper_menu.select_helper_model(mode)

          expect(diff_modal).to be_visible
          expect(diff_modal.old_value).to eq(spanish_input.gsub(/[[:space:]]+/, " ").strip)
          expect(diff_modal.new_value).to eq(
            input.gsub(/[[:space:]]+/, " ").gsub(/[‘’]/, "'").gsub(/[“”]/, '"').strip,
          )
          diff_modal.confirm_changes
          expect(ai_helper_menu).to have_no_context_menu
        end
      end

      it "does not apply the changes when discard button is pressed in the modal" do
        trigger_composer_helper(spanish_input)
        DiscourseAi::Completions::Llm.with_prepared_responses([input]) do
          ai_helper_menu.select_helper_model(mode)
          expect(diff_modal).to be_visible
          diff_modal.discard_changes
          expect(ai_helper_menu).to have_no_context_menu
          expect(composer.composer_input.value).to eq(spanish_input)
        end
      end
    end

    context "when using the proofreading mode" do
      let(:mode) { DiscourseAi::AiHelper::Assistant::PROOFREAD }

      let(:proofread_text) { "The rain in Spain, stays mainly in the Plane." }

      it "replaces the composed message with AI generated content" do
        trigger_composer_helper(input)

        DiscourseAi::Completions::Llm.with_prepared_responses([proofread_text]) do
          ai_helper_menu.select_helper_model(mode)
          diff_modal.confirm_changes
          wait_for { composer.composer_input.value == proofread_text }
          expect(composer.composer_input.value).to eq(proofread_text)
        end
      end

      it "replaces selected formatted content from rich editor as markdown" do
        visit("/latest")
        page.find("#create-topic").click

        composer.toggle_rich_editor
        expect(composer).to have_rich_editor_active

        composer.focus
        composer.type_content("This is **bld text** and *itlic text* with `cde`.")

        composer.select_all

        composer.click_toolbar_button("ai-helper-trigger")
        expect(ai_helper_menu).to have_context_menu

        proofread_text = "This is **bold text** and *italic text* with `code`."

        DiscourseAi::Completions::Llm.with_prepared_responses([proofread_text]) do
          ai_helper_menu.select_helper_model(mode)
          diff_modal.confirm_changes

          composer.toggle_rich_editor
          expect(composer).to have_no_rich_editor_active

          wait_for { composer.composer_input.value == proofread_text }
          expect(composer.composer_input.value).to eq(proofread_text)
        end
      end

      it "applies confirmed changes directly in the rich text editor" do
        visit("/latest")
        page.find("#create-topic").click

        composer.toggle_rich_editor
        expect(composer).to have_rich_editor_active

        composer.focus
        composer.type_content(input)

        composer.click_toolbar_button("ai-helper-trigger")
        expect(ai_helper_menu).to have_context_menu

        DiscourseAi::Completions::Llm.with_prepared_responses([proofread_text]) do
          ai_helper_menu.select_helper_model(mode)
          expect(diff_modal).to have_diff("spain", "Spain,")
          diff_modal.confirm_changes
          expect(composer.rich_editor).to have_css("p", text: proofread_text)
          expect(composer.rich_editor).to have_no_text(input)
        end
      end
    end
  end

  context "when suggesting titles from the AI helper menu" do
    let(:mode) { DiscourseAi::AiHelper::Assistant::GENERATE_TITLES }

    let(:titles) do
      {
        output: [
          "Rainy Spain",
          "Plane-Bound Delights",
          "Mysterious Spain",
          "Plane-Rain Chronicles",
          "Unveiling Spain",
        ],
      }
    end

    it "opens a dropdown with title suggestions" do
      trigger_composer_helper(input)
      DiscourseAi::Completions::Llm.with_prepared_responses([titles]) do
        ai_helper_menu.select_helper_model(mode)

        wait_for { ai_suggestion_dropdown.has_dropdown? }

        expect(ai_suggestion_dropdown).to have_dropdown
      end
    end

    it "replaces the topic title with the selected title" do
      trigger_composer_helper(input)
      DiscourseAi::Completions::Llm.with_prepared_responses([titles]) do
        ai_helper_menu.select_helper_model(mode)
        wait_for { ai_suggestion_dropdown.has_dropdown? }
        ai_suggestion_dropdown.select_suggestion_by_value(1)

        expect(page).to have_field("reply-title", with: "Plane-Bound Delights")
      end
    end

    it "closes the dropdown when clicking outside" do
      trigger_composer_helper(input)
      DiscourseAi::Completions::Llm.with_prepared_responses([titles]) do
        ai_helper_menu.select_helper_model(mode)

        wait_for { ai_suggestion_dropdown.has_dropdown? }

        find(".d-editor-preview").click

        expect(ai_suggestion_dropdown).to have_no_dropdown
      end
    end

    it "only offers title suggestions when there is sufficient content in the composer" do
      trigger_composer_helper("abc")

      expect(ai_helper_menu).to have_context_menu
      expect(ai_helper_menu).to have_no_option(mode)

      ai_helper_menu.press_escape_key
      composer.fill_content(input)
      composer.click_toolbar_button("ai-helper-trigger")

      expect(ai_helper_menu).to have_option(mode)
    end
  end

  context "when suggesting a category inline when editing a topic" do
    let(:edit_category_chooser) do
      PageObjects::Components::SelectKit.new(".edit-category__wrapper .category-chooser")
    end

    before do
      SiteSetting.ai_embeddings_selected_model = embedding_definition.id
      SiteSetting.ai_embeddings_enabled = true
      stub_request(:post, embedding_definition.url).to_return(
        status: 200,
        body: JSON.dump([[0.0038493] * embedding_definition.dimensions]),
      )
    end

    it "applies the best suggestion and closes the dropdown" do
      response = [
        {
          id: category_2.id,
          name: category_2.name,
          slug: category_2.slug,
          color: category_2.color,
          topicCount: 1,
          score: 1.0,
        },
      ]
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns(response)

      topic_page.visit_topic(topic)
      page.find(".edit-topic", visible: false).click

      edit_category_chooser.expand
      edit_category_chooser.select_row_by_value("ai-category-suggest")

      expect(edit_category_chooser).to have_selected_name(category_2.name)
      expect(page).to have_no_css(".edit-category__wrapper .category-chooser.is-expanded")
    end

    it "does not offer a suggestion when embeddings are disabled" do
      SiteSetting.ai_embeddings_enabled = false

      topic_page.visit_topic(topic)
      page.find(".edit-topic", visible: false).click

      edit_category_chooser.expand

      expect(page).to have_no_css(
        ".edit-category__wrapper .category-chooser .select-kit-row[data-value='ai-category-suggest']",
      )
    end
  end

  context "when suggesting tags inline when editing a topic" do
    let(:edit_tag_chooser) do
      PageObjects::Components::SelectKit.new(".edit-tags__wrapper .mini-tag-chooser")
    end

    before do
      SiteSetting.ai_embeddings_selected_model = embedding_definition.id
      SiteSetting.ai_embeddings_enabled = true
      stub_request(:post, embedding_definition.url).to_return(
        status: 200,
        body: JSON.dump([[0.0038493] * embedding_definition.dimensions]),
      )
    end

    it "does not suggest tags that are already on the topic" do
      response =
        [cloud, feedback, review, video, music].map { |t| { id: t.id, name: t.name, count: 1 } }
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)

      topic_page.visit_topic(topic)
      page.find(".edit-topic", visible: false).click

      edit_tag_chooser.expand
      edit_tag_chooser.select_row_by_value("ai-tag-suggest")

      expect(edit_tag_chooser).to have_option_name(cloud.name)
      expect(edit_tag_chooser).to have_no_option_name(video.name)
      expect(edit_tag_chooser).to have_no_option_name(music.name)
    end

    it "applies a suggested tag and stops offering it once added" do
      response = [cloud, feedback].map { |t| { id: t.id, name: t.name, count: 1 } }
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)

      topic_page.visit_topic(topic)
      page.find(".edit-topic", visible: false).click

      edit_tag_chooser.expand
      edit_tag_chooser.select_row_by_value("ai-tag-suggest")
      edit_tag_chooser.select_row_by_name(cloud.name)

      expect(edit_tag_chooser).to have_selected_choice_name(cloud.name)
      expect(edit_tag_chooser).to have_no_option_name(cloud.name)
      expect(edit_tag_chooser).to have_option_name(feedback.name)
    end

    it "does not offer a suggestion when embeddings are disabled" do
      SiteSetting.ai_embeddings_enabled = false

      topic_page.visit_topic(topic)
      page.find(".edit-topic", visible: false).click

      edit_tag_chooser.expand

      expect(page).to have_no_css(
        ".edit-tags__wrapper .mini-tag-chooser .select-kit-row[data-value='ai-tag-suggest']",
      )
    end
  end

  context "when suggesting a category inline in the composer" do
    before do
      SiteSetting.ai_embeddings_selected_model = embedding_definition.id
      SiteSetting.ai_embeddings_enabled = true
    end

    it "applies the best suggestion and closes the dropdown" do
      response = [
        {
          id: category.id,
          name: category.name,
          slug: category.slug,
          color: category.color,
          topicCount: 1,
          score: 1.0,
        },
        {
          id: category_2.id,
          name: category_2.name,
          slug: category_2.slug,
          color: category_2.color,
          topicCount: 1,
          score: 0.5,
        },
      ]
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns(response)

      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)

      composer.category_chooser.expand
      composer.category_chooser.select_row_by_value("ai-category-suggest")

      expect(composer.category_chooser).to have_selected_name(category.name)
      expect(page).to have_no_css(".category-chooser.is-expanded")
    end

    it "shows a toast when no category suggestions are returned" do
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns([])

      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)

      composer.category_chooser.expand
      composer.category_chooser.select_row_by_value("ai-category-suggest")

      expect(toasts).to have_error(
        I18n.t("js.discourse_ai.ai_helper.suggest_errors.no_suggestions"),
      )
    end

    it "does not offer a suggestion without enough content" do
      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content("Too short")

      composer.category_chooser.expand

      expect(page).to have_no_css(
        ".category-chooser .select-kit-row[data-value='ai-category-suggest']",
      )
    end
  end

  context "when suggesting tags inline in the composer" do
    let(:tag_chooser) { PageObjects::Components::SelectKit.new(".mini-tag-chooser") }

    before do
      SiteSetting.ai_embeddings_selected_model = embedding_definition.id
      SiteSetting.ai_embeddings_enabled = true
    end

    it "suggests tags and applies the selected one" do
      response = [{ id: cloud.id, name: cloud.name, count: 1 }]
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)

      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)

      tag_chooser.expand
      tag_chooser.select_row_by_value("ai-tag-suggest")
      tag_chooser.select_row_by_name(cloud.name)

      expect(page).to have_css(".mini-tag-chooser .formatted-selection", text: cloud.name)
    end

    it "shows a toast when no tag suggestions are returned" do
      DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns([])

      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)

      tag_chooser.expand
      tag_chooser.select_row_by_value("ai-tag-suggest")

      expect(toasts).to have_error(
        I18n.t("js.discourse_ai.ai_helper.suggest_errors.no_suggestions"),
      )
    end
  end

  context "when AI helper is disabled" do
    before { SiteSetting.ai_helper_enabled = false }

    it "does not show the AI helper button in the composer toolbar" do
      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)
      expect(page).to have_no_css(".d-editor-button-bar button.ai-helper-trigger")
    end
  end

  context "when user is not a member of AI helper allowed group" do
    before { SiteSetting.composer_ai_helper_allowed_groups = non_member_group.id.to_s }

    it "does not show the AI helper button in the composer toolbar" do
      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)
      expect(page).to have_no_css(".d-editor-button-bar button.ai-helper-trigger")
    end
  end

  context "when the suggestions feature is disabled" do
    let(:mode) { DiscourseAi::AiHelper::Assistant::GENERATE_TITLES }

    before { SiteSetting.ai_helper_enabled_features = "context_menu" }

    it "does not offer title suggestions in the AI helper menu" do
      trigger_composer_helper(input)
      expect(ai_helper_menu).to have_context_menu
      expect(ai_helper_menu).to have_no_option(mode)
    end
  end

  context "when composer helper feature is disabled" do
    before { SiteSetting.ai_helper_enabled_features = "suggestions" }

    it "does not show button in the composer toolbar" do
      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)
      expect(page).to have_no_css(".d-editor-button-bar button.ai-helper-trigger")
    end
  end

  context "when triggering composer AI helper", mobile: true do
    it "closes the composer helper before showing the diff modal" do
      visit("/latest")
      page.find("#create-topic").click
      composer.fill_content(input)
      composer.click_toolbar_button("ai-helper-trigger")

      DiscourseAi::Completions::Llm.with_prepared_responses([input]) do
        ai_helper_menu.select_helper_model(DiscourseAi::AiHelper::Assistant::TRANSLATE)
        expect(ai_helper_menu).to have_no_context_menu
        expect(diff_modal).to be_visible
      end
    end
  end
end