Skip to content

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

31.1 KB
Raw Blame
# frozen_string_literal: true

describe "AI combined search" do
  fab!(:user) { Fabricate(:admin, refresh_auto_groups: true) }
  fab!(:topic_1) { Fabricate(:topic, title: "Password resets and account recovery") }
  fab!(:topic_2) { Fabricate(:topic, title: "Login help for new members") }

  let(:query) { "how do I reset my password" }
  let(:request_ids) { [] }
  let(:scopes) { [] }
  let(:triggers) { [] }
  let(:sources) do
    [topic_1, topic_2].map do |topic|
      { title: topic.title, url: topic.url, excerpt: "An excerpt about #{topic.title}" }
    end
  end

  before do
    enable_current_plugin
    assign_fake_provider_to(:ai_default_llm_model)
    assign_agent_to(:ai_ask_ai_agent, [Group::AUTO_GROUPS[:admins]])

    SiteSetting.discourse_ai_enabled = true
    SiteSetting.ai_ask_ai_enabled = true
    SiteSetting.ai_ask_ai_allowed_groups = Group::AUTO_GROUPS[:admins].to_s
    SiteSetting.enable_ai_combined_search = true

    # the answer is streamed from the spec instead, one phase at a time
    allow(DiscourseAi::Discoveries).to receive(
      :enqueue_reply,
    ) do |user:, query:, request_id:, scope: nil, trigger: "", trigger_reason: "", intent_heuristic: "", **|
      request_ids << request_id
      scopes << scope
      triggers << [trigger, trigger_reason]
      AskAiLog.create!(
        user:,
        query:,
        asked_at: Time.current,
        ask_intent_heuristic: intent_heuristic,
      )
    end

    sign_in(user)
  end

  def publish(payload)
    MessageBus.publish(
      "/discourse-ai/discoveries",
      { query:, request_id: request_ids.last }.merge(payload),
      user_ids: [user.id],
    )
  end

  def wait_for_channel(channel)
    # updates published before the client knows its position on the channel
    # are skipped, which a real answer never outpaces
    try_until_success(timeout: 10) { expect(page.evaluate_script(<<~JS)).to eq(true) }
        MessageBus.callbacks.some(
          (callback) => callback.channel === #{channel.to_json} && callback.last_id !== -1
        )
      JS
  end

  def wait_for_discoveries_channel
    wait_for_channel("/discourse-ai/discoveries")
  end

  def ask(term, input: "#welcome-banner-search-input")
    find(input).fill_in(with: term)
    find(input).send_keys(:enter)
    try_until_success { expect(request_ids).to be_present }
  end

  def tab(kind)
    ".ai-search-tabs .ai-discoveries-search-options__option.--#{kind}"
  end

  def expect_tab(kind)
    expect(page).to have_css("#{tab(kind)}.is-active")
  end

  def select_tab(kind)
    find(tab(kind)).click
    expect_tab(kind)
  end

  def allow_follow_ups
    SiteSetting.ai_bot_enabled = true
    SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:admins].to_s
    assign_agent_to(:ai_ask_ai_follow_up_agent, [Group::AUTO_GROUPS[:admins]]).create_user!
  end

  def complete_answer
    publish(
      done: true,
      phase: "complete",
      answerable: true,
      ai_discover_title: "Resetting your password",
      ai_discover_reply: "Use the **forgot password** link on the login screen.",
      ai_discover_follow_up: "What if I no longer have access to my email?",
      sources:,
    )
  end

  it "streams the answer in full, adding its related topics once it is done" do
    allow_follow_ups
    visit "/"
    wait_for_discoveries_channel
    ask(query)

    # a question opens on the answer
    expect_tab("ask")
    expect(page).to have_css(".ai-search-answer .d-skeleton")

    publish(
      done: false,
      phase: "rewritten",
      keyword_query: "reset password",
      semantic_query: "How can I reset a forgotten password?",
    )
    publish(done: false, phase: "sources", ai_discover_title: "Resetting your password", sources:)
    publish(done: false, phase: "answering", ai_discover_reply: "Use the **forgot")

    expect(page).to have_css(".ai-search-answer__body .cooked", text: "Use the")
    # added once the answer is complete, so they do not slide down as it streams
    expect(page).to have_no_css(".ai-search-answer__more")

    publish(
      done: true,
      phase: "complete",
      answerable: true,
      ai_discover_title: "Resetting your password",
      ai_discover_reply: "Use the **forgot password** link on the login screen. " * 12,
      ai_discover_follow_up: "What if I no longer have access to my email?",
      sources:,
    )

    expect(page).to have_css(".ai-search-answer__body .cooked", text: "forgot password")
    within(".ai-search-answer__more") do
      expect(page).to have_css(".ai-search-answer__related-link", count: 2)
      expect(page).to have_css(
        ".ai-search-answer__follow-up-input[placeholder='What if I no longer have access to my email?']",
      )
    end
    expect(page).to have_no_css(".ai-search-answer__expand")
    expect(page).to have_no_text("Keywords")
  end

  it "leaves out the follow-up when the reader cannot talk to the AI bot" do
    visit "/"
    wait_for_discoveries_channel
    ask(query)
    complete_answer

    within(".ai-search-answer__more") do
      expect(page).to have_css(".ai-search-answer__related-link", count: 2)
      expect(page).to have_no_css(".ai-search-answer__follow-up")
    end
  end

  it "lists every related topic the answer used" do
    category = Fabricate(:category, name: "Account help")
    more_topics =
      Array.new(3) { |i| Fabricate(:topic, category:, title: "Account recovery guide part #{i}") }
    visit "/"
    wait_for_discoveries_channel
    ask(query)

    publish(
      done: true,
      phase: "complete",
      answerable: true,
      ai_discover_reply: "Use the forgot password link.",
      sources:
        sources +
          more_topics.map do |topic|
            {
              title: topic.title,
              url: topic.url,
              excerpt: "An excerpt about #{topic.title}",
              category_id: topic.category_id,
              topic_replies: 12,
              bumped_at: 2.days.ago.iso8601,
            }
          end,
    )

    expect(page).to have_css(".ai-search-answer__related-heading", text: "Related topics")
    last_row = find(".ai-search-answer__related-link", text: more_topics.last.title)
    expect(last_row).to have_css(".ai-search-topic-row__date", text: "2d")
    expect(last_row).to have_css(".ai-search-topic-row__replies[title='12 replies']", text: "12")
    expect(last_row).to have_css(".ai-search-topic-row__category", text: "Account help")
    expect(page).to have_css(".ai-search-answer__related-item", count: 5)
    expect(page).to have_css(".ai-search-answer__related-link", text: more_topics.last.title)
    expect(page).to have_no_css(".ai-search-answer__related-excerpt")
  end

  it "opens on the answer when nothing matches the keywords, and says so on the topics tab" do
    visit "/"
    wait_for_discoveries_channel
    ask("unheard of things")

    expect_tab("ask")
    expect(page).to have_css("#{tab("topics")}.--empty .ai-search-tabs__count", text: "0")

    select_tab("topics")
    expect(page).to have_css(".search-menu .no-results", text: "No keyword matches found.")
    expect(page).to have_no_text("No results found.")
  end

  it "marks the answer tab when no answer was found" do
    visit "/"
    wait_for_discoveries_channel
    ask(query)

    publish(done: true, phase: "complete", answerable: false, ai_discover_reply: "", sources: [])

    expect(page).to have_css("#{tab("ask")} .ai-search-tabs__empty .d-icon-ban")
  end

  it "opens on the answer for a query outside the site's language" do
    visit "/"
    wait_for_discoveries_channel
    ask("сброс")

    expect_tab("ask")
    expect(triggers.last).to eq(["enter", ""])
  end

  it "waits for enter rather than searching as the reader types" do
    visit "/"
    wait_for_discoveries_channel

    find("#welcome-banner-search-input").fill_in(with: query)
    expect(page).to have_no_css(".ai-search-tabs")
    expect(request_ids).to be_empty

    find("#welcome-banner-search-input").send_keys(:enter)
    try_until_success { expect(request_ids.size).to eq(1) }
    expect(page).to have_css(".ai-search-tabs")
  end

  context "with more keyword matches than the menu lists" do
    before do
      SearchIndexer.enable
      8.times do |i|
        topic = Fabricate(:topic, title: "Widget maintenance guide number #{i}")
        Fabricate(:post, topic:, raw: "Keeping widgets running smoothly, part #{i}")
        SearchIndexer.index(topic, force: true)
      end
    end

    after { SearchIndexer.disable }

    it "opens the full search page on the tab's terms from its more link" do
      visit "/"
      wait_for_discoveries_channel
      ask("widget")

      expect_tab("topics")
      find(".search-menu__show-more a").click

      expect(page).to have_current_path(%r{/search\?q=widget\z})
    end
  end

  context "with keyword results" do
    let(:query) { "password" }

    before do
      Fabricate(:post, topic: topic_1, raw: "Reset your password from the login screen")
      SearchIndexer.enable
      SearchIndexer.index(topic_1, force: true)
    end

    after { SearchIndexer.disable }

    it "opens the full search page on a second enter" do
      visit "/"
      wait_for_discoveries_channel
      ask(query)

      expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      find("#welcome-banner-search-input").send_keys(:enter)

      expect(page).to have_current_path(%r{/search\?q=password\z})
      expect(request_ids.size).to eq(1)
    end

    it "shows the search's topics again when the menu is reopened" do
      visit "/about"
      wait_for_discoveries_channel
      find("#search-button").click
      ask(query, input: "#icon-search-input")

      expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      find("#icon-search-input").send_keys(:escape)
      expect(page).to have_no_css("#icon-search-input")

      find("#search-button").click
      expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      expect(request_ids.size).to eq(1)
    end

    it "opens a lookup on its topics, with every tab fetched at once" do
      visit "/"
      wait_for_discoveries_channel
      ask(query)

      expect_tab("topics")
      expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      # counts wait for a tab to open, then show only on the others
      expect(page).to have_no_css("#{tab("topics")} .ai-search-tabs__count")

      # the answer was asked for with the rest, so switching asks nothing more
      select_tab("ask")
      expect(page).to have_css("#{tab("topics")} .ai-search-tabs__count", text: "1")
      expect(page).to have_css(".ai-search-answer")
      expect(page).to have_no_css(".search-menu .search-result-topic")
      publish(
        done: true,
        phase: "complete",
        answerable: true,
        ai_discover_reply: "An answer.",
        sources:,
      )
      expect(page).to have_css(".ai-search-answer__body .cooked", text: "An answer.")

      select_tab("topics")
      expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      expect(request_ids.size).to eq(1)
    end

    it "logs the tab the search opened on and the first one the reader switched to" do
      visit "/"
      wait_for_discoveries_channel
      ask(query)

      expect_tab("topics")
      select_tab("ask")
      select_tab("topics")

      try_until_success do
        expect(AskAiLog.last).to have_attributes(
          ask_intent_heuristic: "lookup",
          ask_tab_opened: "topics",
          ask_tab_opened_reason: "topic_results",
          ask_tab_switched_to: "ask",
        )
      end
    end

    it "records the first result the reader opens" do
      visit "/"
      wait_for_discoveries_channel
      ask(query)

      expect_tab("topics")
      find(".search-menu .search-result-topic a.search-link", text: topic_1.title).click

      try_until_success do
        expect(AskAiLog.last).to have_attributes(
          ask_tab_opened_after_ms: be >= 0,
          ask_result_clicked_tab: "topics",
          ask_result_clicked_after_ms: be > 0,
        )
      end
    end

    it "leaves the answer to a search using operators until the reader opens it" do
      term = "password status:open"
      visit "/"
      wait_for_discoveries_channel
      find("#welcome-banner-search-input").fill_in(with: term)
      find("#welcome-banner-search-input").send_keys(:enter)

      expect_tab("topics")
      try_until_success do
        expect(AskAiLog.find_by(query: term)).to have_attributes(
          ask_outcome: "skipped",
          ask_tab_opened: "topics",
          ask_tab_opened_reason: "syntax",
        )
      end
      expect(request_ids).to be_empty

      select_tab("ask")

      expect(page).to have_css(".ai-search-answer")
      try_until_success { expect(request_ids.size).to eq(1) }
    end

    context "with a decision model judging intent" do
      fab!(:decision_model)

      before { SiteSetting.ai_ask_ai_search_intent_decision_model = decision_model.id }

      it "opens on the answer when the model is sure the reader wants one" do
        DiscourseAi::Decisions.with_canned_answers(intent: { "answer" => 0.9, "lookup" => 0.1 }) do
          visit "/"
          wait_for_discoveries_channel
          ask(query)

          expect_tab("ask")
          expect(page).to have_css("#{tab("topics")} .ai-search-tabs__count", text: "1")
        end

        try_until_success do
          expect(AskAiLog.last).to have_attributes(
            ask_intent_heuristic: "lookup",
            ask_intent_model: "answer",
            ask_intent_probability: 0.9,
            ask_tab_opened: "ask",
            ask_tab_opened_reason: "intent_answer",
          )
        end
      end

      it "shows the keyword results when the reader switches from the answer" do
        DiscourseAi::Decisions.with_canned_answers(intent: "answer") do
          visit "/"
          wait_for_discoveries_channel
          ask(query)
          expect_tab("ask")
        end
        publish(
          done: true,
          phase: "complete",
          answerable: true,
          ai_discover_reply: "Use the forgot password link.",
          sources:,
        )
        expect(page).to have_css(".ai-search-answer__body .cooked", text: "forgot password")

        select_tab("topics")

        expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      end

      it "moves to the results when the answer it opened on finds nothing" do
        DiscourseAi::Decisions.with_canned_answers(intent: "answer") do
          visit "/"
          wait_for_discoveries_channel
          ask(query)
          expect_tab("ask")
        end

        publish(
          done: true,
          phase: "complete",
          answerable: false,
          ai_discover_reply: "",
          sources: [],
        )

        expect_tab("topics")
        expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      end

      it "leaves a reader on the answer they chose, even when it finds nothing" do
        visit "/"
        wait_for_discoveries_channel
        ask(query)
        expect_tab("topics")
        select_tab("ask")

        publish(
          done: true,
          phase: "complete",
          answerable: false,
          ai_discover_reply: "",
          sources: [],
        )

        expect(page).to have_css(".ai-search-answer__empty")
        expect_tab("ask")
      end

      it "keeps rewritten keyword results that arrive while the menu waits for the model" do
        question = "does this site have any guides on that"
        slow_intent = instance_double(DiscourseAi::Discoveries::Intent)
        allow(slow_intent).to receive(:call) do
          sleep 1.5
          nil
        end
        allow(DiscourseAi::Discoveries::Intent).to receive(:new).and_return(slow_intent)

        visit "/"
        wait_for_discoveries_channel
        ask(question)
        publish(
          query: question,
          done: false,
          phase: "rewritten",
          keyword_query: "password",
          semantic_query: "Password guides",
        )

        expect(page).to have_css("#{tab("topics")} .ai-search-tabs__count", text: "1")
        select_tab("topics")
        expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      end

      it "judges from the query alone when the model is too slow, still logging its verdict" do
        slow_intent = instance_double(DiscourseAi::Discoveries::Intent)
        allow(slow_intent).to receive(:call) do
          sleep 1.5
          DiscourseAi::Discoveries::Intent::Judgement.new(intent: "answer", probability: 0.95)
        end
        allow(DiscourseAi::Discoveries::Intent).to receive(:new).and_return(slow_intent)

        visit "/"
        wait_for_discoveries_channel
        ask(query)

        expect_tab("topics")
        try_until_success(timeout: 5) do
          expect(AskAiLog.last).to have_attributes(
            ask_intent_model: "answer",
            ask_tab_opened: "topics",
            ask_tab_opened_reason: "topic_results",
          )
        end
      end
    end

    it "leaves related results to the combined search, so the list holds still" do
      SiteSetting.ai_embeddings_semantic_quick_search_enabled = true

      visit "/"
      wait_for_discoveries_channel
      ask(query)
      publish(
        done: true,
        phase: "complete",
        answerable: true,
        ai_discover_reply: "Use the forgot password link.",
        sources:,
      )

      expect(page).to have_css(".search-menu .search-result-topic", text: topic_1.title)
      expect(page).to have_no_css(".ai-quick-search-notice")
      expect(page).to have_no_css(".search-menu .ai-search-result")
    end
  end

  it "offers to ask the community when no answer is found" do
    visit "/"
    wait_for_discoveries_channel
    ask(query)

    publish(done: true, phase: "complete", answerable: false, ai_discover_reply: "", sources: [])

    expect(page).to have_css(".ai-search-answer__empty", text: "AI couldn’t find a clear answer.")
    find(".ai-search-answer__ask-community", text: "Ask the community.").click

    expect(page).to have_css("#reply-control.open")
    expect(find("#reply-title").value).to eq(query)
  end

  it "centres the message when no answer is found" do
    visit "/"
    wait_for_discoveries_channel
    ask(query)

    publish(done: true, phase: "complete", answerable: false, ai_discover_reply: "", sources: [])

    expect(page).to have_css(".ai-search-answer__empty")
    offsets = page.evaluate_script(<<~JS)
        (() => {
          const box = document.querySelector(".ai-search-answer__body").getBoundingClientRect();
          const text = document.createRange();
          text.selectNodeContents(document.querySelector(".ai-search-answer__empty"));
          const rect = text.getBoundingClientRect();
          return [
            Math.round(rect.top - box.top - (box.bottom - rect.bottom)),
            Math.round(rect.left - box.left - (box.right - rect.right)),
          ];
        })()
      JS
    expect(offsets.map(&:abs)).to all(be <= 2)
  end

  it "keeps the results scrollable" do
    page.current_window.resize_to(1400, 450)

    visit "/"
    wait_for_discoveries_channel
    ask(query)
    publish(
      done: true,
      phase: "complete",
      answerable: true,
      ai_discover_reply: "A long answer that runs on. " * 40,
      sources:,
    )
    # long enough to run past the window
    expect(page).to have_css(".ai-search-answer__more")

    scroll = page.evaluate_script(<<~JS)
        (() => {
          const list = document.querySelector(".search-menu .panel-body-contents");
          const panel = document.querySelector(".search-menu .menu-panel");
          list.scrollTop = 50;
          return {
            overflows: list.scrollHeight > list.clientHeight,
            scrolled: list.scrollTop > 0,
            fits: list.getBoundingClientRect().bottom <= panel.getBoundingClientRect().bottom + 1,
          };
        })()
      JS
    expect(scroll).to eq("overflows" => true, "scrolled" => true, "fits" => true)
  ensure
    page.current_window.resize_to(1400, 1400)
  end

  context "when searching from somewhere" do
    fab!(:category)
    fab!(:inside) { Fabricate(:topic, category:, title: "Widget setup for this team") }
    fab!(:outside) { Fabricate(:topic, title: "Widget setup somewhere else entirely") }
    let(:query) { "widget" }

    before do
      Fabricate(:post, topic: inside, raw: "Widget configuration inside the category")
      Fabricate(:post, topic: outside, raw: "Widget configuration outside the category")
      SearchIndexer.enable
      [inside, outside].each { |topic| SearchIndexer.index(topic, force: true) }
    end

    after { SearchIndexer.disable }

    def open_header_search
      find("#search-button").click
      expect(page).to have_css("#icon-search-input")
    end

    it "offers the category as a tab, opening on it when it has matches" do
      visit category.url
      wait_for_discoveries_channel
      open_header_search
      page.execute_script(<<~JS)
        window.pillWidths = {};
        new MutationObserver(() => {
          document.querySelectorAll(".ai-search-tabs .ai-discoveries-search-options__option").forEach((pill) => {
            const kind = [...pill.classList].find((name) => name.startsWith("--") && name !== "--empty");
            (window.pillWidths[kind] ??= new Set()).add(Math.round(pill.getBoundingClientRect().width));
          });
        }).observe(document.body, { subtree: true, childList: true, characterData: true });
      JS
      ask(query, input: "#icon-search-input")

      expect(page).to have_css(tab("context"), text: category.name)
      expect_tab("context")
      expect(scopes.last).to eq("category:#{category.id}")
      expect(page).to have_no_css("#{tab("context")} .ai-search-tabs__count")
      expect(page).to have_css("#{tab("topics")} .ai-search-tabs__count", text: "2")
      # the counts hang off the pills rather than widening them
      widths = page.evaluate_script(<<~JS)
        Object.fromEntries(Object.entries(window.pillWidths).map(([kind, set]) => [kind, set.size]))
      JS
      expect(widths.values).to all(eq(1))
      expect(page).to have_css(".search-menu .search-result-topic", text: inside.title)
      expect(page).to have_no_css(".search-menu .search-result-topic", text: outside.title)

      select_tab("topics")
      expect(page).to have_css(".search-menu .search-result-topic", text: outside.title)
      expect(page).to have_css("#{tab("context")} .ai-search-tabs__count", text: "1")
      expect(request_ids.size).to eq(1)
    end

    it "says when the answer had to come from the whole site" do
      visit category.url
      wait_for_discoveries_channel
      open_header_search
      ask(query, input: "#icon-search-input")
      select_tab("ask")

      publish(
        done: true,
        phase: "complete",
        answerable: true,
        scope_fallback: true,
        ai_discover_reply: "An answer from elsewhere.",
        sources:,
      )

      expect(page).to have_css(
        ".ai-search-answer__scope-note",
        text: "Nothing found in #{category.name}",
      )
      expect(request_ids.size).to eq(1)
    end

    it "does not mention the whole site when no answer was found there either" do
      visit category.url
      wait_for_discoveries_channel
      open_header_search
      ask(query, input: "#icon-search-input")
      select_tab("ask")

      publish(
        done: true,
        phase: "complete",
        answerable: false,
        scope_fallback: true,
        ai_discover_reply: "",
        sources: [],
      )

      expect(page).to have_css(".ai-search-answer__empty")
      expect(page).to have_no_css(".ai-search-answer__scope-note")
    end

    it "opens a topic search on the topic when its posts match, and on the answer when not" do
      inside.posts.each { |post| SearchIndexer.index(post, force: true) }

      visit inside.url
      wait_for_discoveries_channel
      open_header_search
      ask("widget configuration?", input: "#icon-search-input")

      expect(page).to have_css(tab("context"), text: "This topic")
      expect_tab("context")
      expect(scopes.last).to eq("topic:#{inside.id}")

      find("#icon-search-input").fill_in(with: "something nobody wrote about here")
      find("#icon-search-input").send_keys(:enter)

      try_until_success { expect(request_ids.size).to eq(2) }
      expect_tab("ask")
    end

    it "opens a search about the whole site on its results, answering from the whole site" do
      inside.posts.each { |post| SearchIndexer.index(post, force: true) }
      SiteSetting.ai_ask_ai_search_intent_decision_model = Fabricate(:decision_model).id

      DiscourseAi::Decisions.with_canned_answers(
        intent: "lookup",
        scope: {
          "here" => 0.1,
          "site" => 0.9,
        },
      ) do
        visit inside.url
        wait_for_discoveries_channel
        open_header_search
        ask("widget configuration", input: "#icon-search-input")

        expect(page).to have_css(tab("context"), text: "This topic")
        expect_tab("topics")
      end
      expect(scopes.last).to be_nil
    end

    it "starts afresh in a new context rather than searching again" do
      visit category.url
      wait_for_discoveries_channel
      open_header_search
      ask(query, input: "#icon-search-input")
      expect(page).to have_css(".search-menu .search-result-topic", text: inside.title)

      find(".search-menu .search-result-topic a", text: inside.title).click
      expect(page).to have_current_path(%r{/t/})

      open_header_search

      expect(find("#icon-search-input").value).to be_blank
      expect(page).to have_no_css(".ai-search-tabs")
      expect(request_ids.size).to eq(1)
    end
  end

  context "with a conversation continued from a search" do
    fab!(:bot) { Fabricate(:user, username: "answerbot") }
    fab!(:conversation) do
      Fabricate(:private_message_topic, user:, recipient: bot).tap do |topic|
        # laid out as a conversation with the AI bot, which hides the progress bar
        topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = true
        topic.custom_fields[
          DiscourseAi::Discoveries::ContinueConversation::TOPIC_REQUEST_ID_FIELD
        ] = "request"
        topic.save_custom_fields
      end
    end

    before do
      Fabricate(:post, topic: conversation, user:, raw: query)
      Fabricate(
        :post,
        topic: conversation,
        user: bot,
        raw: "See [#{topic_1.title}](#{topic_1.url}) for the steps.",
      )
    end

    it "lists the topics its answers cite in place of the timeline" do
      visit conversation.url

      cited = find(".ai-search-references__link", text: topic_1.title)
      expect(cited).to have_css(".ai-search-topic-row__date")
      expect(cited).to have_css(".ai-search-topic-row__replies")
      expect(page).to have_no_css(".timeline-container")
      expect(page).to have_no_css(".ai-search-references-button")
    end

    it "lists the answer's sources kept beside the conversation" do
      conversation.custom_fields[
        DiscourseAi::Discoveries::ContinueConversation::TOPIC_SOURCES_FIELD
      ] = [{ topic_id: topic_2.id, title: topic_2.title, url: topic_2.url }]
      conversation.save_custom_fields

      visit conversation.url

      expect(page).to have_css(".ai-search-references__link", text: topic_2.title)
    end

    it "adds the topics a new reply cites" do
      visit conversation.url
      expect(page).to have_css(".ai-search-references__link", text: topic_1.title)
      wait_for_channel("discourse-ai/ai-bot/topic/#{conversation.id}")

      reply =
        Fabricate(
          :post,
          topic: conversation,
          user: bot,
          raw: "Also try [#{topic_2.title}](#{topic_2.url}).",
        )
      MessageBus.publish(
        "discourse-ai/ai-bot/topic/#{conversation.id}",
        { post_id: reply.id, post_number: reply.post_number, cooked: reply.cooked, done: true },
        user_ids: [user.id],
      )

      expect(page).to have_css(".ai-search-references__link", text: topic_2.title)
    end

    it "opens the cited topics from the topic map where the timeline does not fit", mobile: true do
      visit conversation.url
      find(".ai-search-references-button").click

      expect(page).to have_css(
        ".ai-search-references-modal .ai-search-references__link",
        text: topic_1.title,
      )
    end

    it "keeps the timeline for readers without the combined search" do
      SiteSetting.enable_ai_combined_search = false

      visit conversation.url

      expect(page).to have_css(".timeline-container")
      expect(page).to have_no_css(".ai-search-references")
    end
  end

  context "with people and places to find" do
    fab!(:gardening) { Fabricate(:category, name: "Gardening") }
    fab!(:gardener) { Fabricate(:user, username: "plantlover", name: "Green Thumb") }

    before do
      SearchIndexer.enable
      [
        "Gardening tips for the spring season",
        "Gardening in small spaces",
        "Gardening with children",
        "Gardening on a budget",
      ].each do |title|
        topic = Fabricate(:topic, category: gardening, title:)
        Fabricate(:post, topic:, raw: "Gardening is a lovely way to spend the spring")
        SearchIndexer.index(topic, force: true)
      end
      SearchIndexer.index(gardener, force: true)
      SearchIndexer.index(gardening, force: true)
    end

    after { SearchIndexer.disable }

    it "opens a lookup on its topics" do
      visit "/"
      wait_for_discoveries_channel
      ask("gardening")

      expect_tab("topics")
      expect(page).to have_css(".search-menu .search-result-topic", text: "Gardening tips")
    end

    it "opens on the answer when only a person matches" do
      visit "/"
      wait_for_discoveries_channel
      ask("green thumb")

      expect_tab("ask")
    end

    it "opens a question on the answer even when places match" do
      visit "/"
      wait_for_discoveries_channel
      ask("gardening?")

      expect_tab("ask")
    end

    it "opens a query in search syntax on its topics" do
      visit "/"
      wait_for_discoveries_channel
      find("#welcome-banner-search-input").fill_in(with: '"small spaces"')
      find("#welcome-banner-search-input").send_keys(:enter)

      expect_tab("topics")
      expect(page).to have_css(
        ".search-menu .search-result-topic",
        text: "Gardening in small spaces",
      )
    end

    it "opens on the answer when the reader searches again on the same page" do
      visit "/"
      wait_for_discoveries_channel
      ask("gardening")
      expect_tab("topics")

      find("#welcome-banner-search-input").fill_in(with: "spring gardening")
      find("#welcome-banner-search-input").send_keys(:enter)

      try_until_success { expect(request_ids.size).to eq(2) }
      expect_tab("ask")
    end

    it "runs the combined search for a recent search picked from the menu" do
      SearchLog.log(
        term: "gardening",
        search_type: :header,
        ip_address: "127.0.0.1",
        user_id: user.id,
      )

      visit "/"
      wait_for_discoveries_channel
      find("#welcome-banner-search-input").click
      find(".search-menu-recent .search-menu-assistant-item", text: "gardening").click

      expect_tab("topics")
      expect(page).to have_css(".search-menu .search-result-topic", text: "Gardening tips")
      expect(find("#welcome-banner-search-input").value).to eq("gardening")
      expect(triggers.last).to eq(["recent", ""])
    end
  end
end