Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

64.3 KB
Raw Blame
(ns metabase-enterprise.metabot-analytics.api-test
  (:require
   [clojure.set :as set]
   [clojure.test :refer [deftest is testing]]
   [metabase.slackbot.api :as slackbot.api]
   [metabase.test :as mt]
   [toucan2.core :as t2]))

(set! *warn-on-reflection* true)

(defn- insert-conversation!
  [{:keys [conversation-id user-id created-at title slack-team-id slack-channel-id slack-thread-ts ip-address]}]
  (t2/insert! :model/MetabotConversation
              (cond-> {:id      conversation-id
                       :user_id user-id}
                created-at (assoc :created_at created-at)
                title (assoc :title title)
                slack-team-id (assoc :slack_team_id slack-team-id)
                slack-channel-id (assoc :slack_channel_id slack-channel-id)
                slack-thread-ts (assoc :slack_thread_ts slack-thread-ts)
                ip-address (assoc :ip_address ip-address))))

(defn- insert-message!
  [{:keys [conversation-id created-at role profile-id total-tokens data data-version
           deleted-at external-id finished finish-reason context-window-full]
    :as   options
    :or   {data-version 2}}]
  (first (t2/insert-returning-pks!
          :model/MetabotMessage
          (cond-> {:conversation_id conversation-id
                   :role            role
                   :profile_id      profile-id
                   :total_tokens    total-tokens
                   :data            data
                   :data_version    data-version
                   :external_id     (or external-id (str (random-uuid)))}
            created-at          (assoc :created_at created-at)
            deleted-at          (assoc :deleted_at deleted-at)
            finish-reason       (assoc :finish_reason finish-reason)
            context-window-full (assoc :context_window_full context-window-full)
            (contains? options :finished) (assoc :finished finished)))))

(defn- insert-usage!
  "Insert an `ai_usage_log` row for a conversation. `cache-read-tokens` may be
   omitted to seed a pre-cache-columns row (NULL in the table)."
  [{:keys [conversation-id cache-read-tokens]}]
  (t2/insert! :model/AiUsageLog
              (cond-> {:conversation_id   conversation-id
                       :source            "agent"
                       :model             "anthropic/claude-sonnet-4-6"
                       :prompt_tokens     1
                       :completion_tokens 1
                       :total_tokens      2}
                cache-read-tokens (assoc :cache_read_tokens cache-read-tokens))))

(defn- delete-conversations!
  [conversation-ids]
  (t2/delete! :model/AiUsageLog {:where [:in :conversation_id (vec conversation-ids)]})
  (t2/delete! :model/MetabotConversation {:where [:in :id (vec conversation-ids)]}))

(defn- insert-feedback!
  [{:keys [message-id user-id positive issue-type freeform created-at updated-at]}]
  (t2/insert! :model/MetabotFeedback
              (cond-> {:message_id        message-id
                       :user_id           user-id
                       :positive          positive
                       :issue_type        issue-type
                       :freeform_feedback freeform}
                created-at (assoc :created_at created-at)
                updated-at (assoc :updated_at updated-at))))

(defn- offset-date-time
  [s]
  (java.time.OffsetDateTime/parse s))

(defn- find-conversation
  [conversations conversation-id]
  (some #(when (= (:conversation_id %) conversation-id) %) conversations))

(defn- with-list-conversations-fixture!
  [thunk]
  (mt/with-premium-features #{:audit-app}
    (mt/with-temp [:model/User {test-user-id :id} {:email      "[email protected]"
                                                   :first_name "Metabot"
                                                   :last_name  "Analytics"}]
      (let [response-path (format "ee/metabot-analytics/conversations?user_id=%s" test-user-id)
            convo-1       (str (random-uuid))
            convo-2       (str (random-uuid))
            convo-3       (str (random-uuid))
            jan-1         (offset-date-time "2026-01-01T00:00:00Z")
            jan-2         (offset-date-time "2026-01-02T00:00:00Z")
            jan-3         (offset-date-time "2026-01-03T00:00:00Z")
            jan-4         (offset-date-time "2026-01-04T00:00:00Z")
            jan-5         (offset-date-time "2026-01-05T00:00:00Z")]
        (try
          (insert-conversation! {:conversation-id convo-1
                                 :user-id         test-user-id
                                 :created-at      jan-1
                                 :title           "First conversation"})
          (insert-conversation! {:conversation-id convo-2
                                 :user-id         test-user-id
                                 :created-at      jan-2
                                 :title           "Second conversation"})
          (insert-conversation! {:conversation-id convo-3
                                 :user-id         test-user-id
                                 :created-at      jan-3
                                 :title           "Third conversation"})
          (insert-message! {:conversation-id convo-1
                            :created-at      jan-2
                            :role            "user"
                            :profile-id      "ignored-user-model"
                            :total-tokens    3
                            :data            [{:type "text" :text "hello"}]})
          (insert-message! {:conversation-id convo-1
                            :created-at      jan-3
                            :role            "assistant"
                            :profile-id      "nlq"
                            :total-tokens    7
                            :data            [{:type "text" :text "hi"}]})
          (insert-message! {:conversation-id convo-2
                            :created-at      jan-4
                            :role            "user"
                            :profile-id      "ignored-user-model"
                            :total-tokens    2
                            :data            [{:type "text" :text "question"}]})
          (insert-message! {:conversation-id convo-2
                            :created-at      jan-5
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    11
                            :data            [{:type "text" :text "answer"}]})
          (insert-message! {:conversation-id convo-2
                            :created-at      jan-5
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    13
                            :data            [{:type "text" :text "follow-up"}]})
          (insert-message! {:conversation-id convo-3
                            :created-at      jan-4
                            :role            "assistant"
                            :profile-id      "deleted-model"
                            :total-tokens    99
                            :data            [{:type "text" :text "deleted"}]
                            :deleted-at      jan-5})
          ;; convo-1 sums across usage rows; convo-2 also has a NULL-cache row
          ;; (predates the cache-token columns); convo-3 has no usage rows at all.
          (insert-usage! {:conversation-id convo-1 :cache-read-tokens 100})
          (insert-usage! {:conversation-id convo-1 :cache-read-tokens 25})
          (insert-usage! {:conversation-id convo-2 :cache-read-tokens 40})
          (insert-usage! {:conversation-id convo-2})
          (thunk {:test-user-id  test-user-id
                  :response-path response-path
                  :convo-1       convo-1
                  :convo-2       convo-2
                  :convo-3       convo-3})
          (finally
            (delete-conversations! [convo-1 convo-2 convo-3])))))))

(deftest list-conversations-requires-superuser-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations requires superuser"
      (is (= "You don't have permissions to do that."
             (mt/user-http-request :rasta :get 403 "ee/metabot-analytics/conversations"))))))

(deftest list-conversations-aggregates-data-test
  (with-list-conversations-fixture!
    (fn [{:keys [test-user-id response-path convo-1 convo-2 convo-3]}]
      (let [response         (mt/user-http-request :crowberto :get 200 response-path)
            conversation-ids (map :conversation_id (:data response))
            convo-1-response (find-conversation (:data response) convo-1)
            convo-2-response (find-conversation (:data response) convo-2)
            convo-3-response (find-conversation (:data response) convo-3)]
        (is (= 3 (:total response)))
        (is (= 50 (:limit response)))
        (is (= 0 (:offset response)))
        (is (= [convo-3 convo-2 convo-1] conversation-ids))
        (testing "a soft-deleted / regenerated agent response still counts as spend"
          (is (= "deleted-model" (:profile_id convo-3-response)))
          (is (= 1 (:message_count convo-3-response)))
          (is (= 1 (:assistant_message_count convo-3-response)))
          (is (= 99 (:total_tokens convo-3-response)))
          (is (= 0 (:cache_read_tokens convo-3-response))))
        (is (= {:conversation_id         convo-1
                :title                   "First conversation"
                :message_count           2
                :user_message_count      1
                :assistant_message_count 1
                :total_tokens            10
                :cache_read_tokens       125
                :profile_id              "nlq"
                :user                    {:id         test-user-id
                                          :email      "[email protected]"
                                          :first_name "Metabot"
                                          :last_name  "Analytics"}}
               (-> (select-keys convo-1-response [:conversation_id :title :message_count
                                                  :user_message_count :assistant_message_count :total_tokens
                                                  :cache_read_tokens :profile_id :user])
                   (update :user select-keys [:id :email :first_name :last_name]))))
        (is (= {:conversation_id         convo-2
                :message_count           3
                :user_message_count      1
                :assistant_message_count 2
                :total_tokens            26
                :cache_read_tokens       40
                :profile_id              "internal"}
               (select-keys convo-2-response [:conversation_id :message_count :user_message_count
                                              :assistant_message_count :total_tokens :cache_read_tokens
                                              :profile_id])))))))

(deftest list-and-detail-agree-for-regenerated-conversation-test
  (mt/with-premium-features #{:audit-app}
    (testing "the list summary and detail report the same counts for a regenerated conversation"
      (mt/with-temp [:model/User {owner-id :id} {}]
        (let [conversation-id (str (random-uuid))
              day             #(offset-date-time (format "2026-01-0%dT00:00:00Z" %))
              insert!         #(insert-message! (assoc % :conversation-id conversation-id))]
          (try
            (insert-conversation! {:conversation-id conversation-id
                                   :user-id         owner-id
                                   :created-at      (day 1)
                                   :summary         "Regeneration parity"})
            (insert! {:created-at (day 1)
                      :role "user"
                      :profile-id "ignored-user-profile"
                      :total-tokens 2
                      :data [{:type "text" :text "find orders"}]})
            (insert! {:created-at (day 2)
                      :role "assistant"
                      :profile-id "internal"
                      :total-tokens 10
                      :deleted-at (day 3)
                      :data [{:type "text" :text "first"}
                             {:type "tool-search"
                              :toolCallId "s1"
                              :state "output-available"
                              :input {}
                              :output {:output "results"}}]})
            (insert! {:created-at (day 3)
                      :role "assistant"
                      :profile-id "internal"
                      :total-tokens 20
                      :data [{:type "text" :text "kept"}]})
            (let [summary (find-conversation
                           (:data (mt/user-http-request :crowberto :get 200
                                                        (str "ee/metabot-analytics/conversations?user_id=" owner-id)))
                           conversation-id)
                  detail  (mt/user-http-request :crowberto :get 200
                                                (format "ee/metabot-analytics/conversations/%s" conversation-id))]
              (is (some? summary))
              (doseq [k [:message_count :total_tokens :search_count :query_count]]
                (is (= (get detail k) (get summary k))))
              (is (= [3 32 1]
                     ((juxt :message_count :total_tokens :search_count) detail))))
            (finally
              (delete-conversations! [conversation-id]))))))))

(deftest list-conversations-pagination-test
  (with-list-conversations-fixture!
    (fn [{:keys [response-path convo-2]}]
      (let [response (mt/user-http-request :crowberto :get 200
                                           (format "%s&limit=1&offset=1" response-path))]
        (is (= 3 (:total response)))
        (is (= 1 (:limit response)))
        (is (= 1 (:offset response)))
        (is (= [convo-2] (map :conversation_id (:data response)))))
      (testing "total still reflects the full count when paging past the end"
        (let [response (mt/user-http-request :crowberto :get 200
                                             (format "%s&limit=10&offset=999" response-path))]
          (is (= 3 (:total response)))
          (is (= [] (:data response))))))))

(defn- with-sortable-conversations-fixture!
  "Seeds three conversations differentiated across every sortable column: user
   (first_name/last_name), profile_id, ip_address, created_at, message_count,
   title, and total_tokens. Tests pick a sort key and verify the order of the
   convo-a / convo-m / convo-z handles. Seeded into a private 2026 date window
   so a `date` filter isolates them from any other rows in the test app DB.

   Each sort key yields a distinct permutation, so a bug that ignored `sort_by`
   and always returned `created_at` order would fail five of the six cases.

   Designed orderings (asc):
     created_at:        (a, m, z)   jan-1 / jan-2 / jan-3
     user:              (m, a, z)   first_name Alice / Ben / Chloe
     profile_id:        (z, a, m)   1-profile / 2-profile / 3-profile
     ip_address:        (z, m, a)   10.0.0.1 / 10.0.0.2 / 10.0.0.3
     message_count:     (m, z, a)   counts 1, 2, 3
     total_tokens:      (a, z, m)   tokens 10, 20, 30
     cache_read_tokens: (z, a, m)   cache reads 5, 15 (7+8), 25
     title:             (z, m, a)   Alpha request / Middle request / Zebra request
       (all six permutations of three handles are taken, so these
        necessarily repeat an earlier column's ordering)"
  [thunk]
  (mt/with-premium-features #{:audit-app}
    (mt/with-temp [:model/User {user-a :id} {:email      "[email protected]"
                                             :first_name "Ben"
                                             :last_name  "Anderson"}
                   :model/User {user-m :id} {:email      "[email protected]"
                                             :first_name "Alice"
                                             :last_name  "Mason"}
                   :model/User {user-z :id} {:email      "[email protected]"
                                             :first_name "Chloe"
                                             :last_name  "Zane"}]
      (let [base-path     "ee/metabot-analytics/conversations"
            response-path (str base-path "?date=2026-01-01~2026-01-31")
            convo-a       (str (random-uuid))
            convo-m       (str (random-uuid))
            convo-z       (str (random-uuid))
            jan-1         (offset-date-time "2026-01-01T00:00:00Z")
            jan-2         (offset-date-time "2026-01-02T00:00:00Z")
            jan-3         (offset-date-time "2026-01-03T00:00:00Z")
            jan-4         (offset-date-time "2026-01-04T00:00:00Z")
            seed-msg!     (fn [convo-id profile-id tokens]
                            (insert-message! {:conversation-id convo-id
                                              :created-at      jan-4
                                              :role            "assistant"
                                              :profile-id      profile-id
                                              :total-tokens    tokens
                                              :data            [{:type "text" :text "hi"}]}))]
        (try
          (insert-conversation! {:conversation-id convo-a :user-id user-a
                                 :created-at jan-1 :ip-address "10.0.0.3"
                                 :title "Zebra request"})
          (insert-conversation! {:conversation-id convo-m :user-id user-m
                                 :created-at jan-2 :ip-address "10.0.0.2"
                                 :title "Middle request"})
          (insert-conversation! {:conversation-id convo-z :user-id user-z
                                 :created-at jan-3 :ip-address "10.0.0.1"
                                 :title "Alpha request"})
          (seed-msg! convo-a "2-profile" 4)
          (seed-msg! convo-a "2-profile" 3)
          (seed-msg! convo-a "2-profile" 3)
          (seed-msg! convo-m "3-profile" 30)
          (seed-msg! convo-z "1-profile" 10)
          (seed-msg! convo-z "1-profile" 10)
          (insert-usage! {:conversation-id convo-a :cache-read-tokens 7})
          (insert-usage! {:conversation-id convo-a :cache-read-tokens 8})
          (insert-usage! {:conversation-id convo-m :cache-read-tokens 25})
          (insert-usage! {:conversation-id convo-z :cache-read-tokens 5})
          (thunk {:response-path response-path
                  :convo-a       convo-a
                  :convo-m       convo-m
                  :convo-z       convo-z})
          (finally
            (delete-conversations! [convo-a convo-m convo-z])))))))

(deftest list-conversations-sort-test
  (with-sortable-conversations-fixture!
    (fn [{:keys [response-path convo-a convo-m convo-z]}]
      (doseq [[sort-by asc-order]
              [["created_at"    [convo-a convo-m convo-z]]
               ["user"          [convo-m convo-a convo-z]]
               ["profile_id"    [convo-z convo-a convo-m]]
               ["ip_address"    [convo-z convo-m convo-a]]
               ["message_count" [convo-m convo-z convo-a]]
               ["total_tokens"  [convo-a convo-z convo-m]]
               ["cache_read_tokens" [convo-z convo-a convo-m]]
               ["title"         [convo-z convo-m convo-a]]]]
        (testing (str "sort_by=" sort-by " &sort_dir=asc")
          (let [response (mt/user-http-request :crowberto :get 200
                                               (str response-path "&sort_by=" sort-by "&sort_dir=asc"))]
            (is (= asc-order (map :conversation_id (:data response))))))
        (testing (str "sort_by=" sort-by " &sort_dir=desc")
          (let [response (mt/user-http-request :crowberto :get 200
                                               (str response-path "&sort_by=" sort-by "&sort_dir=desc"))]
            (is (= (reverse asc-order) (map :conversation_id (:data response))))))))))

(deftest list-conversations-invalid-sort-test
  (with-list-conversations-fixture!
    (fn [{:keys [response-path]}]
      (is (some? (:errors (mt/user-http-request :crowberto :get 400
                                                (format "%s&sort_by=drop_table" response-path))))))))

(deftest list-conversations-invalid-sort-dir-test
  (testing "sort-dir is constrained to the {asc, desc} enum"
    (with-list-conversations-fixture!
      (fn [{:keys [response-path]}]
        (is (some? (:errors (mt/user-http-request :crowberto :get 400
                                                  (format "%s&sort_dir=sideways" response-path)))))))))

(deftest list-conversations-user-with-no-conversations-test
  (testing "filtering by a user-id that has no conversations returns an empty data set, not an error"
    (mt/with-premium-features #{:audit-app}
      (mt/with-temp [:model/User {empty-user-id :id} {:email "[email protected]"}]
        (is (=? {:total 0
                 :data  []}
                (mt/user-http-request :crowberto :get 200
                                      (format "ee/metabot-analytics/conversations?user_id=%s"
                                              empty-user-id))))))))

(deftest list-conversations-requires-audit-app-feature-test
  (testing "GET /api/ee/metabot-analytics/conversations is gated by :audit-app and 402s without it"
    (mt/with-premium-features #{}
      (mt/user-http-request :crowberto :get 402 "ee/metabot-analytics/conversations"))))

(defn- with-filters-fixture!
  [thunk]
  (mt/with-premium-features #{:audit-app :tenants}
    (mt/with-temp [:model/Tenant                     {tenant-a :id} {}
                   :model/Tenant                     {tenant-b :id} {}
                   :model/User                       {user-a :id}   {:email     "[email protected]"
                                                                     :tenant_id tenant-a}
                   :model/User                       {user-b :id}   {:email     "[email protected]"
                                                                     :tenant_id tenant-b}
                   :model/PermissionsGroup           {group-id :id} {:name "Metabot analytics filters"}
                   :model/PermissionsGroupMembership _              {:user_id user-a :group_id group-id}]
      (let [convo-1 (str (random-uuid))
            convo-2 (str (random-uuid))
            convo-3 (str (random-uuid))]
        (try
          (insert-conversation! {:conversation-id convo-1 :user-id user-a
                                 :created-at (offset-date-time "2026-01-01T00:00:00Z")})
          (insert-conversation! {:conversation-id convo-2 :user-id user-a
                                 :created-at (offset-date-time "2026-01-02T00:00:00Z")})
          (insert-conversation! {:conversation-id convo-3 :user-id user-b
                                 :created-at (offset-date-time "2026-01-03T00:00:00Z")})
          (thunk {:base-path   "ee/metabot-analytics/conversations"
                  :group-id    group-id
                  :tenant-a-id tenant-a
                  :user-a-id   user-a
                  :convo-1     convo-1
                  :convo-2     convo-2
                  :convo-3     convo-3})
          (finally
            (delete-conversations! [convo-1 convo-2 convo-3])))))))

(deftest list-conversations-filter-test
  (with-filters-fixture!
    (fn [{:keys [base-path group-id tenant-a-id user-a-id convo-1 convo-2 convo-3]}]
      (let [seeded      #{convo-1 convo-2 convo-3}
            request-ids (fn [query-string]
                          (->> (str base-path "?" query-string)
                               (mt/user-http-request :crowberto :get 200)
                               :data
                               (into #{} (map :conversation_id))
                               (set/intersection seeded)))]
        (testing "date narrows to the half-open [start, end) window"
          (is (= #{convo-1 convo-2} (request-ids "date=2026-01-01~2026-01-02"))))
        (testing "group-id narrows to conversations owned by group members"
          (is (= #{convo-1 convo-2} (request-ids (str "group_id=" group-id)))))
        (testing "group_id=1 (All Users) is treated as no-filter"
          (is (= #{convo-1 convo-2 convo-3} (request-ids "group_id=1"))))
        (testing "tenant-id narrows to conversations owned by users in that tenant"
          (is (= #{convo-1 convo-2} (request-ids (str "tenant_id=" tenant-a-id)))))
        (testing "filters compose: group-id + user-id + date narrow cumulatively"
          (is (= #{convo-1} (request-ids (format "group_id=%d&user_id=%d&date=2026-01-01~2026-01-01"
                                                 group-id user-a-id)))))
        (testing "malformed date returns 400"
          (mt/user-http-request :crowberto :get 400 (str base-path "?date=not-a-real-range")))))))

(deftest get-conversation-detail-requires-audit-app-feature-test
  (testing "GET /api/ee/metabot-analytics/conversations/:id is gated by :audit-app and 402s without it"
    (mt/with-premium-features #{}
      (mt/user-http-request :crowberto :get 402
                            (format "ee/metabot-analytics/conversations/%s" (random-uuid))))))

(deftest get-conversation-detail-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id"
      (let [conversation-id (str (random-uuid))
            user-id         (mt/user->id :crowberto)
            jan-1           (offset-date-time "2026-01-01T00:00:00Z")
            jan-2           (offset-date-time "2026-01-02T00:00:00Z")]
        (try
          (insert-conversation! {:conversation-id conversation-id
                                 :user-id         user-id
                                 :created-at      jan-1
                                 :title           "Conversation detail"})
          (insert-message! {:conversation-id conversation-id
                            :created-at      jan-1
                            :role            "user"
                            :profile-id      "ignored-user-profile"
                            :total-tokens    4
                            :data            [{:type "text" :text "hello"}]})
          (insert-message! {:conversation-id conversation-id
                            :created-at      jan-2
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    8
                            :data            [{:type "text" :text "hi there"}]})
          (let [response (mt/user-http-request :crowberto :get 200
                                               (format "ee/metabot-analytics/conversations/%s" conversation-id))]
            (is (= conversation-id (:conversation_id response)))
            (is (= "Conversation detail" (:title response)))
            (is (= {:id         user-id
                    :email      "[email protected]"
                    :first_name "Crowberto"
                    :last_name  "Corv"}
                   (select-keys (:user response) [:id :email :first_name :last_name])))
            (is (nil? (:slack_permalink response)))
            (is (= "internal" (:profile_id response))
                "profile_id comes from the first assistant message, ignoring user-message placeholders")
            (is (= 2 (:message_count response)))
            (is (= [] (:feedback response)))
            (is (= 2 (count (:messages response)))
                "one user prompt + one assistant reply, as row-level messages")
            (let [[user-msg asst-msg] (:messages response)]
              (is (= ["user" "text" "hello" {:type "done"}]
                     [(:role user-msg)
                      (-> user-msg :parts first :type)
                      (-> user-msg :parts first :message)
                      (:status user-msg)]))
              (is (nil? (:parent_message_id user-msg)) "the root prompt has no parent")
              (is (not (contains? asst-msg :kept))
                  "no :kept on the wire; the client derives the current path from sibling order")
              (is (= ["agent" "text" {:type "done"}]
                     [(:role asst-msg) (-> asst-msg :parts first :type) (:status asst-msg)]))
              (is (= (:id user-msg) (:parent_message_id asst-msg))
                  "the reply points at its prompt's row message id")
              (is (string? (:externalId asst-msg)) "the agent message keeps its feedback external id")))
          (finally
            (delete-conversations! [conversation-id])))))))

(defn- with-detail-conversation!
  [thunk]
  (mt/with-premium-features #{:audit-app}
    (let [conversation-id (str (random-uuid))
          user-id         (mt/user->id :crowberto)
          day             #(offset-date-time (format "2026-01-0%dT00:00:00Z" %))
          insert!         #(insert-message! (assoc % :conversation-id conversation-id))
          fetch           #(mt/user-http-request :crowberto :get 200
                                                 (format "ee/metabot-analytics/conversations/%s" conversation-id))]
      (try
        (insert-conversation! {:conversation-id conversation-id :user-id user-id :created-at (day 1)})
        (thunk {:user-id user-id :day day :insert! insert! :fetch fetch})
        (finally
          (delete-conversations! [conversation-id]))))))

(defn- message-by-text
  [messages text]
  (or (some (fn [message]
              (when (some #(= text (:message %)) (:parts message))
                message))
            messages)
      (throw (ex-info (str "Message not found: " text) {:text text}))))

(deftest get-conversation-detail-attempts-test
  (testing "a prompt's regenerated attempts surface as flat, chronologically ordered sibling messages"
    (with-detail-conversation!
      (fn [{:keys [insert! day fetch]}]
        (insert! {:created-at (day 1) :role "user" :profile-id "p" :total-tokens 2
                  :data [{:type "text" :text "count the orders"}]})
        (insert! {:created-at (day 2) :role "assistant" :profile-id "internal" :total-tokens 10
                  :deleted-at (day 4) :data [{:type "text" :text "first try"}]})
        (insert! {:created-at (day 3) :role "assistant" :profile-id "internal" :total-tokens 20
                  :deleted-at (day 4) :data [{:type "text" :text "second try"}]})
        (insert! {:created-at (day 4) :role "assistant" :profile-id "internal" :total-tokens 30
                  :data [{:type "text" :text "kept answer"}]})
        (let [{:keys [messages total_tokens message_count]} (fetch)
              [prompt & attempts] messages]
          (is (= ["first try" "second try" "kept answer"]
                 (map #(-> % :parts first :message) attempts)))
          (is (every? #(= (:id prompt) (:parent_message_id %)) attempts))
          (is (= [62 4] [total_tokens message_count])))))))

(deftest get-conversation-detail-parent-pointers-test
  (testing "a follow-up prompt points at the kept (live) reply, not a regenerated-away one"
    (with-detail-conversation!
      (fn [{:keys [insert! day fetch]}]
        (insert! {:created-at (day 1) :role "user" :profile-id "p" :total-tokens 1
                  :data [{:type "text" :text "q1"}]})
        (insert! {:created-at (day 2) :role "assistant" :profile-id "internal" :total-tokens 1
                  :deleted-at (day 3) :data [{:type "text" :text "discarded"}]})
        (insert! {:created-at (day 3) :role "assistant" :profile-id "internal" :total-tokens 1
                  :data [{:type "text" :text "kept"}]})
        (insert! {:created-at (day 4) :role "user" :profile-id "p" :total-tokens 1
                  :data [{:type "text" :text "q2"}]})
        (insert! {:created-at (day 5) :role "assistant" :profile-id "internal" :total-tokens 1
                  :data [{:type "text" :text "a2"}]})
        (let [messages (:messages (fetch))
              q1       (message-by-text messages "q1")
              kept     (message-by-text messages "kept")
              q2       (message-by-text messages "q2")]
          (is (nil? (:parent_message_id q1)))
          (is (= (:id q1) (:parent_message_id kept)))
          (is (= (:id kept) (:parent_message_id q2))))))))

(deftest get-conversation-detail-turn-with-no-live-reply-test
  (testing "a turn whose only reply was soft-deleted still keeps the following turn on the path"
    (with-detail-conversation!
      (fn [{:keys [insert! day fetch]}]
        (insert! {:created-at (day 1) :role "user" :profile-id "p" :total-tokens 1
                  :data [{:type "text" :text "q1"}]})
        (insert! {:created-at (day 2) :role "assistant" :profile-id "internal" :total-tokens 1
                  :deleted-at (day 3) :data [{:type "text" :text "orphaned"}]})
        (insert! {:created-at (day 4) :role "user" :profile-id "p" :total-tokens 1
                  :data [{:type "text" :text "q2"}]})
        (insert! {:created-at (day 5) :role "assistant" :profile-id "internal" :total-tokens 1
                  :data [{:type "text" :text "a2"}]})
        (let [messages (:messages (fetch))
              q1       (message-by-text messages "q1")
              q2       (message-by-text messages "q2")]
          (is (= (:id q1) (:parent_message_id q2))))))))

(deftest get-conversation-detail-in-flight-attempt-test
  (testing "a still-streaming reply surfaces as an in-progress message"
    (with-detail-conversation!
      (fn [{:keys [insert! fetch]}]
        (insert! {:role "user" :profile-id "p" :total-tokens 3
                  :data [{:type "text" :text "still thinking?"}]})
        (insert! {:role "assistant" :profile-id "internal" :total-tokens 0 :data [] :finished nil})
        (let [{:keys [messages message_count]} (fetch)]
          (is (= ["user" "agent"] (map :role messages)))
          (is (= {:type "in_progress"} (:status (second messages))))
          (is (= [] (:parts (second messages))))
          (is (= 2 message_count)))))))

(deftest get-conversation-detail-incomplete-status-test
  (testing "a reply the provider cut off surfaces as an incomplete message"
    (with-detail-conversation!
      (fn [{:keys [insert! day fetch]}]
        (insert! {:created-at (day 1) :role "user" :profile-id "p" :total-tokens 3
                  :data [{:type "text" :text "a long question"}]})
        (insert! {:created-at (day 2) :role "assistant" :profile-id "internal" :total-tokens 9 :finished true
                  :finish-reason "length" :data [{:type "text" :text "cut o"}]})
        (insert! {:created-at (day 3) :role "user" :profile-id "p" :total-tokens 3
                  :data [{:type "text" :text "go on"}]})
        (insert! {:created-at (day 4) :role "assistant" :profile-id "internal" :total-tokens 9 :finished true
                  :finish-reason "length" :context-window-full true
                  :data [{:type "text" :text "cut again"}]})
        (let [messages (:messages (fetch))]
          (testing "a row with no full-window verdict is a plain length stop"
            (is (= {:type "incomplete" :finishReason "length"}
                   (:status (message-by-text messages "cut o")))))
          (testing "a row saved as full reads as full here too, the same as on chat reload"
            (is (= {:type "incomplete" :finishReason "length" :contextWindowFull true}
                   (:status (message-by-text messages "cut again"))))))))))

(deftest get-conversation-detail-feedback-on-discarded-attempt-test
  (testing "feedback on a regenerated-away attempt still resolves to that attempt's message"
    (with-detail-conversation!
      (fn [{:keys [insert! day user-id fetch]}]
        (let [discarded-ext (str (random-uuid))]
          (insert! {:created-at (day 1) :role "user" :profile-id "p" :total-tokens 2
                    :data [{:type "text" :text "help"}]})
          (let [discarded-id (insert! {:created-at (day 2) :role "assistant" :profile-id "internal"
                                       :total-tokens 10 :deleted-at (day 3) :external-id discarded-ext
                                       :data [{:type "text" :text "thumbs-downed answer"}]})]
            (insert! {:created-at (day 3) :role "assistant" :profile-id "internal" :total-tokens 20
                      :data [{:type "text" :text "kept answer"}]})
            (insert-feedback! {:message-id discarded-id :user-id user-id :positive false
                               :issue-type "incorrect" :freeform "wrong table"
                               :created-at (day 2) :updated-at (day 2)})
            (let [{:keys [feedback messages]} (fetch)
                  attempt-exts (into #{} (keep :externalId) messages)]
              (is (= 1 (count feedback)))
              (is (= discarded-ext (:external_id (first feedback))))
              (is (contains? attempt-exts discarded-ext)))))))))

(deftest get-conversation-detail-queries-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id returns generated queries"
      (let [conversation-id (str (random-uuid))
            user-id         (mt/user->id :crowberto)
            jan-1           (offset-date-time "2026-01-01T00:00:00Z")
            jan-2           (offset-date-time "2026-01-02T00:00:00Z")
            jan-3           (offset-date-time "2026-01-03T00:00:00Z")
            sql             "SELECT * FROM orders"]
        (try
          (insert-conversation! {:conversation-id conversation-id
                                 :user-id         user-id
                                 :created-at      jan-1
                                 :title           "Conversation with queries"})
          ;; user prompt
          (insert-message! {:conversation-id conversation-id
                            :created-at      jan-1
                            :role            "user"
                            :profile-id      "ignored-user-model"
                            :total-tokens    3
                            :data            [{:type "text" :text "show me orders"}]})
          ;; successful create_sql_query — should appear in :queries
          (insert-message! {:conversation-id conversation-id
                            :created-at      jan-2
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    20
                            :data            [{:type "text" :text "Sure, here it is."}
                                              {:type         "tool-create_sql_query"
                                               :toolCallId   "call-success"
                                               :state        "output-available"
                                               :input        {:database_id (mt/id) :sql_query sql}
                                               :output       {:output "<result>...</result>"
                                                              :structured_output {:query-id      "qid-success"
                                                                                  :query-content sql
                                                                                  :query         {:database (mt/id)
                                                                                                  :type     :native
                                                                                                  :native   {:query sql}}
                                                                                  :database      (mt/id)}}}]})
          ;; failed create_sql_query (only :output, no structured output) — should NOT appear in :queries
          (insert-message! {:conversation-id conversation-id
                            :created-at      jan-3
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    10
                            :data            [{:type         "tool-create_sql_query"
                                               :toolCallId   "call-failed"
                                               :state        "output-available"
                                               :input        {:database_id (mt/id) :sql_query "SELEKT bad"}
                                               :output       {:output "<result>SQL query construction failed.</result>"}}]})
          (let [response (mt/user-http-request :crowberto :get 200
                                               (format "ee/metabot-analytics/conversations/%s" conversation-id))
                queries  (:queries response)]
            (is (= 1 (count queries))
                "errored tool call should be filtered out")
            (let [q (first queries)]
              (is (= "create_sql_query" (:tool q)))
              (is (= "sql"               (:query_type q)))
              (is (= "qid-success"       (:query_id q)))
              (is (= sql                 (:sql q)))
              (is (nil?                  (:mbql q)))
              (is (= (mt/id)             (:database_id q)))
              ;; Tables extraction goes through the real Macaw path — sample data has an "orders" table.
              (is (contains? (set (:tables q)) "orders"))))
          (finally
            (delete-conversations! [conversation-id])))))))

(defn- search-part
  [call-id]
  {:type         "tool-search"
   :toolCallId   call-id
   :state        "output-available"
   :input        {:q "foo"}
   :output       {:output "<result>...</result>"}})

(defn- with-search-count-fixture!
  "Seed conversations with varying numbers of search tool parts so we
   can assert both list and detail `:search_count` behavior without perturbing
   the existing list fixture."
  [thunk]
  (mt/with-premium-features #{:audit-app}
    (mt/with-temp [:model/User {test-user-id :id} {:email      "[email protected]"
                                                   :first_name "Search"
                                                   :last_name  "Counter"}]
      (let [convo-none    (str (random-uuid))
            convo-two     (str (random-uuid))
            convo-errored (str (random-uuid))
            jan-1         (offset-date-time "2026-02-01T00:00:00Z")
            jan-2         (offset-date-time "2026-02-02T00:00:00Z")
            jan-3         (offset-date-time "2026-02-03T00:00:00Z")]
        (try
          (insert-conversation! {:conversation-id convo-none
                                 :user-id         test-user-id
                                 :created-at      jan-1
                                 :title           "no searches"})
          (insert-conversation! {:conversation-id convo-two
                                 :user-id         test-user-id
                                 :created-at      jan-2
                                 :title           "two searches across two messages"})
          (insert-conversation! {:conversation-id convo-errored
                                 :user-id         test-user-id
                                 :created-at      jan-3
                                 :title           "one errored search still counts"})
          ;; convo-none: only text, no search calls.
          (insert-message! {:conversation-id convo-none
                            :created-at      jan-1
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    5
                            :data            [{:type "text" :text "no tools here"}]})
          ;; convo-two: one search in msg 1, one search in msg 2 (plus an unrelated tool).
          (insert-message! {:conversation-id convo-two
                            :created-at      jan-2
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    10
                            :data            [(search-part "call-a")]})
          (insert-message! {:conversation-id convo-two
                            :created-at      jan-2
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    10
                            :data            [{:type "tool-analyze_chart" :toolCallId "call-x"
                                               :state "input-available" :input {}}
                                              (search-part "call-b")]})
          ;; convo-errored: a single search whose call errored — should still count.
          (insert-message! {:conversation-id convo-errored
                            :created-at      jan-3
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    4
                            :data            [{:type         "tool-search"
                                               :toolCallId   "call-err"
                                               :state        "output-error"
                                               :input        {:q "foo"}
                                               :errorText    "boom"}]})
          (thunk {:test-user-id  test-user-id
                  :convo-none    convo-none
                  :convo-two     convo-two
                  :convo-errored convo-errored})
          (finally
            (delete-conversations! [convo-none convo-two convo-errored])))))))

(deftest search-count-test
  (with-search-count-fixture!
    (fn [{:keys [test-user-id convo-none convo-two convo-errored]}]
      (testing "list endpoint surfaces per-conversation search counts (errored calls still count)"
        (let [response (mt/user-http-request :crowberto :get 200
                                             (format "ee/metabot-analytics/conversations?user_id=%s" test-user-id))
              by-id    (into {} (map (juxt :conversation_id identity)) (:data response))]
          (is (= {convo-none 0, convo-two 2, convo-errored 1}
                 (update-vals by-id :search_count)))))
      (testing "pagination scopes the hydration batch to the page"
        ;; Default sort is created_at desc: [convo-errored convo-two convo-none].
        (let [response (mt/user-http-request :crowberto :get 200
                                             (format "ee/metabot-analytics/conversations?user_id=%s&limit=1&offset=1"
                                                     test-user-id))]
          (is (= [convo-two] (map :conversation_id (:data response))))
          (is (= 2 (:search_count (first (:data response)))))))
      (testing "detail endpoint surfaces the same counts"
        (doseq [[convo expected] [[convo-none 0] [convo-two 2] [convo-errored 1]]]
          (let [response (mt/user-http-request :crowberto :get 200
                                               (format "ee/metabot-analytics/conversations/%s" convo))]
            (is (= expected (:search_count response))
                (format "expected search_count=%d for %s" expected convo))))))))

(defn- query-tool-part
  [call-id tool-name]
  {:type         (str "tool-" tool-name)
   :toolCallId   call-id
   :state        "output-available"
   :input        {}
   :output       {:output "ok"}})

(defn- with-query-count-fixture!
  "Seed conversations that exercise `:query_count` for every query-generation
   tool — create_sql_query, edit_sql_query, replace_sql_query, and
   construct_notebook_query. Non-query tool calls (search) are sprinkled in
   to verify they don't bump `:query_count`."
  [thunk]
  (mt/with-premium-features #{:audit-app}
    (mt/with-temp [:model/User {test-user-id :id} {:email      "[email protected]"
                                                   :first_name "Query"
                                                   :last_name  "Counter"}]
      (let [convo-none  (str (random-uuid))
            convo-mixed (str (random-uuid))
            convo-edits (str (random-uuid))
            mar-1       (offset-date-time "2026-03-10T00:00:00Z")
            mar-2       (offset-date-time "2026-03-11T00:00:00Z")
            mar-3       (offset-date-time "2026-03-12T00:00:00Z")]
        (try
          (insert-conversation! {:conversation-id convo-none
                                 :user-id         test-user-id
                                 :created-at      mar-1
                                 :title           "no query tools"})
          (insert-conversation! {:conversation-id convo-mixed
                                 :user-id         test-user-id
                                 :created-at      mar-2
                                 :title           "create + edit + notebook across messages"})
          (insert-conversation! {:conversation-id convo-edits
                                 :user-id         test-user-id
                                 :created-at      mar-3
                                 :title           "only edit/replace — counted as queries"})
          ;; convo-none: only a search, no new-query tools.
          (insert-message! {:conversation-id convo-none
                            :created-at      mar-1
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    5
                            :data            [(search-part "call-s")]})
          ;; convo-mixed: one search + create_sql_query in msg 1, then one edit_sql_query
          ;; and one construct_notebook_query in msg 2 — three counted queries.
          (insert-message! {:conversation-id convo-mixed
                            :created-at      mar-2
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    10
                            :data            [(search-part "call-mixed-s")
                                              (query-tool-part "call-a" "create_sql_query")]})
          (insert-message! {:conversation-id convo-mixed
                            :created-at      mar-2
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    10
                            :data            [(query-tool-part "call-b" "edit_sql_query")
                                              (query-tool-part "call-c" "construct_notebook_query")]})
          ;; convo-edits: search + edit + replace
          (insert-message! {:conversation-id convo-edits
                            :created-at      mar-3
                            :role            "assistant"
                            :profile-id      "internal"
                            :total-tokens    4
                            :data            [(search-part "call-edits-s")
                                              (query-tool-part "call-e" "edit_sql_query")
                                              (query-tool-part "call-r" "replace_sql_query")]})
          (thunk {:test-user-id test-user-id
                  :convo-none   convo-none
                  :convo-mixed  convo-mixed
                  :convo-edits  convo-edits})
          (finally
            (delete-conversations! [convo-none convo-mixed convo-edits])))))))

(deftest query-count-test
  (with-query-count-fixture!
    (fn [{:keys [test-user-id convo-none convo-mixed convo-edits]}]
      (testing "list endpoint: counts every query-generation tool (incl. edit/replace), excludes non-query tools like search"
        (let [response (mt/user-http-request :crowberto :get 200
                                             (format "ee/metabot-analytics/conversations?user_id=%s" test-user-id))
              by-id    (into {} (map (juxt :conversation_id identity)) (:data response))]
          (is (= {convo-none 0, convo-mixed 3, convo-edits 2}
                 (update-vals by-id :query_count)))))
      (testing "detail endpoint surfaces the same counts"
        (doseq [[convo expected] [[convo-none 0] [convo-mixed 3] [convo-edits 2]]]
          (let [response (mt/user-http-request :crowberto :get 200
                                               (format "ee/metabot-analytics/conversations/%s" convo))]
            (is (= expected (:query_count response))
                (format "expected query_count=%d for %s" expected convo))))))))

(deftest get-conversation-detail-slack-permalink-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id returns a Slack permalink when metadata is present"
      (let [conversation-id (str (random-uuid))
            user-id         (mt/user->id :crowberto)
            permalink       "https://example.slack.com/archives/C123/p1712785577123456"]
        (try
          (insert-conversation! {:conversation-id  conversation-id
                                 :user-id          user-id
                                 :title            "Slack conversation"
                                 :slack-team-id    "T123"
                                 :slack-channel-id "C123"
                                 :slack-thread-ts  "1712785577.123456"})
          (mt/with-dynamic-fn-redefs [slackbot.api/conversation-permalink (fn [channel ts]
                                                                            (is (= "C123" channel))
                                                                            (is (= "1712785577.123456" ts))
                                                                            permalink)]
            (let [response (mt/user-http-request :crowberto :get 200
                                                 (format "ee/metabot-analytics/conversations/%s" conversation-id))]
              (is (= permalink (:slack_permalink response)))))
          (finally
            (delete-conversations! [conversation-id])))))))

(defn- with-ip-address-fixture!
  "Seed conversations with varying IP-address state so we can assert both list
   and detail `:ip_address` behavior without perturbing the list fixture."
  [thunk]
  (mt/with-premium-features #{:audit-app}
    (mt/with-temp [:model/User {test-user-id :id} {:email      "[email protected]"
                                                   :first_name "IP"
                                                   :last_name  "Tester"}]
      (let [convo-web   (str (random-uuid))
            convo-slack (str (random-uuid))
            convo-null  (str (random-uuid))
            jan-1       (offset-date-time "2026-03-01T00:00:00Z")
            jan-2       (offset-date-time "2026-03-02T00:00:00Z")
            jan-3       (offset-date-time "2026-03-03T00:00:00Z")]
        (try
          (insert-conversation! {:conversation-id convo-web
                                 :user-id         test-user-id
                                 :created-at      jan-1
                                 :title           "web conversation"
                                 :ip-address      "1.2.3.4"})
          (insert-conversation! {:conversation-id convo-slack
                                 :user-id         test-user-id
                                 :created-at      jan-2
                                 :title           "slack conversation"
                                 :slack-team-id   "T123"
                                 :slack-channel-id "C123"
                                 :slack-thread-ts  "1712785577.123456"})
          (insert-conversation! {:conversation-id convo-null
                                 :user-id         test-user-id
                                 :created-at      jan-3
                                 :title           "legacy conversation with no ip"})
          (thunk {:test-user-id test-user-id
                  :convo-web    convo-web
                  :convo-slack  convo-slack
                  :convo-null   convo-null})
          (finally
            (delete-conversations! [convo-web convo-slack convo-null])))))))

(deftest ^:parallel get-conversation-detail-requires-superuser-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id requires superuser"
      (is (= "You don't have permissions to do that."
             (mt/user-http-request :rasta :get 403
                                   (format "ee/metabot-analytics/conversations/%s"
                                           (str (random-uuid)))))))))

(deftest ^:parallel get-conversation-detail-404-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id 404s for unknown conversations"
      (mt/user-http-request :crowberto :get 404
                            (format "ee/metabot-analytics/conversations/%s"
                                    (str (random-uuid)))))))

(deftest get-conversation-detail-feedback-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id surfaces user-submitted feedback on the :feedback key, ordered by submission time"
      (let [conversation-id (str (random-uuid))
            user-id         (mt/user->id :crowberto)
            jan-1           (offset-date-time "2026-04-01T00:00:00Z")
            jan-2           (offset-date-time "2026-04-02T00:00:00Z")
            jan-3           (offset-date-time "2026-04-03T00:00:00Z")]
        (try
          (insert-conversation! {:conversation-id conversation-id
                                 :user-id         user-id
                                 :created-at      jan-1
                                 :title           "feedback conversation"})
          (let [msg-1 (insert-message! {:conversation-id conversation-id :created-at jan-2
                                        :role "assistant" :profile-id "gpt-5" :total-tokens 5
                                        :data [{:type "text" :text "first answer"}]})
                msg-2 (insert-message! {:conversation-id conversation-id :created-at jan-3
                                        :role "assistant" :profile-id "gpt-5" :total-tokens 7
                                        :data [{:type "text" :text "second answer"}]})]
            (run! insert-feedback!
                  [{:message-id msg-1 :user-id user-id :positive true  :freeform "great" :created-at jan-2}
                   {:message-id msg-2 :user-id user-id :positive false :issue-type "not-factual"
                    :freeform "wrong" :created-at jan-3}])
            (let [feedback (:feedback (mt/user-http-request :crowberto :get 200
                                                            (format "ee/metabot-analytics/conversations/%s"
                                                                    conversation-id)))]
              (is (= 2 (count feedback)))
              (is (= [true false] (map :positive feedback)))
              (is (= [msg-1 msg-2] (map :message_id feedback)))
              (is (= "not-factual" (:issue_type (second feedback))))
              (is (every? (comp string? :external_id) feedback)
                  "each feedback row carries the parent metabot_message.external_id so the admin UI can link to it")
              (is (every? (comp pos-int? :id) feedback)
                  "each feedback row has a surrogate id after the multi-user migration")
              (is (= [user-id user-id] (map :user_id feedback))
                  "each feedback row carries the submitter's user_id")
              (is (= [{:id         user-id
                       :email      "[email protected]"
                       :first_name "Crowberto"
                       :last_name  "Corv"}
                      {:id         user-id
                       :email      "[email protected]"
                       :first_name "Crowberto"
                       :last_name  "Corv"}]
                     (map #(select-keys (:user %) [:id :email :first_name :last_name]) feedback))
                  "submitter is hydrated on each feedback row")))
          (finally
            (delete-conversations! [conversation-id])))))))

(deftest get-conversation-detail-feedback-multi-user-test
  (mt/with-premium-features #{:audit-app}
    (testing "GET /api/ee/metabot-analytics/conversations/:id returns one feedback row per submitter when multiple users rate the same assistant message"
      (mt/with-temp [:model/User {participant-id :id} {:email      "[email protected]"
                                                       :first_name "Feedback"
                                                       :last_name  "Participant"}]
        (let [conversation-id (str (random-uuid))
              owner-id        (mt/user->id :crowberto)
              apr-1           (offset-date-time "2026-04-10T00:00:00Z")
              apr-2           (offset-date-time "2026-04-11T00:00:00Z")
              apr-3           (offset-date-time "2026-04-12T00:00:00Z")]
          (try
            (insert-conversation! {:conversation-id conversation-id
                                   :user-id         owner-id
                                   :created-at      apr-1
                                   :title           "shared thread feedback"})
            (let [assistant-msg (insert-message! {:conversation-id conversation-id :created-at apr-2
                                                  :role "assistant" :profile-id "slackbot" :total-tokens 9
                                                  :data [{:type "text" :text "shared answer"}]})]
              (run! insert-feedback!
                    [{:message-id assistant-msg :user-id owner-id :positive true
                      :freeform "looks good" :created-at apr-2}
                     {:message-id assistant-msg :user-id participant-id :positive false
                      :issue-type "not-factual" :freeform "disagree" :created-at apr-3}])
              (let [feedback (:feedback (mt/user-http-request :crowberto :get 200
                                                              (format "ee/metabot-analytics/conversations/%s"
                                                                      conversation-id)))
                    by-user  (into {} (map (juxt :user_id identity)) feedback)]
                (is (= 2 (count feedback)))
                (is (= #{owner-id participant-id} (set (map :user_id feedback)))
                    "both submitters appear as distinct rows on the same message")
                (is (= #{assistant-msg} (set (map :message_id feedback)))
                    "both rows point to the same assistant message")
                (is (apply distinct? (map :id feedback))
                    "surrogate ids disambiguate the rows")
                (is (= {:id         owner-id
                        :email      "[email protected]"
                        :first_name "Crowberto"
                        :last_name  "Corv"}
                       (select-keys (:user (get by-user owner-id)) [:id :email :first_name :last_name])))
                (is (= {:id         participant-id
                        :email      "[email protected]"
                        :first_name "Feedback"
                        :last_name  "Participant"}
                       (select-keys (:user (get by-user participant-id)) [:id :email :first_name :last_name])))
                (is (true? (:positive (get by-user owner-id))))
                (is (false? (:positive (get by-user participant-id))))
                (is (= "not-factual" (:issue_type (get by-user participant-id))))))
            (finally
              (delete-conversations! [conversation-id]))))))))

(deftest ip-address-test
  (with-ip-address-fixture!
    (fn [{:keys [test-user-id convo-web convo-slack convo-null]}]
      (testing "list endpoint surfaces IP for web conversations, nil for Slack/legacy"
        (let [response (mt/user-http-request :crowberto :get 200
                                             (format "ee/metabot-analytics/conversations?user_id=%s" test-user-id))
              by-id    (into {} (map (juxt :conversation_id identity)) (:data response))]
          (is (= {convo-web "1.2.3.4", convo-slack nil, convo-null nil}
                 (update-vals by-id :ip_address)))))
      (testing "pagination preserves ip_address for rows on page 2"
        ;; Default sort is created_at desc: [convo-null convo-slack convo-web].
        (let [response (mt/user-http-request :crowberto :get 200
                                             (format "ee/metabot-analytics/conversations?user_id=%s&limit=1&offset=1"
                                                     test-user-id))]
          (is (= [convo-slack] (map :conversation_id (:data response))))
          (is (nil? (:ip_address (first (:data response)))))))
      (testing "detail endpoint surfaces the same values"
        (doseq [[convo expected] [[convo-web "1.2.3.4"] [convo-slack nil] [convo-null nil]]]
          (let [response (mt/user-http-request :crowberto :get 200
                                               (format "ee/metabot-analytics/conversations/%s" convo))]
            (is (= expected (:ip_address response))
                (format "expected ip_address=%s for %s" (pr-str expected) convo))))))))