Skip to content

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

FEATURE: Add AI audit log admin (#42667)

Sam91a8ca9a169b
diff --git a/db/structure.sql b/db/structure.sql
index 290c6592911..d35200eda7e 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -17539,6 +17539,41 @@ CREATE INDEX idx_access_control_lists_allowed_group_ids ON public.access_control
CREATE INDEX idx_access_control_lists_allowed_user_ids ON public.access_control_lists USING gin (allowed_user_ids);
+--
+-- Name: idx_ai_api_audit_logs_failed_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_ai_api_audit_logs_failed_id ON public.ai_api_audit_logs USING btree (id) WHERE (((response_status IS NOT NULL) AND ((response_status < 200) OR (response_status > 299))) OR ((response_status IS NULL) AND (COALESCE(response_tokens, 0) <= 0)));
+
+
+--
+-- Name: idx_ai_api_audit_logs_feature_name_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_ai_api_audit_logs_feature_name_id ON public.ai_api_audit_logs USING btree (feature_name, id) WHERE (feature_name IS NOT NULL);
+
+
+--
+-- Name: idx_ai_api_audit_logs_payload_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_ai_api_audit_logs_payload_id ON public.ai_api_audit_logs USING btree (id) WHERE ((raw_request_payload IS NOT NULL) OR (raw_response_payload IS NOT NULL));
+
+
+--
+-- Name: idx_ai_api_audit_logs_retried_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_ai_api_audit_logs_retried_id ON public.ai_api_audit_logs USING btree (id) WHERE (request_attempts IS NOT NULL);
+
+
+--
+-- Name: idx_ai_api_audit_logs_user_id_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_ai_api_audit_logs_user_id_id ON public.ai_api_audit_logs USING btree (user_id, id);
+
+
--
-- Name: idx_ai_bot_conversation_stars_topic_id; Type: INDEX; Schema: public; Owner: -
--
@@ -23190,6 +23225,11 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20260818045317'),
+('20260818045314'),
+('20260818045311'),
+('20260818045308'),
+('20260818045305'),
('20260817054353'),
('20260817054044'),
('20260814083721'),
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-logs.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-logs.gjs
new file mode 100644
index 00000000000..4d7ddcba207
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-logs.gjs
@@ -0,0 +1,821 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { next } from "@ember/runloop";
+import { service } from "@ember/service";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import UserChooser from "discourse/select-kit/components/user-chooser";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DDateTimeInputRange from "discourse/ui-kit/d-date-time-input-range";
+import DLoadMore from "discourse/ui-kit/d-load-more";
+import DPageSubheader from "discourse/ui-kit/d-page-subheader";
+import { i18n } from "discourse-i18n";
+import AiLogRow from "discourse/plugins/discourse-ai/discourse/components/ai-log-row";
+import AiLogDetailModal from "./modal/ai-log-detail-modal";
+import AiLogRetentionModal from "./modal/ai-log-retention-modal";
+
+const ALL_FILTER_VALUE = "__all__";
+const MAX_SAFE_ID = Number.MAX_SAFE_INTEGER;
+const PERIODS = {
+ hour: 1,
+ day: 24,
+ week: 24 * 7,
+};
+
+export default class AiLogs extends Component {
+ @service currentUser;
+ @service modal;
+ @service router;
+ @service toasts;
+
+ @tracked logs = [];
+ @tracked meta = {};
+ @tracked models = [];
+ @tracked features = [];
+ @tracked loading = false;
+ @tracked loadingMore = false;
+ @tracked selectedPeriod;
+ @tracked selectedOutcome;
+ @tracked hasRetries = false;
+ @tracked selectedModel;
+ @tracked selectedFeature;
+ @tracked selectedUsernames = [];
+ @tracked unattributed = false;
+ @tracked idType = "id";
+ @tracked idValue;
+ @tracked startDate;
+ @tracked endDate;
+
+ filterFormApi;
+ _requestId = 0;
+ _openLogId;
+
+ constructor() {
+ super(...arguments);
+ window.addEventListener("popstate", this.syncDetailsFromLocation);
+ this.logs = this.args.model.logs || [];
+ this.meta = this.args.model.meta || {};
+ this.models = this.args.model.models || [];
+ this.features = this.mergedFeatures(this.args.model.features, this.logs);
+ this.initializeFilters(this.args.queryParams);
+
+ if (this.args.queryParams.details) {
+ next(() =>
+ this.openDetails(this.args.queryParams.details, { updateUrl: false })
+ );
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ window.removeEventListener("popstate", this.syncDetailsFromLocation);
+ if (this._openLogId) {
+ this.modal.close();
+ }
+ }
+
+ @action
+ syncDetailsFromLocation() {
+ const logId = new URL(window.location.href).searchParams.get("details");
+ if (logId && String(logId) !== String(this._openLogId)) {
+ this.openDetails(logId, { updateUrl: false });
+ } else if (!logId && this._openLogId) {
+ this._openLogId = undefined;
+ this.modal.close();
+ }
+ }
+
+ mergedFeatures(features = [], logs = []) {
+ return [
+ ...new Set([
+ ...features,
+ ...logs.map((log) => log.feature_name).filter(Boolean),
+ ]),
+ ].sort();
+ }
+
+ initializeFilters(params = {}) {
+ this.selectedPeriod = params.period || undefined;
+ this.selectedOutcome = params.outcome || undefined;
+ this.hasRetries =
+ params.has_retries === "true" || params.has_retries === true;
+ this.selectedModel = params.model ? String(params.model) : undefined;
+ this.selectedFeature = params.feature || undefined;
+ this.selectedUsernames = params.username ? [params.username] : [];
+ this.unattributed =
+ params.unattributed === "true" || params.unattributed === true;
+ this.idType = params.id_type || "id";
+ this.idValue = params.id_value || undefined;
+ this.startDate = params.start_date
+ ? moment(params.start_date).toDate()
+ : moment().subtract(24, "hours").toDate();
+ this.endDate = params.end_date
+ ? moment(params.end_date).toDate()
+ : new Date();
+ }
+
+ @cached
+ get filterFormData() {
+ return {
+ period: this.selectedPeriod,
+ date_range: { from: this.startDate, to: this.endDate },
+ outcome: this.selectedOutcome || ALL_FILTER_VALUE,
+ model: this.selectedModel || ALL_FILTER_VALUE,
+ feature: this.selectedFeature,
+ usernames: this.selectedUsernames,
+ has_retries: this.hasRetries,
+ unattributed: this.unattributed,
+ id_type: this.idType,
+ id_value: this.idValue,
+ };
+ }
+
+ get periodOptions() {
+ return [
+ { id: "hour", name: i18n("discourse_ai.logs.periods.hour") },
+ { id: "day", name: i18n("discourse_ai.logs.periods.day") },
+ { id: "week", name: i18n("discourse_ai.logs.periods.week") },
+ { id: "custom", name: i18n("discourse_ai.logs.periods.custom") },
+ ];
+ }
+
+ get outcomeOptions() {
+ return [
+ { id: "successful", name: i18n("discourse_ai.logs.successful") },
+ { id: "failed", name: i18n("discourse_ai.logs.failed") },
+ ];
+ }
+
+ get idTypeOptions() {
+ return [
+ { id: "id", name: i18n("discourse_ai.logs.log_id") },
+ { id: "topic_id", name: i18n("discourse_ai.logs.topic_id") },
+ { id: "post_id", name: i18n("discourse_ai.logs.post_id") },
+ ];
+ }
+
+ get modelOptions() {
+ return this.models.map((model) => ({
+ id: String(model.id),
+ name: model.name,
+ }));
+ }
+
+ get hasFilters() {
+ return Boolean(
+ this.selectedPeriod ||
+ this.selectedOutcome ||
+ this.hasRetries ||
+ this.selectedModel ||
+ this.selectedFeature ||
+ this.selectedUsernames.length ||
+ this.unattributed ||
+ this.idValue
+ );
+ }
+
+ get lifecycleSummary() {
+ const detailed = this.meta.retention?.detailed_days ?? 0;
+ const summary = this.meta.retention?.summary_days ?? 0;
+
+ if (detailed === 0 && summary === 0) {
+ return i18n("discourse_ai.logs.retention.lifecycle.complete_forever");
+ }
+ if (detailed === 0) {
+ return i18n("discourse_ai.logs.retention.lifecycle.detail_until_delete", {
+ summary,
+ });
+ }
+ if (summary === 0) {
+ return i18n("discourse_ai.logs.retention.lifecycle.summary_forever", {
+ detailed,
+ });
+ }
+ return i18n("discourse_ai.logs.retention.lifecycle.finite", {
+ detailed,
+ summary,
+ });
+ }
+
+ get requestParams() {
+ const params = {
+ outcome: this.selectedOutcome || undefined,
+ has_retries: this.hasRetries || undefined,
+ llm_id: this.selectedModel || undefined,
+ feature: this.selectedFeature || undefined,
+ username: this.selectedUsernames[0] || undefined,
+ unattributed: this.unattributed || undefined,
+ };
+
+ if (this.idValue) {
+ params[this.idType] = this.idValue;
+ return params;
+ }
+
+ if (this.selectedPeriod === "custom") {
+ params.start_date = moment(this.startDate).format("YYYY-MM-DD");
+ params.end_date = moment(this.endDate).format("YYYY-MM-DD");
+ params.timezone =
+ this.currentUser?.user_option?.timezone || moment.tz.guess();
+ } else if (this.selectedPeriod) {
+ params.start_date = moment()
+ .subtract(PERIODS[this.selectedPeriod], "hours")
+ .toISOString();
+ params.end_date = moment().toISOString();
+ }
+
+ return params;
+ }
+
+ get queryParams() {
+ return {
+ period: this.selectedPeriod || null,
+ start_date:
+ this.selectedPeriod === "custom"
+ ? moment(this.startDate).format("YYYY-MM-DD")
+ : null,
+ end_date:
+ this.selectedPeriod === "custom"
+ ? moment(this.endDate).format("YYYY-MM-DD")
+ : null,
+ outcome: this.selectedOutcome || null,
+ has_retries: this.hasRetries ? "true" : null,
+ model: this.selectedModel || null,
+ feature: this.selectedFeature || null,
+ username: this.selectedUsernames[0] || null,
+ unattributed: this.unattributed ? "true" : null,
+ id_type: this.idValue ? this.idType : null,
+ id_value: this.idValue || null,
+ };
+ }
+
+ updateUrl(extra = {}) {
+ this.router.transitionTo(this.router.currentRouteName, {
+ queryParams: { ...this.queryParams, ...extra },
+ });
+ }
+
+ @action
+ async refresh() {
+ const requestId = ++this._requestId;
+ this.loading = true;
+ this.loadingMore = false;
+ try {
+ const result = await ajax("/admin/plugins/discourse-ai/ai-logs.json", {
+ data: this.requestParams,
+ });
+ if (
+ requestId !== this._requestId ||
+ this.isDestroying ||
+ this.isDestroyed
+ ) {
+ return;
+ }
+
+ this.logs = result.logs;
+ this.meta = { ...this.meta, ...result.meta };
+ this.models = result.models || this.models;
+ this.features = this.mergedFeatures(
+ result.features || this.features,
+ result.logs
+ );
+ this.updateUrl();
+ } catch (error) {
+ if (
+ requestId === this._requestId &&
+ !this.isDestroying &&
+ !this.isDestroyed
+ ) {
+ popupAjaxError(error);
+ }
+ } finally {
+ if (
+ requestId === this._requestId &&
+ !this.isDestroying &&
+ !this.isDestroyed
+ ) {
+ this.loading = false;
+ }
+ }
+ }
+
+ @action
+ async loadMore() {
+ if (!this.meta.has_more || this.loadingMore) {
+ return;
+ }
+
+ const requestId = this._requestId;
+ const cursor = this.meta.next_cursor;
+ this.loadingMore = true;
+ try {
+ const result = await ajax("/admin/plugins/discourse-ai/ai-logs.json", {
+ data: { ...this.requestParams, cursor },
+ });
+ if (
+ requestId !== this._requestId ||
+ cursor !== this.meta.next_cursor ||
+ this.isDestroying ||
+ this.isDestroyed
+ ) {
+ return;
+ }
+
+ this.logs = [...this.logs, ...result.logs];
+ this.features = this.mergedFeatures(this.features, result.logs);
+ this.meta = { ...this.meta, ...result.meta };
+ } catch (error) {
+ if (
+ requestId === this._requestId &&
+ !this.isDestroying &&
+ !this.isDestroyed
+ ) {
+ popupAjaxError(error);
+ }
+ } finally {
+ if (
+ requestId === this._requestId &&
+ !this.isDestroying &&
+ !this.isDestroyed
+ ) {
+ this.loadingMore = false;
+ }
+ }
+ }
+
+ @action
+ registerFilterFormApi(api) {
+ this.filterFormApi = api;
+ }
+
+ @action
+ applyFilterForm(data) {
+ this.selectedPeriod = data.period || undefined;
+ this.startDate = data.date_range?.from || this.startDate;
+ this.endDate = data.date_range?.to || this.endDate;
+ this.selectedOutcome =
+ data.outcome === ALL_FILTER_VALUE ? undefined : data.outcome;
+ this.selectedModel =
+ data.model === ALL_FILTER_VALUE ? undefined : data.model;
+ this.selectedFeature = data.feature || undefined;
+ this.hasRetries = Boolean(data.has_retries);
+ this.unattributed = Boolean(data.unattributed);
+ this.selectedUsernames = this.unattributed ? [] : data.usernames || [];
+ this.idType = data.id_type || "id";
+ this.idValue = data.id_value || undefined;
+ this.refresh();
+ }
+
+ @action
+ selectPeriod(period) {
+ this.selectedPeriod = this.selectedPeriod === period ? undefined : period;
+ this.filterFormApi?.set("period", this.selectedPeriod);
+ if (this.selectedPeriod && this.selectedPeriod !== "custom") {
+ this.endDate = new Date();
+ this.startDate = moment()
+ .subtract(PERIODS[this.selectedPeriod], "hours")
+ .toDate();
+ this.filterFormApi?.set("date_range", {
+ from: this.startDate,
+ to: this.endDate,
+ });
+ }
+ this.refresh();
+ }
+
+ @action
+ changeDateRange(value) {
+ this.filterFormApi?.set("date_range", value);
+ this.startDate = value.from;
+ this.endDate = value.to;
+ }
+
+ @action
+ changeOutcome(value, { set }) {
+ set("outcome", value);
+ this.selectedOutcome =
+ value === ALL_FILTER_VALUE ? undefined : value || undefined;
+ this.refresh();
+ }
+
+ @action
+ changeModel(value, { set }) {
+ set("model", value);
+ this.selectedModel =
+ value === ALL_FILTER_VALUE ? undefined : value || undefined;
+ this.refresh();
+ }
+
+ @action
+ changeUser(usernames) {
+ const selectedUsernames = usernames || [];
+ this.filterFormApi?.set("usernames", selectedUsernames);
+ this.filterFormApi?.set("unattributed", false);
+ this.selectedUsernames = selectedUsernames;
+ this.unattributed = false;
+ this.refresh();
+ }
+
+ @action
+ toggleRetries(value, { set }) {
+ set("has_retries", value);
+ this.hasRetries = Boolean(value);
+ this.refresh();
+ }
+
+ @action
+ toggleUnattributed(value, { set }) {
+ set("unattributed", value);
+ this.unattributed = Boolean(value);
+ if (this.unattributed) {
+ set("usernames", []);
+ this.selectedUsernames = [];
+ }
+ this.refresh();
+ }
+
+ @action
+ setFeature(value, { set }) {
+ set("feature", value);
+ this.selectedFeature = value || undefined;
+ }
+
+ @action
+ setIdValue(value, { set }) {
+ set("id_value", value);
+ this.idValue = value || undefined;
+ }
+
+ @action
+ changeIdType(value, { set }) {
+ set("id_type", value);
+ this.idType = value;
+ if (this.idValue) {
+ this.refresh();
+ }
+ }
+
+ @action
+ clearFilters() {
+ const cleared = {
+ period: undefined,
+ date_range: {
+ from: moment().subtract(24, "hours").toDate(),
+ to: new Date(),
+ },
+ outcome: ALL_FILTER_VALUE,
+ model: ALL_FILTER_VALUE,
+ feature: undefined,
+ usernames: [],
+ has_retries: false,
+ unattributed: false,
+ id_type: "id",
+ id_value: undefined,
+ };
+ this.filterFormApi?.setProperties(cleared);
+ this.selectedPeriod = undefined;
+ this.startDate = cleared.date_range.from;
+ this.endDate = cleared.date_range.to;
+ this.selectedOutcome = undefined;
+ this.hasRetries = false;
+ this.selectedModel = undefined;
+ this.selectedFeature = undefined;
+ this.selectedUsernames = [];
+ this.unattributed = false;
+ this.idType = "id";
+ this.idValue = undefined;
+ this.refresh();
+ }
+
+ @action
+ openDetails(logId, { updateUrl = true } = {}) {
+ this._openLogId = String(logId);
+ if (updateUrl) {
+ this.updateUrl({ details: this._openLogId });
+ }
+ this.modal.show(AiLogDetailModal, {
+ model: {
+ logId,
+ onClose: () => {
+ this._openLogId = undefined;
+ this.updateUrl({ details: null });
+ },
+ },
+ });
+ }
+
+ @action
+ configureRetention() {
+ this.modal.show(AiLogRetentionModal, {
+ model: {
+ retention: this.meta.retention,
+ storage: this.meta.storage,
+ onSave: (retention) => {
+ this.meta = { ...this.meta, retention };
+ this.toasts.success({
+ data: { message: i18n("discourse_ai.logs.retention.saved") },
+ });
+ },
+ },
+ });
+ }
+
+ <template>
+ <section class="ai-logs admin-detail">
+ <DPageSubheader
+ @titleLabel={{i18n "discourse_ai.logs.short_title"}}
+ @descriptionLabel={{i18n "discourse_ai.logs.description"}}
+ >
+ <:actions as |actions|>
+ <actions.Primary
+ @action={{this.configureRetention}}
+ @icon="clock"
+ @label="discourse_ai.logs.retention.configure"
+ />
+ <actions.Default
+ @action={{this.refresh}}
+ @icon="arrows-rotate"
+ @label="discourse_ai.logs.refresh"
+ />
+ </:actions>
+ </DPageSubheader>
+
+ <aside class="ai-logs__retention">
+ <p class="ai-logs__retention-warning">{{i18n
+ "discourse_ai.logs.sensitive_warning"
+ }}</p>
+ <DButton
+ class="btn-transparent ai-logs__retention-action"
+ @action={{this.configureRetention}}
+ @translatedLabel={{this.lifecycleSummary}}
+ />
+ </aside>
+
+ <Form
+ class="ai-logs__filters"
+ @data={{this.filterFormData}}
+ @onRegisterApi={{this.registerFilterFormApi}}
+ @onSubmit={{this.applyFilterForm}}
+ as |form|
+ >
+ <form.Fieldset
+ class="ai-logs__period-field"
+ @name="period-filter"
+ @title={{i18n "discourse_ai.logs.filters.period"}}
+ >
+ <div class="ai-logs__periods">
+ {{#each this.periodOptions as |period|}}
+ <DButton
+ class={{if
+ (eq this.selectedPeriod period.id)
+ "btn-primary"
+ "btn-default"
+ }}
+ @action={{fn this.selectPeriod period.id}}
+ @ariaPressed={{eq this.selectedPeriod period.id}}
+ @translatedLabel={{period.name}}
+ />
+ {{/each}}
+ </div>
+ </form.Fieldset>
+
+ {{#if (eq this.selectedPeriod "custom")}}
+ <form.Fieldset
+ class="ai-logs__date-range-field"
+ @name="date-range-filter"
+ @title={{i18n "discourse_ai.logs.filters.date_range"}}
+ >
+ <div class="ai-logs__date-range">
+ <DDateTimeInputRange
+ @from={{this.startDate}}
+ @to={{this.endDate}}
+ @showFromTime={{false}}
+ @showToTime={{false}}
+ @onChange={{this.changeDateRange}}
+ />
+ <form.Submit
+ class="btn-default"
+ @label="discourse_ai.logs.apply"
+ />
+ </div>
+ </form.Fieldset>
+ {{/if}}
+
+ <div class="ai-logs__filter-grid">
+ <form.Field
+ class="ai-logs__outcome-filter"
+ @name="outcome"
+ @title={{i18n "discourse_ai.logs.outcome"}}
+ @type="select"
+ @onSet={{this.changeOutcome}}
+ as |field|
+ >
+ <field.Control @includeNone={{false}} as |select|>
+ <select.Option @value={{ALL_FILTER_VALUE}}>{{i18n
+ "discourse_ai.logs.all_outcomes"
+ }}</select.Option>
+ {{#each this.outcomeOptions as |outcome|}}
+ <select.Option @value={{outcome.id}}>
+ {{outcome.name}}
+ </select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ class="ai-logs__model-filter"
+ @name="model"
+ @title={{i18n "discourse_ai.logs.model"}}
+ @type="select"
+ @onSet={{this.changeModel}}
+ as |field|
+ >
+ <field.Control @includeNone={{false}} as |select|>
+ <select.Option @value={{ALL_FILTER_VALUE}}>{{i18n
+ "discourse_ai.logs.all_models"
+ }}</select.Option>
+ {{#each this.modelOptions as |model|}}
+ <select.Option @value={{model.id}}>
+ {{model.name}}
+ </select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ class="ai-logs__feature-filter"
+ @name="feature"
+ @title={{i18n "discourse_ai.logs.feature"}}
+ @type="input"
+ @onSet={{this.setFeature}}
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n "discourse_ai.logs.feature_placeholder"}}
+ list="ai-log-features"
+ />
+ </form.Field>
+ <datalist id="ai-log-features">
+ {{#each this.features as |feature|}}
+ <option value={{feature}}></option>
+ {{/each}}
+ </datalist>
+
+ <form.Fieldset
+ class="ai-logs__user-filter"
+ @name="user-filter"
+ @title={{i18n "discourse_ai.logs.user"}}
+ >
+ <UserChooser
+ @value={{this.selectedUsernames}}
+ @onChange={{this.changeUser}}
+ @options={{hash
+ maximum=1
+ none="discourse_ai.logs.user_placeholder"
+ filterPlaceholder="discourse_ai.logs.user_placeholder"
+ headerAriaLabel=(i18n "discourse_ai.logs.user_placeholder")
+ }}
+ />
+ </form.Fieldset>
+
+ <form.Field
+ class="ai-logs__toggle"
+ @name="has_retries"
+ @title={{i18n "discourse_ai.logs.has_retries"}}
+ @type="checkbox"
+ @onSet={{this.toggleRetries}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ class="ai-logs__toggle"
+ @name="unattributed"
+ @title={{i18n "discourse_ai.logs.unattributed"}}
+ @type="checkbox"
+ @onSet={{this.toggleUnattributed}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ </div>
+
+ <div class="ai-logs__id-filter">
+ <form.Field
+ @name="id_type"
+ @title={{i18n "discourse_ai.logs.filters.id_type"}}
+ @type="select"
+ @onSet={{this.changeIdType}}
+ as |field|
+ >
+ <field.Control @includeNone={{false}} as |select|>
+ {{#each this.idTypeOptions as |idType|}}
+ <select.Option @value={{idType.id}}>
+ {{idType.name}}
+ </select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @name="id_value"
+ @title={{i18n "discourse_ai.logs.filters.id_value"}}
+ @type="input-number"
+ @onSet={{this.setIdValue}}
+ as |field|
+ >
+ <field.Control
+ min="1"
+ max={{MAX_SAFE_ID}}
+ placeholder={{i18n "discourse_ai.logs.id_placeholder"}}
+ />
+ </form.Field>
+
+ <form.Submit
+ class="btn-default ai-logs__find"
+ @label="discourse_ai.logs.find"
+ />
+ {{#if this.hasFilters}}
+ <DButton
+ class="btn-transparent ai-logs__clear"
+ @action={{this.clearFilters}}
+ @label="discourse_ai.logs.clear_filters"
+ />
+ {{/if}}
+ </div>
+ </Form>
+
+ <DConditionalLoadingSpinner @condition={{this.loading}}>
+ {{#if this.logs.length}}
+ <DLoadMore
+ @action={{this.loadMore}}
+ @enabled={{this.meta.has_more}}
+ @isLoading={{this.loadingMore}}
+ >
+ <div class="ai-logs__table-wrapper">
+ <table class="d-table ai-logs__table">
+ <caption class="sr-only">{{i18n
+ "discourse_ai.logs.table_caption"
+ }}</caption>
+ <thead class="d-table__header">
+ <tr class="d-table__row">
+ <th class="ai-logs__col-outcome" scope="col"><span
+ class="sr-only"
+ >{{i18n "discourse_ai.logs.outcome"}}</span></th>
+ <th class="ai-logs__col-time" scope="col">{{i18n
+ "discourse_ai.logs.when"
+ }}</th>
+ <th class="ai-logs__col-request" scope="col">{{i18n
+ "discourse_ai.logs.request"
+ }}</th>
+ <th class="ai-logs__col-user" scope="col">{{i18n
+ "discourse_ai.logs.user"
+ }}</th>
+ <th class="ai-logs__col-duration" scope="col">{{i18n
+ "discourse_ai.logs.duration_tokens"
+ }}</th>
+ <th class="ai-logs__col-context" scope="col">{{i18n
+ "discourse_ai.logs.context"
+ }}</th>
+ <th class="ai-logs__col-actions" scope="col"><span
+ class="sr-only"
+ >{{i18n "discourse_ai.logs.actions"}}</span></th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.logs as |currentLog|}}
+ <AiLogRow
+ @log={{currentLog}}
+ @onOpen={{this.openDetails}}
+ />
+ {{/each}}
+ </tbody>
+ </table>
+ </div>
+ </DLoadMore>
+ {{else}}
+ <div class="ai-logs__empty">
+ <p>{{if
+ this.hasFilters
+ (i18n "discourse_ai.logs.no_results")
+ (i18n "discourse_ai.logs.no_logs")
+ }}</p>
+ {{#if this.hasFilters}}
+ <DButton
+ class="btn-default"
+ @action={{this.clearFilters}}
+ @label="discourse_ai.logs.clear_filters"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+ </DConditionalLoadingSpinner>
+ </section>
+ </template>
+}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/modal/ai-log-detail-modal.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/modal/ai-log-detail-modal.gjs
new file mode 100644
index 00000000000..baaae495b46
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/modal/ai-log-detail-modal.gjs
@@ -0,0 +1,315 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { next } from "@ember/runloop";
+import { ajax } from "discourse/lib/ajax";
+import getURL from "discourse/lib/get-url";
+import { eq, or } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+import AiPayloadViewer from "discourse/plugins/discourse-ai/discourse/components/ai-payload-viewer";
+
+export default class AiLogDetailModal extends Component {
+ @tracked log;
+ @tracked loading = true;
+ @tracked failed = false;
+ @tracked notFound = false;
+ @tracked activeTab = "request";
+
+ constructor() {
+ super(...arguments);
+ next(() => this.load());
+ }
+
+ @action
+ async load() {
+ this.loading = true;
+ this.failed = false;
+ this.notFound = false;
+
+ try {
+ const log = await ajax(
+ `/admin/plugins/discourse-ai/ai-logs/${this.args.model.logId}.json`
+ );
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.log = log;
+ }
+ } catch (error) {
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.failed = true;
+ this.notFound = error.jqXHR?.status === 404;
+ }
+ } finally {
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.loading = false;
+ }
+ }
+ }
+
+ get tabs() {
+ const tabs = [
+ { id: "request", label: i18n("discourse_ai.logs.detail.request") },
+ { id: "response", label: i18n("discourse_ai.logs.detail.response") },
+ ];
+
+ if (this.log?.feature_context) {
+ tabs.push({
+ id: "context",
+ label: i18n("discourse_ai.logs.detail.context"),
+ });
+ }
+ if (this.log?.request_attempts?.length) {
+ tabs.push({
+ id: "attempts",
+ label: i18n("discourse_ai.logs.detail.attempts"),
+ });
+ }
+ return tabs;
+ }
+
+ get activePayload() {
+ return this.activeTab === "request"
+ ? this.log?.raw_request_payload
+ : this.log?.raw_response_payload;
+ }
+
+ get activePayloadTruncated() {
+ return this.activeTab === "request"
+ ? this.log?.raw_request_payload_truncated
+ : this.log?.raw_response_payload_truncated;
+ }
+
+ get activeCopyLabel() {
+ return this.activeTab === "request"
+ ? i18n("discourse_ai.logs.detail.copy_request")
+ : i18n("discourse_ai.logs.detail.copy_response");
+ }
+
+ get contextPayload() {
+ return this.log?.feature_context
+ ? JSON.stringify(this.log.feature_context)
+ : null;
+ }
+
+ get formattedOutcome() {
+ const successful =
+ (this.log?.response_status >= 200 && this.log?.response_status <= 299) ||
+ (this.log?.response_status == null &&
+ Number(this.log?.response_tokens || 0) > 0);
+ const outcome = i18n(
+ `discourse_ai.logs.${successful ? "successful" : "failed"}`
+ );
+
+ return this.log?.response_status == null
+ ? outcome
+ : i18n("discourse_ai.logs.detail.outcome_with_status", {
+ outcome,
+ status: this.log.response_status,
+ });
+ }
+
+ get formattedCreatedAt() {
+ return this.log?.created_at
+ ? moment(this.log.created_at).format("LLL")
+ : "—";
+ }
+
+ get formattedDuration() {
+ return this.log?.duration_msecs == null
+ ? "—"
+ : i18n("discourse_ai.logs.detail.duration_seconds", {
+ seconds: this.seconds(this.log.duration_msecs),
+ });
+ }
+
+ get formattedFirstToken() {
+ return i18n("discourse_ai.logs.detail.duration_seconds", {
+ seconds: this.seconds(this.log.time_to_first_token_msecs),
+ });
+ }
+
+ get hasFirstToken() {
+ return this.log?.time_to_first_token_msecs != null;
+ }
+
+ seconds(milliseconds) {
+ return (milliseconds / 1000).toFixed(1);
+ }
+
+ get hasCost() {
+ return Number(this.log?.spending) > 0;
+ }
+
+ get formattedCost() {
+ return this.log?.spending == null
+ ? "—"
+ : `$${Number(this.log.spending).toFixed(4)}`;
+ }
+
+ get topicUrl() {
+ return this.log?.topic_id ? getURL(`/t/${this.log.topic_id}`) : null;
+ }
+
+ get postUrl() {
+ return this.log?.post_id ? getURL(`/p/${this.log.post_id}`) : null;
+ }
+
+ @action
+ attemptStatus(attempt) {
+ return attempt.status === 0
+ ? i18n("discourse_ai.logs.detail.network_error")
+ : attempt.status;
+ }
+
+ @action
+ selectTab(tab) {
+ this.activeTab = tab;
+ }
+
+ @action
+ close() {
+ this.args.model.onClose?.();
+ this.args.closeModal();
+ }
+
+ <template>
+ <DModal
+ class="ai-log-detail-modal"
+ @title={{i18n "discourse_ai.logs.detail.title" [email protected]}}
+ @closeModal={{this.close}}
+ >
+ <:body>
+ {{#if this.loading}}
+ <DConditionalLoadingSpinner @condition={{true}} />
+ {{else if this.failed}}
+ <div class="ai-log-detail-modal__error">
+ <p>{{if
+ this.notFound
+ (i18n "discourse_ai.logs.detail.load_error")
+ (i18n "discourse_ai.logs.detail.generic_load_error")
+ }}</p>
+ <DButton
+ class="btn-default"
+ @action={{this.load}}
+ @label="discourse_ai.logs.retry"
+ />
+ </div>
+ {{else}}
+ <dl class="ai-log-detail-modal__metadata">
+ <div><dt>{{i18n "discourse_ai.logs.time"}}</dt><dd
+ >{{this.formattedCreatedAt}}</dd></div>
+ <div><dt>{{i18n "discourse_ai.logs.outcome"}}</dt><dd
+ >{{this.formattedOutcome}}</dd></div>
+ <div><dt>{{i18n "discourse_ai.logs.feature"}}</dt><dd>{{or
+ this.log.feature_name
+ "—"
+ }}</dd></div>
+ <div><dt>{{i18n "discourse_ai.logs.model"}}</dt><dd>{{or
+ this.log.model_name
+ this.log.language_model
+ "—"
+ }}</dd></div>
+ <div><dt>{{i18n "discourse_ai.logs.provider"}}</dt><dd>{{or
+ this.log.provider_name
+ "—"
+ }}</dd></div>
+ <div class="ai-log-detail-modal__metadata-duration"><dt>{{i18n
+ "discourse_ai.logs.duration"
+ }}</dt><dd>{{this.formattedDuration}}</dd></div>
+ {{#if this.hasFirstToken}}
+ <div class="ai-log-detail-modal__metadata-first-token"><dt>{{i18n
+ "discourse_ai.logs.first_token"
+ }}</dt><dd>{{this.formattedFirstToken}}</dd></div>
+ {{/if}}
+ {{#if this.hasCost}}
+ <div class="ai-log-detail-modal__metadata-cost"><dt>{{i18n
+ "discourse_ai.logs.cost"
+ }}</dt><dd>{{this.formattedCost}}</dd></div>
+ {{/if}}
+ <div><dt>{{i18n "discourse_ai.logs.tokens"}}</dt><dd
+ >{{this.log.request_tokens}}
+ →
+ {{this.log.response_tokens}}</dd></div>
+ <div><dt>{{i18n "discourse_ai.logs.cache_read_tokens"}}</dt><dd>{{or
+ this.log.cache_read_tokens
+ 0
+ }}</dd></div>
+ <div><dt>{{i18n "discourse_ai.logs.cache_write_tokens"}}</dt><dd
+ >{{or this.log.cache_write_tokens 0}}</dd></div>
+ {{#if this.log.username}}
+ <div><dt>{{i18n "discourse_ai.logs.user"}}</dt><dd
+ >{{this.log.username}}</dd></div>
+ {{/if}}
+ {{#if this.topicUrl}}
+ <div><dt>{{i18n "discourse_ai.logs.topic"}}</dt><dd><a
+ href={{this.topicUrl}}
+ >{{this.log.topic_id}}</a></dd></div>
+ {{/if}}
+ {{#if this.postUrl}}
+ <div><dt>{{i18n "discourse_ai.logs.post"}}</dt><dd><a
+ href={{this.postUrl}}
+ >{{this.log.post_id}}</a></dd></div>
+ {{/if}}
+ </dl>
+
+ <nav
+ class="ai-log-detail-modal__tabs"
+ aria-label={{i18n "discourse_ai.logs.detail.tabs_label"}}
+ >
+ {{#each this.tabs as |tab|}}
+ <DButton
+ class={{if
+ (eq this.activeTab tab.id)
+ "btn-primary"
+ "btn-default"
+ }}
+ @action={{fn this.selectTab tab.id}}
+ @ariaPressed={{eq this.activeTab tab.id}}
+ @translatedLabel={{tab.label}}
+ />
+ {{/each}}
+ </nav>
+
+ {{#if
+ (or (eq this.activeTab "request") (eq this.activeTab "response"))
+ }}
+ <AiPayloadViewer
+ @payload={{this.activePayload}}
+ @truncated={{this.activePayloadTruncated}}
+ @copyLabel={{this.activeCopyLabel}}
+ @emptyMessage={{i18n
+ "discourse_ai.logs.detail.payload_unavailable"
+ }}
+ @truncatedMessage={{i18n
+ "discourse_ai.logs.detail.payload_truncated"
+ }}
+ />
+ {{else if (eq this.activeTab "context")}}
+ <AiPayloadViewer
+ @payload={{this.contextPayload}}
+ @copyLabel={{i18n "discourse_ai.logs.detail.copy_context"}}
+ @emptyMessage={{i18n
+ "discourse_ai.logs.detail.payload_unavailable"
+ }}
+ />
+ {{else}}
+ <ol class="ai-log-detail-modal__attempts">
+ {{#each this.log.request_attempts as |attempt|}}
+ <li>
+ {{i18n
+ "discourse_ai.logs.detail.attempt"
+ status=(this.attemptStatus attempt)
+ delay=attempt.delay_ms
+ }}
+ </li>
+ {{/each}}
+ </ol>
+ {{/if}}
+ {{/if}}
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/modal/ai-log-retention-modal.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/modal/ai-log-retention-modal.gjs
new file mode 100644
index 00000000000..c7e00d2a11c
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/modal/ai-log-retention-modal.gjs
@@ -0,0 +1,227 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+const MAX_RETENTION_DAYS = 36500;
+
+export default class AiLogRetentionModal extends Component {
+ @cached
+ get formData() {
+ return {
+ detailed_days: this.args.model.retention.detailed_days,
+ summary_days: this.args.model.retention.summary_days,
+ };
+ }
+
+ get formattedStorage() {
+ const bytes = Number(this.args.model.storage?.total_bytes || 0);
+ if (bytes < 1024) {
+ return `${bytes} B`;
+ }
+
+ const units = ["KB", "MB", "GB", "TB"];
+ let value = bytes / 1024;
+ let unit = units[0];
+ for (let index = 1; value >= 1024 && index < units.length; index++) {
+ value /= 1024;
+ unit = units[index];
+ }
+ return `${value.toFixed(1)} ${unit}`;
+ }
+
+ lifecycle(data) {
+ const detailed = Number(data.detailed_days || 0);
+ const summary = Number(data.summary_days || 0);
+
+ if (detailed === 0 && summary === 0) {
+ return i18n("discourse_ai.logs.retention.lifecycle.complete_forever");
+ }
+ if (detailed === 0) {
+ return i18n("discourse_ai.logs.retention.lifecycle.detail_until_delete", {
+ summary,
+ });
+ }
+ if (summary === 0) {
+ return i18n("discourse_ai.logs.retention.lifecycle.summary_forever", {
+ detailed,
+ });
+ }
+ return i18n("discourse_ai.logs.retention.lifecycle.finite", {
+ detailed,
+ summary,
+ });
+ }
+
+ @action
+ retentionPreview(data) {
+ return this.lifecycle(data);
+ }
+
+ @action
+ isShortening(data) {
+ const cutoff = (retention) => {
+ const summary = Number(retention.summary_days);
+ const detailed = Number(retention.detailed_days);
+ const summaryCutoff = summary > 0 ? summary : Infinity;
+
+ return {
+ summary: summaryCutoff,
+ detailed: detailed > 0 ? detailed : summaryCutoff,
+ };
+ };
+ const current = cutoff(this.args.model.retention);
+ const proposed = cutoff(data);
+
+ return (
+ proposed.detailed < current.detailed || proposed.summary < current.summary
+ );
+ }
+
+ @action
+ validate(data, { addError, removeError }) {
+ const detailed = Number(data.detailed_days);
+ const summary = Number(data.summary_days);
+
+ if (
+ Number.isFinite(detailed) &&
+ (!Number.isInteger(detailed) ||
+ detailed < 0 ||
+ detailed > MAX_RETENTION_DAYS)
+ ) {
+ addError("detailed_days", {
+ title: i18n("discourse_ai.logs.retention.detailed_title"),
+ message: i18n("discourse_ai.logs.retention.valid_range", {
+ max: MAX_RETENTION_DAYS,
+ }),
+ });
+ } else {
+ removeError("detailed_days");
+ }
+
+ if (
+ Number.isFinite(summary) &&
+ (!Number.isInteger(summary) ||
+ summary < 0 ||
+ summary > MAX_RETENTION_DAYS)
+ ) {
+ addError("summary_days", {
+ title: i18n("discourse_ai.logs.retention.summary_title"),
+ message: i18n("discourse_ai.logs.retention.valid_range", {
+ max: MAX_RETENTION_DAYS,
+ }),
+ });
+ } else if (detailed > 0 && summary > 0 && summary < detailed) {
+ addError("summary_days", {
+ title: i18n("discourse_ai.logs.retention.summary_title"),
+ message: i18n("discourse_ai.logs.retention.invalid_order"),
+ });
+ } else {
+ removeError("summary_days");
+ }
+ }
+
+ @action
+ async save(data) {
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-ai/ai-logs/retention.json",
+ {
+ type: "PUT",
+ data: {
+ detailed_days: Number(data.detailed_days),
+ summary_days: Number(data.summary_days),
+ },
+ }
+ );
+ this.args.model.onSave(result.retention);
+ this.args.closeModal();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DModal
+ class="ai-log-retention-modal"
+ @title={{i18n "discourse_ai.logs.retention.title"}}
+ @closeModal={{@closeModal}}
+ >
+ <:body>
+ <div
+ class="ai-log-retention-modal__lifecycle"
+ role="img"
+ aria-label={{i18n "discourse_ai.logs.retention.lifecycle_label"}}
+ >
+ <span>{{i18n "discourse_ai.logs.retention.detailed_stage"}}</span>
+ <span
+ class="ai-log-retention-modal__lifecycle-arrow"
+ aria-hidden="true"
+ >→</span>
+ <span>{{i18n "discourse_ai.logs.retention.summary_stage"}}</span>
+ <span
+ class="ai-log-retention-modal__lifecycle-arrow"
+ aria-hidden="true"
+ >→</span>
+ <span>{{i18n "discourse_ai.logs.retention.deleted_stage"}}</span>
+ </div>
+ <p class="ai-log-retention-modal__hint">
+ {{i18n "discourse_ai.logs.retention.hint"}}
+ </p>
+
+ <Form
+ @data={{this.formData}}
+ @validate={{this.validate}}
+ @onSubmit={{this.save}}
+ as |form data|
+ >
+ <form.Field
+ @name="detailed_days"
+ @title={{i18n "discourse_ai.logs.retention.detailed_title"}}
+ @description={{i18n "discourse_ai.logs.retention.detailed_help"}}
+ @validation="required|number"
+ @format="large"
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" max={{MAX_RETENTION_DAYS}} step="1" />
+ </form.Field>
+
+ <form.Field
+ @name="summary_days"
+ @title={{i18n "discourse_ai.logs.retention.summary_title"}}
+ @description={{i18n "discourse_ai.logs.retention.summary_help"}}
+ @validation="required|number"
+ @format="large"
+ @type="input-number"
+ as |field|
+ >
+ <field.Control min="0" max={{MAX_RETENTION_DAYS}} step="1" />
+ </form.Field>
+
+ <p class="ai-log-retention-modal__preview">
+ {{this.retentionPreview data}}
+ </p>
+ {{#if (this.isShortening data)}}
+ <div class="alert alert-warning">
+ {{i18n "discourse_ai.logs.retention.destructive_warning"}}
+ </div>
+ {{/if}}
+
+ <form.Submit
+ class="btn-primary"
+ @label="discourse_ai.logs.retention.save"
+ />
+ </Form>
+
+ <p class="ai-log-retention-modal__meta">
+ {{i18n "discourse_ai.logs.retention.meta" size=this.formattedStorage}}
+ </p>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-logs.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-logs.js
new file mode 100644
index 00000000000..4f3f4982fea
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-logs.js
@@ -0,0 +1,31 @@
+import Controller from "@ember/controller";
+
+export default class DiscourseAiLogsController extends Controller {
+ queryParams = [
+ "period",
+ "start_date",
+ "end_date",
+ "outcome",
+ "has_retries",
+ { selectedModel: "model" },
+ "feature",
+ "username",
+ "unattributed",
+ "id_type",
+ "id_value",
+ "details",
+ ];
+
+ period = null;
+ start_date = null;
+ end_date = null;
+ outcome = null;
+ has_retries = null;
+ selectedModel = null;
+ feature = null;
+ username = null;
+ unattributed = null;
+ id_type = null;
+ id_value = null;
+ details = null;
+}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-logs.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-logs.js
new file mode 100644
index 00000000000..d70fffb6116
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-logs.js
@@ -0,0 +1,86 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseAiLogsRoute extends DiscourseRoute {
+ @service currentUser;
+
+ queryParams = {
+ period: { replace: true },
+ start_date: { replace: true },
+ end_date: { replace: true },
+ outcome: { replace: true },
+ has_retries: { replace: true },
+ selectedModel: { replace: true },
+ feature: { replace: true },
+ username: { replace: true },
+ unattributed: { replace: true },
+ id_type: { replace: true },
+ id_value: { replace: true },
+ details: { replace: false },
+ };
+
+ async model(params) {
+ const period = ["hour", "day", "week", "custom"].includes(params.period)
+ ? params.period
+ : null;
+ const idType = ["id", "topic_id", "post_id"].includes(params.id_type)
+ ? params.id_type
+ : "id";
+ const outcome = ["successful", "failed"].includes(params.outcome)
+ ? params.outcome
+ : null;
+ const hasRetries = String(params.has_retries) === "true" ? "true" : null;
+ const unattributed = String(params.unattributed) === "true" ? "true" : null;
+ const selectedModel = /^[1-9]\d*$/.test(params.selectedModel || "")
+ ? params.selectedModel
+ : null;
+ const idValue = /^[1-9]\d*$/.test(params.id_value || "")
+ ? params.id_value
+ : null;
+ const filterQueryParams = {
+ ...params,
+ period,
+ outcome,
+ has_retries: hasRetries,
+ unattributed,
+ id_type: idType,
+ id_value: idValue,
+ model: selectedModel,
+ };
+ delete filterQueryParams.selectedModel;
+
+ const requestParams = { ...filterQueryParams };
+ delete requestParams.details;
+ delete requestParams.period;
+ delete requestParams.id_type;
+ delete requestParams.id_value;
+ requestParams.llm_id = requestParams.model;
+ delete requestParams.model;
+ requestParams.include_meta = true;
+
+ if (period === "custom") {
+ requestParams.timezone =
+ this.currentUser?.user_option?.timezone || moment.tz.guess();
+ } else if (period) {
+ const hours = { hour: 1, day: 24, week: 24 * 7 }[period];
+ if (hours) {
+ requestParams.start_date = moment()
+ .subtract(hours, "hours")
+ .toISOString();
+ requestParams.end_date = moment().toISOString();
+ }
+ }
+
+ if (idValue) {
+ requestParams[idType] = idValue;
+ }
+
+ return {
+ data: await ajax("/admin/plugins/discourse-ai/ai-logs.json", {
+ data: requestParams,
+ }),
+ queryParams: filterQueryParams,
+ };
+ }
+}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-logs.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-logs.gjs
new file mode 100644
index 00000000000..587a4528862
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-logs.gjs
@@ -0,0 +1,8 @@
+import AiLogs from "../../../components/ai-logs";
+
+export default <template>
+ <AiLogs
+ @model={{@controller.model.data}}
+ @queryParams={{@controller.model.queryParams}}
+ />
+</template>
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_logs_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_logs_controller.rb
new file mode 100644
index 00000000000..925457ea3a8
--- /dev/null
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_logs_controller.rb
@@ -0,0 +1,312 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Admin
+ class AiLogsController < ::Admin::AdminController
+ requires_plugin "discourse-ai"
+
+ LIST_LIMIT = 50
+ MAX_DATE_RANGE = 366.days
+ MAX_RETENTION_DAYS = 36_500
+ MAX_PAYLOAD_BYTES = 1.megabyte
+ MIN_PAYLOAD_CHARACTERS = MAX_PAYLOAD_BYTES / 4
+ DETAIL_COLUMNS = %i[
+ id
+ provider_id
+ user_id
+ request_tokens
+ response_tokens
+ created_at
+ topic_id
+ post_id
+ feature_name
+ language_model
+ feature_context
+ duration_msecs
+ time_to_first_token_msecs
+ cache_write_tokens
+ cache_read_tokens
+ llm_id
+ response_status
+ request_attempts
+ estimated_cost
+ ].freeze
+ LIST_COLUMNS = %i[
+ id
+ created_at
+ provider_id
+ feature_name
+ language_model
+ llm_id
+ user_id
+ topic_id
+ post_id
+ request_tokens
+ response_tokens
+ response_status
+ duration_msecs
+ ].freeze
+ BOOLEAN_VALUES = %w[true false].freeze
+
+ def index
+ limit = page_limit
+ logs = filtered_logs
+ if params[:cursor] && params[:id].blank?
+ logs = logs.where("ai_api_audit_logs.id < ?", positive_integer!(:cursor))
+ end
+ logs =
+ logs
+ .select(
+ *LIST_COLUMNS,
+ Arel.sql("request_attempts IS NOT NULL AS has_retries"),
+ Arel.sql(
+ "CASE WHEN #{AiApiAuditLog::SUCCESS_CONDITION} THEN 'successful' ELSE 'failed' END AS outcome",
+ ),
+ )
+ .order(id: :desc)
+ .limit(limit + 1)
+ .preload(:user, :llm_model)
+ .to_a
+
+ has_more = logs.length > limit
+ logs = logs.first(limit)
+
+ response = {
+ logs:
+ ActiveModel::ArraySerializer.new(
+ logs,
+ each_serializer: DiscourseAi::Admin::AiLogListSerializer,
+ root: false,
+ ).as_json,
+ meta: {
+ next_cursor: has_more ? logs.last&.id : nil,
+ has_more:,
+ },
+ }
+
+ if boolean_param(:include_meta)
+ response[:meta].merge!(retention_metadata)
+ response[:models] = LlmModel
+ .order(:display_name)
+ .pluck(:id, :display_name)
+ .map { |id, name| { id:, name: } }
+ response[:features] = DiscourseAi::Configuration::Feature
+ .all
+ .map(&:name)
+ .compact
+ .uniq
+ .sort
+ end
+
+ render json: response
+ end
+
+ def show
+ log =
+ AiApiAuditLog
+ .select(
+ *DETAIL_COLUMNS,
+ Arel.sql(payload_projection_sql(:raw_request_payload)),
+ Arel.sql(payload_projection_sql(:raw_response_payload)),
+ Arel.sql("OCTET_LENGTH(raw_request_payload) AS raw_request_payload_bytes"),
+ Arel.sql("OCTET_LENGTH(raw_response_payload) AS raw_response_payload_bytes"),
+ )
+ .preload(:user, :llm_model)
+ .find(positive_integer!(:id))
+ render json: DiscourseAi::Admin::AiLogDetailSerializer.new(log, root: false)
+ end
+
+ def update_retention
+ detailed_days = non_negative_integer!(:detailed_days)
+ summary_days = non_negative_integer!(:summary_days)
+
+ if detailed_days.positive? && summary_days.positive? && summary_days < detailed_days
+ raise Discourse::InvalidParameters.new(:summary_days)
+ end
+
+ SiteSetting::Update.call(
+ guardian:,
+ params: {
+ settings: [
+ { setting_name: :ai_audit_logs_detailed_retention_days, value: detailed_days },
+ { setting_name: :ai_audit_logs_purge_after_days, value: summary_days },
+ ],
+ },
+ ) do
+ on_success do
+ render json: {
+ retention: {
+ detailed_days: SiteSetting.ai_audit_logs_detailed_retention_days,
+ summary_days: SiteSetting.ai_audit_logs_purge_after_days,
+ },
+ }
+ end
+ on_failed_policy(:settings_are_unshadowed_globally) do |policy|
+ raise Discourse::InvalidParameters, policy.reason
+ end
+ on_failed_policy(:settings_are_visible) do |policy|
+ raise Discourse::InvalidParameters, policy.reason
+ end
+ on_failed_policy(:settings_are_configurable) do |policy|
+ raise Discourse::InvalidParameters, policy.reason
+ end
+ on_failed_policy(:settings_are_not_deprecated) do |policy|
+ raise Discourse::InvalidParameters, policy.reason
+ end
+ on_failed_contract do |contract|
+ raise Discourse::InvalidParameters, contract.errors.full_messages.join(", ")
+ end
+ on_failure { raise Discourse::InvalidParameters, :retention }
+ end
+ end
+
+ private
+
+ def payload_projection_sql(column)
+ <<~SQL.squish
+ LEFT(
+ #{column},
+ GREATEST(
+ #{MIN_PAYLOAD_CHARACTERS},
+ #{MAX_PAYLOAD_BYTES} - (OCTET_LENGTH(#{column}) - CHAR_LENGTH(#{column}))
+ )
+ ) AS #{column}
+ SQL
+ end
+
+ def filtered_logs
+ validate_filter_params!
+ scope = AiApiAuditLog.all
+
+ id_filters = %i[id topic_id post_id].select { |name| params[name].present? }
+ raise Discourse::InvalidParameters.new(:id) if id_filters.length > 1
+
+ if id_filters.one?
+ name = id_filters.first
+ return scope.where(name => positive_integer!(name))
+ end
+
+ scope = apply_date_filters(scope)
+ scope = apply_outcome_filter(scope)
+ scope = scope.where.not(request_attempts: nil) if boolean_param(:has_retries)
+ scope = scope.where(llm_id: positive_integer!(:llm_id)) if params[:llm_id].present?
+ scope = scope.where(feature_name: params[:feature].to_s) if params[:feature].present?
+
+ if params[:user_id].present? || params[:username].present?
+ raise Discourse::InvalidParameters.new(:unattributed) if boolean_param(:unattributed)
+ user_id =
+ if params[:user_id].present?
+ positive_integer!(:user_id)
+ else
+ User.find_by_username(params[:username].to_s)&.id || -1
+ end
+ scope = scope.where(user_id:)
+ elsif boolean_param(:unattributed)
+ scope = scope.where(user_id: nil)
+ end
+
+ scope
+ end
+
+ def apply_date_filters(scope)
+ return scope if params[:start_date].blank? && params[:end_date].blank?
+
+ timezone =
+ if params[:timezone].present?
+ ActiveSupport::TimeZone[params[:timezone].to_s] ||
+ (raise Discourse::InvalidParameters.new(:timezone))
+ else
+ Time.zone
+ end
+
+ start_time = parse_time!(:start_date, timezone, :beginning) if params[:start_date].present?
+ end_time = parse_time!(:end_date, timezone, :end) if params[:end_date].present?
+
+ if start_time && end_time &&
+ (end_time < start_time || end_time - start_time > MAX_DATE_RANGE)
+ raise Discourse::InvalidParameters.new(:date_range)
+ end
+
+ scope = scope.where("ai_api_audit_logs.created_at >= ?", start_time) if start_time
+ scope = scope.where("ai_api_audit_logs.created_at <= ?", end_time) if end_time
+ scope
+ end
+
+ def parse_time!(name, timezone, boundary)
+ value = params[name].to_s
+ parsed = timezone.parse(value)
+ raise Discourse::InvalidParameters.new(name) if !parsed
+
+ if value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
+ boundary == :end ? parsed.end_of_day : parsed.beginning_of_day
+ else
+ Time.iso8601(value)
+ end
+ rescue ArgumentError
+ raise Discourse::InvalidParameters.new(name)
+ end
+
+ def apply_outcome_filter(scope)
+ case params[:outcome]
+ when nil, ""
+ scope
+ when "successful"
+ scope.successful_requests
+ when "failed"
+ scope.failed_requests
+ else
+ raise Discourse::InvalidParameters.new(:outcome)
+ end
+ end
+
+ def validate_filter_params!
+ %i[has_retries unattributed include_meta].each do |name|
+ next if params[name].blank? || BOOLEAN_VALUES.include?(params[name].to_s)
+
+ raise Discourse::InvalidParameters.new(name)
+ end
+ end
+
+ def boolean_param(name)
+ params[name].to_s == "true"
+ end
+
+ def page_limit
+ return LIST_LIMIT if params[:limit].blank?
+
+ [positive_integer!(:limit), LIST_LIMIT].min
+ end
+
+ def positive_integer!(name)
+ value = Integer(params[name], exception: false)
+ raise Discourse::InvalidParameters.new(name) if !value || value <= 0
+
+ value
+ end
+
+ def non_negative_integer!(name)
+ value = Integer(params[name], exception: false)
+ if !value || value.negative? || value > MAX_RETENTION_DAYS
+ raise Discourse::InvalidParameters.new(name)
+ end
+
+ value
+ end
+
+ def retention_metadata
+ total_bytes =
+ DB.query_single("SELECT pg_total_relation_size('ai_api_audit_logs')").first.to_i
+
+ {
+ retention: {
+ detailed_days: SiteSetting.ai_audit_logs_detailed_retention_days,
+ summary_days: SiteSetting.ai_audit_logs_purge_after_days,
+ },
+ storage: {
+ total_bytes:,
+ },
+ }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb b/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb
index 95a7769293d..b465a3a8de4 100644
--- a/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb
+++ b/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb
@@ -4,14 +4,28 @@ module Jobs
class PurgeAiApiAuditLogs < ::Jobs::Scheduled
every 1.day
+ BATCH_SIZE = 1_000
+
def execute(_args)
- return unless SiteSetting.discourse_ai_enabled
+ summary_retention_days = SiteSetting.ai_audit_logs_purge_after_days.to_i
+ detailed_retention_days = SiteSetting.ai_audit_logs_detailed_retention_days.to_i
+
+ return if summary_retention_days <= 0 && detailed_retention_days <= 0
+
+ if summary_retention_days.positive?
+ AiApiAuditLog
+ .where("created_at < ?", summary_retention_days.days.ago)
+ .in_batches(of: BATCH_SIZE)
+ .delete_all
+ end
- retention_days = SiteSetting.ai_audit_logs_purge_after_days.to_i
- return if retention_days <= 0
+ return if detailed_retention_days <= 0
- cutoff = retention_days.days.ago
- AiApiAuditLog.where("created_at < ?", cutoff).delete_all
+ AiApiAuditLog
+ .where("created_at < ?", detailed_retention_days.days.ago)
+ .where("raw_request_payload IS NOT NULL OR raw_response_payload IS NOT NULL")
+ .in_batches(of: BATCH_SIZE)
+ .update_all(raw_request_payload: nil, raw_response_payload: nil)
end
end
end
diff --git a/plugins/discourse-ai/app/models/ai_api_audit_log.rb b/plugins/discourse-ai/app/models/ai_api_audit_log.rb
index 6f293cce9b9..b1278d40fcd 100644
--- a/plugins/discourse-ai/app/models/ai_api_audit_log.rb
+++ b/plugins/discourse-ai/app/models/ai_api_audit_log.rb
@@ -9,6 +9,17 @@ class AiApiAuditLog < ActiveRecord::Base
belongs_to :user
belongs_to :llm_model, foreign_key: :llm_id, optional: true
+ # Keep this predicate compatible with idx_ai_api_audit_logs_failed_id.
+ FAILURE_CONDITION =
+ "(response_status IS NOT NULL AND response_status NOT BETWEEN 200 AND 299) OR " \
+ "(response_status IS NULL AND COALESCE(response_tokens, 0) <= 0)"
+ SUCCESS_CONDITION =
+ "(response_status BETWEEN 200 AND 299) OR " \
+ "(response_status IS NULL AND COALESCE(response_tokens, 0) > 0)"
+
+ scope :failed_requests, -> { where(FAILURE_CONDITION) }
+ scope :successful_requests, -> { where(SUCCESS_CONDITION) }
+
module Provider
OpenAI = 1
Anthropic = 2
@@ -50,11 +61,11 @@ class AiApiAuditLog < ActiveRecord::Base
end
def next_log_id
- self.class.where("id > ?", id).where(topic_id: topic_id).order(id: :asc).pluck(:id).first
+ self.class.where("id > ?", id).where(topic_id: topic_id).order(id: :asc).pick(:id)
end
def prev_log_id
- self.class.where("id < ?", id).where(topic_id: topic_id).order(id: :desc).pluck(:id).first
+ self.class.where("id < ?", id).where(topic_id: topic_id).order(id: :desc).pick(:id)
end
end
@@ -87,6 +98,11 @@ end
#
# Indexes
#
+# idx_ai_api_audit_logs_failed_id (id) WHERE (((response_status IS NOT NULL) AND ((response_status < 200) OR (response_status > 299))) OR ((response_status IS NULL) AND (COALESCE(response_tokens, 0) <= 0)))
+# idx_ai_api_audit_logs_feature_name_id (feature_name,id) WHERE (feature_name IS NOT NULL)
+# idx_ai_api_audit_logs_payload_id (id) WHERE ((raw_request_payload IS NOT NULL) OR (raw_response_payload IS NOT NULL))
+# idx_ai_api_audit_logs_retried_id (id) WHERE (request_attempts IS NOT NULL)
+# idx_ai_api_audit_logs_user_id_id (user_id,id)
# index_ai_api_audit_logs_on_created_at_and_feature_name (created_at,feature_name)
# index_ai_api_audit_logs_on_created_at_and_language_model (created_at,language_model)
# index_ai_api_audit_logs_on_created_at_and_user_id (created_at,user_id)
diff --git a/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_detail_serializer.rb b/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_detail_serializer.rb
new file mode 100644
index 00000000000..1fbd4189f99
--- /dev/null
+++ b/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_detail_serializer.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Admin
+ class AiLogDetailSerializer < ApplicationSerializer
+ attributes :id,
+ :created_at,
+ :provider_id,
+ :provider_name,
+ :feature_name,
+ :feature_context,
+ :language_model,
+ :llm_id,
+ :model_name,
+ :user_id,
+ :username,
+ :avatar_template,
+ :topic_id,
+ :post_id,
+ :request_tokens,
+ :response_tokens,
+ :cache_read_tokens,
+ :cache_write_tokens,
+ :response_status,
+ :duration_msecs,
+ :time_to_first_token_msecs,
+ :spending,
+ :request_attempts,
+ :raw_request_payload,
+ :raw_response_payload,
+ :raw_request_payload_bytes,
+ :raw_response_payload_bytes,
+ :raw_request_payload_truncated,
+ :raw_response_payload_truncated,
+ :payload_available
+
+ def provider_name
+ AiLogSerializerHelpers.provider_name(object.provider_id)
+ end
+
+ def model_name
+ object.llm_model&.display_name || object.language_model
+ end
+
+ def username
+ object.user&.username
+ end
+
+ def avatar_template
+ object.user&.avatar_template
+ end
+
+ def spending
+ return object.estimated_cost.to_d.round(6).to_f if !object.estimated_cost.nil?
+
+ object.llm_model&.spending_for(object)
+ end
+
+ def raw_request_payload_bytes
+ object[:raw_request_payload_bytes]&.to_i
+ end
+
+ def raw_response_payload_bytes
+ object[:raw_response_payload_bytes]&.to_i
+ end
+
+ def raw_request_payload_truncated
+ raw_request_payload_bytes.to_i > object.raw_request_payload&.bytesize.to_i
+ end
+
+ def raw_response_payload_truncated
+ raw_response_payload_bytes.to_i > object.raw_response_payload&.bytesize.to_i
+ end
+
+ def payload_available
+ !raw_request_payload_bytes.nil? || !raw_response_payload_bytes.nil?
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_list_serializer.rb b/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_list_serializer.rb
new file mode 100644
index 00000000000..f84b509a203
--- /dev/null
+++ b/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_list_serializer.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Admin
+ class AiLogListSerializer < ApplicationSerializer
+ attributes :id,
+ :created_at,
+ :provider_id,
+ :provider_name,
+ :feature_name,
+ :language_model,
+ :llm_id,
+ :model_name,
+ :user_id,
+ :username,
+ :avatar_template,
+ :topic_id,
+ :post_id,
+ :request_tokens,
+ :response_tokens,
+ :response_status,
+ :duration_msecs,
+ :has_retries,
+ :outcome
+
+ def provider_name
+ AiLogSerializerHelpers.provider_name(object.provider_id)
+ end
+
+ def model_name
+ object.llm_model&.display_name || object.language_model
+ end
+
+ def username
+ object.user&.username
+ end
+
+ def avatar_template
+ object.user&.avatar_template
+ end
+
+ def has_retries
+ ActiveModel::Type::Boolean.new.cast(object[:has_retries])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_serializer_helpers.rb b/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_serializer_helpers.rb
new file mode 100644
index 00000000000..1301ecf45da
--- /dev/null
+++ b/plugins/discourse-ai/app/serializers/discourse_ai/admin/ai_log_serializer_helpers.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Admin
+ module AiLogSerializerHelpers
+ PROVIDER_NAMES = {
+ AiApiAuditLog::Provider::OpenAI => "OpenAI",
+ AiApiAuditLog::Provider::Anthropic => "Anthropic",
+ AiApiAuditLog::Provider::HuggingFaceTextGeneration => "Hugging Face",
+ AiApiAuditLog::Provider::Gemini => "Gemini",
+ AiApiAuditLog::Provider::Vllm => "vLLM",
+ AiApiAuditLog::Provider::Cohere => "Cohere",
+ AiApiAuditLog::Provider::Ollama => "Ollama",
+ AiApiAuditLog::Provider::SambaNova => "SambaNova",
+ AiApiAuditLog::Provider::Mistral => "Mistral",
+ AiApiAuditLog::Provider::OpenRouter => "OpenRouter",
+ AiApiAuditLog::Provider::BedrockConverse => "Amazon Bedrock",
+ }.freeze
+
+ def self.provider_name(provider_id)
+ PROVIDER_NAMES[provider_id]
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb b/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb
index 943bbea7854..31904678d2d 100644
--- a/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb
+++ b/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb
@@ -53,14 +53,7 @@ class ProblemCheck::AiLlmStatus < ProblemCheck
counts = DB.query_single(<<~SQL, llm_id: model.id, since: LOOKBACK_WINDOW.ago)
SELECT
COUNT(*) AS total_calls,
- SUM(
- CASE
- WHEN response_status IS NOT NULL THEN
- CASE WHEN response_status NOT BETWEEN 200 AND 299 THEN 1 ELSE 0 END
- ELSE
- CASE WHEN COALESCE(response_tokens, 0) <= 0 THEN 1 ELSE 0 END
- END
- ) AS failed_calls
+ COUNT(*) FILTER (WHERE #{AiApiAuditLog::FAILURE_CONDITION}) AS failed_calls
FROM ai_api_audit_logs
WHERE llm_id = :llm_id
AND created_at >= :since
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js b/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js
index a9dc5d31b77..ef836b425c7 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js
@@ -29,6 +29,7 @@ export default {
this.route("discourse-ai-spam", { path: "ai-spam" });
this.route("discourse-ai-translations", { path: "ai-translations" });
this.route("discourse-ai-usage", { path: "ai-usage" });
+ this.route("discourse-ai-logs", { path: "ai-logs" });
this.route(
"discourse-ai-embeddings",
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-log-row.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-log-row.gjs
new file mode 100644
index 00000000000..b9c64861122
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-log-row.gjs
@@ -0,0 +1,208 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import getURL from "discourse/lib/get-url";
+import DButton from "discourse/ui-kit/d-button";
+import DUserLink from "discourse/ui-kit/d-user-link";
+import dAgeWithTooltip from "discourse/ui-kit/helpers/d-age-with-tooltip";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import I18n, { i18n } from "discourse-i18n";
+
+function compactTokenCount(value) {
+ if (value < 1_000) {
+ return I18n.toNumber(value, { precision: 0 });
+ }
+
+ const millions = value >= 999_500;
+ const scaled = value / (millions ? 1_000_000 : 1_000);
+ const roundedToOneDecimal = Math.round(scaled * 10) / 10;
+ const precision =
+ scaled < 10 && !Number.isInteger(roundedToOneDecimal) ? 1 : 0;
+ const number = I18n.toNumber(scaled, { precision });
+
+ return i18n(`number.short.${millions ? "millions" : "thousands"}`, {
+ number,
+ });
+}
+
+export default class AiLogRow extends Component {
+ get status() {
+ const log = this.args.log;
+ if (["successful", "failed"].includes(log.outcome)) {
+ return log.outcome;
+ }
+
+ return (log.response_status >= 200 && log.response_status <= 299) ||
+ (log.response_status == null && Number(log.response_tokens || 0) > 0)
+ ? "successful"
+ : "failed";
+ }
+
+ get statusLabel() {
+ return i18n(`discourse_ai.logs.${this.status}`);
+ }
+
+ get statusClass() {
+ return this.status === "successful" ? "--success" : "--failed";
+ }
+
+ get featureName() {
+ return this.args.log.feature_name || "—";
+ }
+
+ get modelName() {
+ return this.args.log.model_name || this.args.log.language_model || "—";
+ }
+
+ get tokenValues() {
+ const { request_tokens: request, response_tokens: response } =
+ this.args.log;
+
+ return {
+ request:
+ request == null ? null : I18n.toNumber(request, { precision: 0 }),
+ response:
+ response == null ? null : I18n.toNumber(response, { precision: 0 }),
+ };
+ }
+
+ get compactTokenValues() {
+ const { request_tokens: request, response_tokens: response } =
+ this.args.log;
+
+ return {
+ request: request == null ? "—" : compactTokenCount(request),
+ response: response == null ? "—" : compactTokenCount(response),
+ };
+ }
+
+ get tokensLabel() {
+ const { request, response } = this.compactTokenValues;
+ return request === "—" && response === "—"
+ ? "—"
+ : i18n("discourse_ai.logs.tokens_pair", { request, response });
+ }
+
+ get tokensAriaLabel() {
+ const { request, response } = this.tokenValues;
+ if (request == null && response == null) {
+ return i18n("discourse_ai.logs.tokens_unavailable");
+ }
+
+ return i18n("discourse_ai.logs.tokens_aria", {
+ request: request ?? i18n("discourse_ai.logs.unknown"),
+ response: response ?? i18n("discourse_ai.logs.unknown"),
+ });
+ }
+
+ get formattedDuration() {
+ return this.args.log.duration_msecs == null
+ ? "—"
+ : i18n("discourse_ai.logs.detail.duration_seconds", {
+ seconds: (this.args.log.duration_msecs / 1000).toFixed(1),
+ });
+ }
+
+ get topicUrl() {
+ return this.args.log.topic_id
+ ? getURL(`/t/${this.args.log.topic_id}`)
+ : null;
+ }
+
+ get postUrl() {
+ return this.args.log.post_id ? getURL(`/p/${this.args.log.post_id}`) : null;
+ }
+
+ get hasContext() {
+ return Boolean(this.topicUrl || this.postUrl);
+ }
+
+ <template>
+ <tr class="d-table__row ai-logs__row" data-log-id={{@log.id}}>
+ <td class="d-table__cell ai-logs__col-outcome">
+ <div class="ai-logs__status-cell">
+ <span
+ class="ai-logs__status-dot {{this.statusClass}}"
+ role="img"
+ title={{this.statusLabel}}
+ aria-label={{this.statusLabel}}
+ ></span>
+ {{#if @log.has_retries}}
+ <span
+ class="ai-logs__flag"
+ role="img"
+ title={{i18n "discourse_ai.logs.retried"}}
+ aria-label={{i18n "discourse_ai.logs.retried"}}
+ >
+ {{dIcon "arrows-rotate"}}
+ </span>
+ {{/if}}
+ </div>
+ </td>
+ <td class="d-table__cell ai-logs__col-time">
+ {{dAgeWithTooltip @log.created_at}}
+ </td>
+ <td class="d-table__cell ai-logs__col-request">
+ <span class="ai-logs__feature" title={{this.featureName}}>
+ {{this.featureName}}
+ </span>
+ <span class="ai-logs__model" title={{this.modelName}}>
+ {{this.modelName}}
+ </span>
+ </td>
+ <td class="d-table__cell ai-logs__col-user">
+ {{#if @log.username}}
+ <DUserLink
+ @user={{@log}}
+ class="ai-logs__user"
+ title={{@log.username}}
+ >
+ {{dAvatar
+ @log
+ avatarTemplatePath="avatar_template"
+ imageSize="tiny"
+ }}
+ <span>{{@log.username}}</span>
+ </DUserLink>
+ {{else}}
+ <span class="ai-logs__unattributed">
+ {{i18n "discourse_ai.logs.unattributed"}}
+ </span>
+ {{/if}}
+ </td>
+ <td class="d-table__cell ai-logs__col-duration">
+ <span class="ai-logs__duration-value">{{this.formattedDuration}}</span>
+ <span class="ai-logs__token-summary">
+ <span aria-hidden="true" dir="ltr">{{this.tokensLabel}}</span>
+ <span class="sr-only">{{this.tokensAriaLabel}}</span>
+ </span>
+ </td>
+ <td class="d-table__cell ai-logs__col-context">
+ <div class="ai-logs__context-links">
+ {{#if this.topicUrl}}
+ <a href={{this.topicUrl}}>
+ {{i18n "discourse_ai.logs.topic_short" [email protected]_id}}
+ </a>
+ {{/if}}
+ {{#if this.postUrl}}
+ <a href={{this.postUrl}}>
+ {{i18n "discourse_ai.logs.post_short" [email protected]_id}}
+ </a>
+ {{/if}}
+ {{#unless this.hasContext}}
+ <span class="ai-logs__empty-value">—</span>
+ {{/unless}}
+ </div>
+ </td>
+ <td class="d-table__cell ai-logs__col-actions --controls">
+ <DButton
+ class="btn-flat"
+ @icon="ellipsis"
+ @action={{fn @onOpen @log.id}}
+ @title="discourse_ai.logs.view_details"
+ @ariaLabel="discourse_ai.logs.view_details"
+ />
+ </td>
+ </tr>
+ </template>
+}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-payload-viewer.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-payload-viewer.gjs
new file mode 100644
index 00000000000..574ffb705d2
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-payload-viewer.gjs
@@ -0,0 +1,55 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { clipboardCopy } from "discourse/lib/utilities";
+import DButton from "discourse/ui-kit/d-button";
+
+const JSON_FORMAT_LIMIT = 200_000;
+
+export default class AiPayloadViewer extends Component {
+ @cached
+ get content() {
+ const payload = this.args.payload;
+ if (!payload) {
+ return "";
+ }
+
+ if (payload.length > JSON_FORMAT_LIMIT) {
+ return payload;
+ }
+
+ try {
+ return JSON.stringify(JSON.parse(payload), null, 2);
+ } catch {
+ return payload;
+ }
+ }
+
+ @action
+ copy() {
+ clipboardCopy(this.args.payload || "");
+ this.args.onCopy?.();
+ }
+
+ <template>
+ <div class="ai-payload-viewer" ...attributes>
+ {{#if @payload}}
+ {{#if @truncated}}
+ <p class="ai-payload-viewer__notice">
+ {{@truncatedMessage}}
+ </p>
+ {{/if}}
+ <pre class="ai-payload-viewer__content" tabindex="0"><code
+ >{{this.content}}</code></pre>
+ <DButton
+ class="btn-default ai-payload-viewer__copy"
+ @icon="copy"
+ @action={{this.copy}}
+ @translatedLabel={{@copyLabel}}
+ />
+ {{else}}
+ <p class="ai-payload-viewer__empty">{{@emptyMessage}}</p>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs
index fb018024861..13de1ff61a3 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs
@@ -3,15 +3,13 @@ import { tracked } from "@glimmer/tracking";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { next } from "@ember/runloop";
-import { trustHTML } from "@ember/template";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import discourseLater from "discourse/lib/later";
-import { clipboardCopy, escapeExpression } from "discourse/lib/utilities";
import DButton from "discourse/ui-kit/d-button";
import DModal from "discourse/ui-kit/d-modal";
import { i18n } from "discourse-i18n";
-import { jsonToHtml } from "../../lib/utilities";
+import AiPayloadViewer from "discourse/plugins/discourse-ai/discourse/components/ai-payload-viewer";
export default class DebugAiModal extends Component {
@tracked info = null;
@@ -25,42 +23,29 @@ export default class DebugAiModal extends Component {
});
}
- get htmlContext() {
+ get activePayload() {
if (!this.info) {
- return "";
- }
-
- let parsed;
-
- try {
- if (this.activeTab === "request") {
- parsed = JSON.parse(this.info.raw_request_payload);
- } else {
- return this.formattedResponse(this.info.raw_response_payload);
- }
- } catch {
- return this.info.raw_request_payload;
+ return null;
}
- return jsonToHtml(parsed);
+ return this.activeTab === "request"
+ ? this.info.raw_request_payload
+ : this.info.raw_response_payload;
}
- formattedResponse(response) {
- // we need to replace the new lines with <br> to make it look good
- const split = response.split("\n");
- const safe = split.map((line) => escapeExpression(line)).join("<br>");
-
- return trustHTML(safe);
+ get activeCopyLabel() {
+ return this.activeTab === "request"
+ ? i18n("discourse_ai.ai_bot.debug_ai_modal.copy_request")
+ : i18n("discourse_ai.ai_bot.debug_ai_modal.copy_response");
}
@action
- copyRequest() {
- this.copy(this.info.raw_request_payload);
- }
+ copied() {
+ this.justCopiedText = i18n("discourse_ai.ai_bot.conversation_shared");
- @action
- copyResponse() {
- this.copy(this.info.raw_response_payload);
+ discourseLater(() => {
+ this.justCopiedText = "";
+ }, 2000);
}
async loadLog(logId) {
@@ -85,15 +70,6 @@ export default class DebugAiModal extends Component {
this.loadLog(this.info.next_log_id);
}
- copy(text) {
- clipboardCopy(text);
- this.justCopiedText = i18n("discourse_ai.ai_bot.conversation_shared");
-
- discourseLater(() => {
- this.justCopiedText = "";
- }, 2000);
- }
-
loadApiRequestInfo() {
ajax(`/discourse-ai/ai-bot/post/${this.args.model.id}/show-debug-info.json`)
.then((result) => {
@@ -288,46 +264,36 @@ export default class DebugAiModal extends Component {
</p>
{{/if}}
</div>
- <div class="ai-debug-modal__preview">
- {{this.htmlContext}}
- </div>
+ <AiPayloadViewer
+ class="ai-debug-modal__preview"
+ @payload={{this.activePayload}}
+ @copyLabel={{this.activeCopyLabel}}
+ @onCopy={{this.copied}}
+ @emptyMessage={{i18n
+ "discourse_ai.ai_bot.debug_ai_modal.payload_unavailable"
+ }}
+ />
{{/if}}
</:body>
<:footer>
- {{#if this.info}}
+ {{#if this.info.prev_log_id}}
<DButton
- class="btn confirm"
- @icon="copy"
- @action={{this.copyRequest}}
- @label="discourse_ai.ai_bot.debug_ai_modal.copy_request"
+ class="btn"
+ @icon="angles-left"
+ @action={{this.prevLog}}
+ @label="discourse_ai.ai_bot.debug_ai_modal.previous_log"
/>
+ {{/if}}
+ {{#if this.info.next_log_id}}
<DButton
- class="btn confirm"
- @icon="copy"
- @action={{this.copyResponse}}
- @label="discourse_ai.ai_bot.debug_ai_modal.copy_response"
+ class="btn"
+ @icon="angles-right"
+ @action={{this.nextLog}}
+ @label="discourse_ai.ai_bot.debug_ai_modal.next_log"
/>
- {{#if this.info.prev_log_id}}
- <DButton
- class="btn"
- @icon="angles-left"
- @action={{this.prevLog}}
- @label="discourse_ai.ai_bot.debug_ai_modal.previous_log"
- />
- {{/if}}
- {{#if this.info.next_log_id}}
- <DButton
- class="btn"
- @icon="angles-right"
- @action={{this.nextLog}}
- @label="discourse_ai.ai_bot.debug_ai_modal.next_log"
- />
- {{/if}}
- <span
- class="ai-debug-modal__just-copied"
- >{{this.justCopiedText}}</span>
{{/if}}
+ <span class="ai-debug-modal__just-copied">{{this.justCopiedText}}</span>
</:footer>
</DModal>
</template>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
index 1fcab47f56c..1be1e19109d 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
@@ -60,6 +60,11 @@ export default {
route: "adminPlugins.show.discourse-ai-translations",
description: "discourse_ai.translations.description",
},
+ {
+ label: "discourse_ai.logs.short_title",
+ route: "adminPlugins.show.discourse-ai-logs",
+ description: "discourse_ai.logs.description",
+ },
]);
});
},
diff --git a/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss b/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss
new file mode 100644
index 00000000000..1f72ff7b31a
--- /dev/null
+++ b/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss
@@ -0,0 +1,415 @@
+@use "lib/viewport";
+
+.ai-logs {
+ padding: var(--space-4);
+
+ &__retention {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ margin-bottom: var(--space-4);
+ padding: var(--space-3);
+ border: 1px solid var(--content-border-color);
+ background: var(--primary-very-low);
+ }
+
+ &__retention-warning {
+ margin: 0;
+ color: var(--primary-high);
+ }
+
+ &__filters {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ margin-bottom: var(--space-4);
+ }
+
+ &__periods,
+ &__date-range {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__filter-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
+ align-items: end;
+ width: 100%;
+ gap: var(--space-2);
+
+ > * {
+ min-width: 0;
+ }
+
+ .d-select {
+ width: 100%;
+ }
+ }
+
+ &__user-filter .select-kit {
+ width: 100%;
+ max-width: var(--form-kit-medium-input);
+
+ @include viewport.until(sm) {
+ max-width: 100%;
+ }
+ }
+
+ &__toggle {
+ align-self: end;
+ padding-bottom: var(--space-2);
+ }
+
+ &__id-filter {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: end;
+ gap: var(--space-2);
+
+ > .form-kit__field {
+ min-width: 10rem;
+ }
+ }
+
+ &__table-wrapper {
+ border-block: 1px solid var(--content-border-color);
+ }
+
+ &__table {
+ width: 100%;
+ table-layout: fixed;
+
+ th,
+ td {
+ vertical-align: middle;
+ }
+
+ th {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ font-weight: 600;
+ }
+ }
+
+ &__row {
+ transition: background-color 0.15s ease;
+
+ &:focus-within {
+ background: var(--primary-very-low);
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ }
+
+ html.discourse-no-touch &:hover {
+ background: var(--primary-very-low);
+ }
+ }
+
+ &__col-time {
+ width: 6rem;
+ }
+
+ td.ai-logs__col-time {
+ color: var(--primary-high);
+ white-space: nowrap;
+ }
+
+ &__col-outcome {
+ width: 5rem;
+ text-align: center;
+ }
+
+ &__col-user {
+ width: 10rem;
+ }
+
+ &__col-duration {
+ width: 7.5rem;
+ text-align: end;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ }
+
+ &__duration-value,
+ &__token-summary {
+ display: block;
+ }
+
+ &__token-summary {
+ margin-top: 0.15em;
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ }
+
+ &__col-context {
+ width: 10rem;
+ }
+
+ &__col-actions {
+ width: 3rem;
+ text-align: end;
+
+ .btn-flat {
+ color: var(--primary-high);
+ }
+ }
+
+ &__model,
+ &__unattributed,
+ &__empty-value {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ }
+
+ &__status-cell {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-1);
+ }
+
+ &__status-dot {
+ display: inline-block;
+ width: 0.65rem;
+ height: 0.65rem;
+ flex: 0 0 0.65rem;
+ border-radius: 50%;
+ cursor: help;
+
+ &.--success {
+ background: var(--success);
+ }
+
+ &.--failed {
+ background: var(--danger);
+ }
+ }
+
+ &__flag {
+ display: inline-flex;
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ }
+
+ &__feature,
+ &__model {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__feature {
+ font-weight: 600;
+ }
+
+ &__model {
+ margin-top: 0.15em;
+ }
+
+ &__user {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ gap: var(--space-1);
+ color: var(--primary);
+
+ span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+
+ &__context-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1) var(--space-2);
+ }
+
+ &__empty {
+ padding: var(--space-8);
+ color: var(--primary-high);
+ text-align: center;
+ }
+
+ @include viewport.until(xl) {
+ &__col-context {
+ display: none;
+ }
+ }
+
+ @include viewport.until(lg) {
+ padding: var(--space-2);
+
+ &__col-outcome {
+ width: 4rem;
+ }
+
+ &__col-user {
+ width: 7.5rem;
+ }
+
+ &__col-duration {
+ width: 6.5rem;
+ }
+
+ &__model {
+ display: none;
+ }
+ }
+
+ @include viewport.until(md) {
+ &__table {
+ margin-bottom: 0;
+ }
+
+ &__row {
+ display: grid;
+ grid-template-columns: auto 1fr auto;
+ grid-template-areas:
+ "outcome time actions"
+ "request request request"
+ "user user duration";
+ align-items: center;
+ padding-block: var(--space-1);
+
+ > .d-table__cell {
+ width: auto;
+ padding: var(--space-1) var(--space-2);
+ border-top: 0;
+ }
+
+ > .ai-logs__col-time {
+ grid-area: time;
+ }
+
+ > .ai-logs__col-outcome {
+ grid-area: outcome;
+ }
+
+ > .ai-logs__col-request {
+ grid-area: request;
+ }
+
+ > .ai-logs__col-user {
+ grid-area: user;
+ min-width: 0;
+ }
+
+ > .ai-logs__col-duration {
+ grid-area: duration;
+ text-align: end;
+ }
+
+ > .ai-logs__col-actions {
+ position: static;
+ grid-area: actions;
+ }
+ }
+
+ &__status-cell {
+ justify-content: start;
+ }
+ }
+}
+
+.d-modal.ai-log-detail-modal {
+ --modal-max-width: min(96vw, 75rem);
+}
+
+.ai-log-detail-modal {
+ &__metadata {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
+ gap: var(--space-2);
+ margin: 0 0 var(--space-4);
+
+ div {
+ min-width: 0;
+ padding: var(--space-2);
+ background: var(--primary-very-low);
+ }
+
+ dt {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ }
+
+ dd {
+ margin: 0;
+ overflow-wrap: anywhere;
+ font-variant-numeric: tabular-nums;
+ }
+ }
+
+ &__tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+ margin-bottom: var(--space-3);
+ }
+
+ &__attempts {
+ margin: 0;
+ padding-inline-start: var(--space-6);
+ }
+
+ &__error {
+ padding: var(--space-6);
+ text-align: center;
+ }
+}
+
+.d-modal.ai-log-retention-modal {
+ --modal-max-width: 36rem;
+}
+
+.ai-log-retention-modal {
+ &__lifecycle {
+ display: grid;
+ grid-template-columns: 1fr auto 1fr auto 1fr;
+ gap: var(--space-2);
+ align-items: center;
+ margin-bottom: var(--space-2);
+ padding: var(--space-2);
+ background: var(--primary-very-low);
+ text-align: center;
+
+ @include viewport.until(sm) {
+ grid-template-columns: 1fr;
+
+ &-arrow {
+ transform: rotate(90deg);
+ }
+ }
+ }
+
+ &__hint,
+ &__meta {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ }
+
+ &__hint {
+ margin-bottom: var(--space-4);
+ }
+
+ &__meta {
+ margin: var(--space-3) 0 0;
+ }
+
+ &__preview {
+ margin: 0;
+ padding: var(--space-3);
+ border-inline-start: 3px solid var(--tertiary);
+ background: var(--primary-very-low);
+ font-weight: 600;
+ }
+}
diff --git a/plugins/discourse-ai/assets/stylesheets/common/ai-payload-viewer.scss b/plugins/discourse-ai/assets/stylesheets/common/ai-payload-viewer.scss
new file mode 100644
index 00000000000..24fca891411
--- /dev/null
+++ b/plugins/discourse-ai/assets/stylesheets/common/ai-payload-viewer.scss
@@ -0,0 +1,34 @@
+.ai-payload-viewer {
+ &__notice {
+ color: var(--danger);
+ font-weight: 600;
+ }
+
+ &__content {
+ max-height: 60vh;
+ margin: 0 0 var(--space-2);
+ padding: var(--space-3);
+ overflow: auto;
+ border: 1px solid var(--content-border-color);
+ border-radius: var(--d-border-radius);
+ background: var(--primary-very-low);
+ color: var(--primary);
+ font-family: var(--d-font-family--monospace);
+ font-size: var(--font-down-1);
+ line-height: var(--line-height-medium);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+
+ &:focus-visible {
+ outline: 2px solid var(--tertiary);
+ outline-offset: 2px;
+ }
+ }
+
+ &__empty {
+ padding: var(--space-6);
+ border: 1px dashed var(--content-border-color);
+ color: var(--primary-high);
+ text-align: center;
+ }
+}
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
index 00ff9a90cf9..768c2e578cf 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
@@ -182,18 +182,6 @@ span.onebox-ai-llm-title {
align-self: center;
}
-.ai-debug-modal__preview {
- background-color: var(--primary-very-low);
- border: 1px solid var(--primary-low);
- border-radius: var(--d-border-radius);
- padding: 0.75em 1em;
- max-height: 60vh;
- overflow: auto;
- font-family: var(--d-font-family--monospace);
- font-size: var(--font-down-1);
- line-height: 1.45;
-}
-
.d-modal ul.ai-debug-modal__nav {
margin: 0 0 1em;
padding: 0;
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index f45bf09278d..e6a48c8d56a 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -654,6 +654,109 @@ en:
custom: "Custom..."
credit_allocations: "Credit allocations"
+ logs:
+ short_title: "Logs"
+ description: "Inspect individual requests sent to AI models and their responses"
+ sensitive_warning: "Only administrators can view AI logs."
+ refresh: "Refresh logs"
+ retry: "Try again"
+ apply: "Apply"
+ find: "Find"
+ clear_filters: "Clear filters"
+ all_outcomes: "All outcomes"
+ all_models: "All models"
+ successful: "Successful"
+ failed: "Failed"
+ unknown: "Unknown"
+ has_retries: "Has retries"
+ retried: "Retried"
+ unattributed: "Unattributed"
+ feature_placeholder: "Feature name"
+ user_placeholder: "Filter by user"
+ id_placeholder: "Enter an ID"
+ log_id: "Log ID"
+ topic_id: "Topic ID"
+ post_id: "Post ID"
+ time: "Time"
+ when: "When"
+ outcome: "Outcome"
+ feature: "Feature"
+ model: "Model"
+ request: "Request"
+ provider: "Provider"
+ user: "User"
+ tokens: "Tokens"
+ tokens_pair: "%{request} → %{response}"
+ tokens_aria: "%{request} input tokens and %{response} output tokens"
+ tokens_unavailable: "Token counts unavailable"
+ cache_read_tokens: "Cache read"
+ cache_write_tokens: "Cache write"
+ context: "Context"
+ topic: "Topic"
+ topic_short: "Topic %{id}"
+ post: "Post"
+ post_short: "Post %{id}"
+ duration: "Duration"
+ duration_tokens: "Duration / tokens"
+ first_token: "First token"
+ cost: "Cost"
+ actions: "Actions"
+ table_caption: "AI requests sent to language models and their outcomes"
+ view_details: "View details"
+ no_results: "No AI logs match these filters."
+ no_logs: "No retained AI logs were found."
+ filters:
+ period: "Time period"
+ date_range: "Date range"
+ id_type: "ID type"
+ id_value: "ID value"
+ periods:
+ hour: "Last hour"
+ day: "Last 24 hours"
+ week: "Last 7 days"
+ custom: "Custom"
+ detail:
+ title: "AI log #%{id}"
+ request: "Request"
+ response: "Response"
+ context: "Context"
+ attempts: "Attempts"
+ tabs_label: "AI log payload sections"
+ copy_request: "Copy request"
+ copy_response: "Copy response"
+ copy_context: "Copy context"
+ payload_unavailable: "Payload not available"
+ payload_truncated: "This payload is too large to display completely and has been truncated."
+ load_error: "This log could not be found. It may have been removed by the retention policy."
+ generic_load_error: "This log could not be loaded. Try again."
+ network_error: "Network error"
+ outcome_with_status: "%{outcome} (%{status})"
+ duration_seconds: "%{seconds} s"
+ attempt: "Status %{status}, delay %{delay} ms"
+ retention:
+ configure: "Configure retention"
+ title: "Log retention"
+ lifecycle_label: "Logs are kept first as full payloads, then as summaries, then deleted."
+ detailed_stage: "Full payload"
+ summary_stage: "Summary"
+ deleted_stage: "Deleted"
+ hint: "Days are counted from the request date. 0 means no separate limit."
+ detailed_title: "Full payloads (days)"
+ detailed_help: "Raw requests and responses. 0 keeps them until the summary is deleted."
+ summary_title: "Summaries (days)"
+ summary_help: "Audit metadata. 0 keeps it forever."
+ invalid_order: "Summaries must be kept at least as long as payloads."
+ valid_range: "Enter a whole number from 0 to %{max}."
+ destructive_warning: "Shorter retention permanently deletes data at the next cleanup. This cannot be undone."
+ meta: "Using %{size} · Cleanup runs daily · Usage data is unaffected"
+ save: "Save"
+ saved: "Retention saved. Cleanup runs within 24 hours."
+ lifecycle:
+ complete_forever: "Logs kept forever"
+ detail_until_delete: "Full logs kept %{summary} days, then deleted"
+ summary_forever: "Payloads kept %{detailed} days, summaries kept forever"
+ finite: "Payloads kept %{detailed} days, summaries %{summary} days, then deleted"
+
ai_agent:
ai_tools: "Tools"
native_tools_help: "Provider-native tools, such as web search or page fetch, appear when \"Always use default language model\" is enabled and the selected default language model supports them."
@@ -1370,6 +1473,7 @@ en:
title: "View AI interaction"
copy_request: "Copy request"
copy_response: "Copy response"
+ payload_unavailable: "Payload not available"
this_turn: "This turn:"
whole_conversation: "Conversation:"
tokens_summary: "%{request_tokens} in → %{response_tokens} out"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 9607ded7212..147f33b553e 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -181,7 +181,8 @@ en:
ai_translation_backfill_hourly_rate: "The number of posts and topics to translate per hour during backfill operations. Set to 0 to disable automatic backfilling of translations for existing content."
ai_translation_backfill_parallel_jobs: "The number of parallel post localization jobs to run per backfill cycle. Higher values increase throughput but consume more resources."
ai_usage_rollup_after_days: "Number of days to keep per-request AI usage stats before rolling them into daily aggregates. Set to 0 to disable rollups."
- ai_audit_logs_purge_after_days: "Delete AI API audit logs older than this many days. Defaults to about 6 months. Set to 0 to keep indefinitely."
+ ai_audit_logs_detailed_retention_days: "Keep raw AI request and response payloads for this many days. Set to 0 to keep payloads until the summary log is deleted. Raw payloads can contain private or sensitive content. Cleanup continues while the AI plugin is disabled."
+ ai_audit_logs_purge_after_days: "Keep AI API audit log summaries for this many days before deleting the entire log. Set to 0 to keep summaries forever. Cleanup continues while the AI plugin is disabled."
reviewables:
reasons:
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index fcb25d14d7c..5e87bfb10ea 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -153,6 +153,9 @@ Discourse::Application.routes.draw do
get "/ai-usage", to: "discourse_ai/admin/ai_usage#show"
get "/ai-usage-report", to: "discourse_ai/admin/ai_usage#report"
+ get "/ai-logs", to: "discourse_ai/admin/ai_logs#index"
+ put "/ai-logs/retention", to: "discourse_ai/admin/ai_logs#update_retention"
+ get "/ai-logs/:id", to: "discourse_ai/admin/ai_logs#show", constraints: { id: /\d+/ }
get "/ai-spam", to: "discourse_ai/admin/ai_spam#show"
put "/ai-spam", to: "discourse_ai/admin/ai_spam#update"
post "/ai-spam/test", to: "discourse_ai/admin/ai_spam#test"
diff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.yml
index 9ff3184d59c..c8ac5691563 100644
--- a/plugins/discourse-ai/config/settings.yml
+++ b/plugins/discourse-ai/config/settings.yml
@@ -661,7 +661,13 @@ discourse_ai:
client: false
hidden: true
+ ai_audit_logs_detailed_retention_days:
+ default: 0
+ min: 0
+ max: 36500
+ client: false
ai_audit_logs_purge_after_days:
default: 180
min: 0
+ max: 36500
client: false
diff --git a/plugins/discourse-ai/db/migrate/20260818045305_add_failed_id_index_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20260818045305_add_failed_id_index_to_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..7dce8e1ee93
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260818045305_add_failed_id_index_to_ai_api_audit_logs.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+class AddFailedIdIndexToAiApiAuditLogs < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_ai_api_audit_logs_failed_id"
+ FAILURE_CONDITION =
+ "(response_status IS NOT NULL AND response_status NOT BETWEEN 200 AND 299) OR " \
+ "(response_status IS NULL AND COALESCE(response_tokens, 0) <= 0)"
+
+ def up
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :ai_api_audit_logs,
+ :id,
+ name: INDEX_NAME,
+ where: FAILURE_CONDITION,
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20260818045308_add_retry_id_index_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20260818045308_add_retry_id_index_to_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..88805b29c96
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260818045308_add_retry_id_index_to_ai_api_audit_logs.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class AddRetryIdIndexToAiApiAuditLogs < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_ai_api_audit_logs_retried_id"
+
+ def up
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :ai_api_audit_logs,
+ :id,
+ name: INDEX_NAME,
+ where: "request_attempts IS NOT NULL",
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20260818045311_add_user_id_id_index_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20260818045311_add_user_id_id_index_to_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..0d86f15e40e
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260818045311_add_user_id_id_index_to_ai_api_audit_logs.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+class AddUserIdIdIndexToAiApiAuditLogs < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_ai_api_audit_logs_user_id_id"
+
+ def up
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :ai_api_audit_logs, %i[user_id id], name: INDEX_NAME, algorithm: :concurrently
+ end
+
+ def down
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20260818045314_add_feature_name_id_index_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20260818045314_add_feature_name_id_index_to_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..e03012acd3e
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260818045314_add_feature_name_id_index_to_ai_api_audit_logs.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class AddFeatureNameIdIndexToAiApiAuditLogs < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_ai_api_audit_logs_feature_name_id"
+
+ def up
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :ai_api_audit_logs,
+ %i[feature_name id],
+ name: INDEX_NAME,
+ where: "feature_name IS NOT NULL",
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20260818045317_add_payload_id_index_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20260818045317_add_payload_id_index_to_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..9f429d249fc
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260818045317_add_payload_id_index_to_ai_api_audit_logs.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class AddPayloadIdIndexToAiApiAuditLogs < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_ai_api_audit_logs_payload_id"
+
+ def up
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :ai_api_audit_logs,
+ :id,
+ name: INDEX_NAME,
+ where: "raw_request_payload IS NOT NULL OR raw_response_payload IS NOT NULL",
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :ai_api_audit_logs, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index a968e1ab48c..2b8d5415192 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -20,8 +20,10 @@ register_asset "stylesheets/common/streaming.scss"
register_asset "stylesheets/common/ai-blinking-animation.scss"
register_asset "stylesheets/common/ai-user-settings.scss"
register_asset "stylesheets/common/ai-features.scss"
+register_asset "stylesheets/common/ai-payload-viewer.scss"
register_asset "stylesheets/admin/ai-features-editor.scss", :admin
+register_asset "stylesheets/admin/ai-logs.scss", :admin
register_asset "stylesheets/modules/translation/admin/translations.scss", :admin
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb
index fe7848fabaa..db78edc3303 100644
--- a/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb
@@ -3,26 +3,127 @@
RSpec.describe Jobs::PurgeAiApiAuditLogs do
before do
enable_current_plugin
+ SiteSetting.ai_audit_logs_detailed_retention_days = 30
SiteSetting.ai_audit_logs_purge_after_days = 180
freeze_time Time.zone.parse("2025-11-22 12:00:00 UTC")
end
let(:job) { described_class.new }
- it "removes audit logs older than the retention window" do
- recent = AiApiAuditLog.create!(provider_id: 1, created_at: 10.days.ago)
- stale = AiApiAuditLog.create!(provider_id: 1, created_at: 181.days.ago)
+ it "removes expired summaries and strips payloads from expired details" do
+ recent =
+ Fabricate(
+ :ai_api_audit_log,
+ raw_request_payload: "recent request",
+ raw_response_payload: "recent response",
+ created_at: 10.days.ago,
+ )
+ summary =
+ Fabricate(
+ :ai_api_audit_log,
+ raw_request_payload: "old request",
+ raw_response_payload: "old response",
+ feature_context: {
+ "source" => "spec",
+ },
+ request_attempts: [{ "status" => 429, "delay_ms" => 1_000 }],
+ created_at: 31.days.ago,
+ )
+ expired = Fabricate(:ai_api_audit_log, raw_request_payload: "expired", created_at: 181.days.ago)
- expect { job.execute({}) }.to change { AiApiAuditLog.count }.by(-1)
+ job.execute({})
- expect(AiApiAuditLog.exists?(recent.id)).to be(true)
- expect(AiApiAuditLog.exists?(stale.id)).to be(false)
+ expect(AiApiAuditLog.exists?(expired.id)).to eq(false)
+ expect(recent.reload).to have_attributes(
+ raw_request_payload: "recent request",
+ raw_response_payload: "recent response",
+ )
+ expect(summary.reload).to have_attributes(
+ raw_request_payload: nil,
+ raw_response_payload: nil,
+ feature_context: {
+ "source" => "spec",
+ },
+ request_attempts: [{ "status" => 429, "delay_ms" => 1_000 }],
+ created_at: 31.days.ago,
+ )
end
- it "does nothing when retention is disabled" do
+ it "keeps full details until deletion when detailed retention is zero" do
+ SiteSetting.ai_audit_logs_detailed_retention_days = 0
+ recent = Fabricate(:ai_api_audit_log, raw_request_payload: "kept", created_at: 179.days.ago)
+ expired = Fabricate(:ai_api_audit_log, raw_request_payload: "deleted", created_at: 181.days.ago)
+
+ job.execute({})
+
+ expect(recent.reload.raw_request_payload).to eq("kept")
+ expect(AiApiAuditLog.exists?(expired.id)).to eq(false)
+ end
+
+ it "keeps summaries forever when summary retention is zero" do
+ SiteSetting.ai_audit_logs_purge_after_days = 0
+ log = Fabricate(:ai_api_audit_log, raw_request_payload: "strip", created_at: 31.days.ago)
+
+ job.execute({})
+
+ expect(log.reload.raw_request_payload).to be_nil
+ expect(AiApiAuditLog.exists?(log.id)).to eq(true)
+ end
+
+ it "does nothing when both retention periods are forever" do
+ SiteSetting.ai_audit_logs_detailed_retention_days = 0
SiteSetting.ai_audit_logs_purge_after_days = 0
- AiApiAuditLog.create!(provider_id: 1, created_at: 400.days.ago)
+ log = Fabricate(:ai_api_audit_log, raw_request_payload: "kept", created_at: 400.days.ago)
+
+ expect { job.execute({}) }.not_to change { log.reload.attributes }
+ end
+
+ it "applies retention when Discourse AI is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+ log = Fabricate(:ai_api_audit_log, raw_request_payload: "strip", created_at: 31.days.ago)
+
+ job.execute({})
+
+ expect(log.reload.raw_request_payload).to be_nil
+ end
+
+ it "processes deletion and payload stripping across batches" do
+ stub_const(described_class, :BATCH_SIZE, 2) do
+ expired_logs =
+ Fabricate.times(
+ 5,
+ :ai_api_audit_log,
+ raw_request_payload: "delete",
+ created_at: 181.days.ago,
+ )
+ summary_logs =
+ Fabricate.times(5, :ai_api_audit_log, raw_request_payload: "strip", created_at: 31.days.ago)
+
+ job.execute({})
+
+ expect(AiApiAuditLog.where(id: expired_logs.map(&:id))).to be_empty
+ expect(AiApiAuditLog.where(id: summary_logs.map(&:id)).pluck(:raw_request_payload)).to all(
+ be_nil,
+ )
+ end
+ end
+
+ it "handles retention settings with an inverted cutoff safely" do
+ SiteSetting.ai_audit_logs_detailed_retention_days = 180
+ SiteSetting.ai_audit_logs_purge_after_days = 30
+ deleted = Fabricate(:ai_api_audit_log, raw_request_payload: "delete", created_at: 31.days.ago)
+ retained = Fabricate(:ai_api_audit_log, raw_request_payload: "keep", created_at: 29.days.ago)
+
+ job.execute({})
+
+ expect(AiApiAuditLog.exists?(deleted.id)).to eq(false)
+ expect(retained.reload.raw_request_payload).to eq("keep")
+ end
+
+ it "is idempotent" do
+ log = Fabricate(:ai_api_audit_log, raw_request_payload: "strip", created_at: 31.days.ago)
- expect { job.execute({}) }.not_to change { AiApiAuditLog.count }
+ job.execute({})
+ expect { job.execute({}) }.not_to change { log.reload.attributes }
end
end
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_logs_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_logs_controller_spec.rb
new file mode 100644
index 00000000000..dd80277e964
--- /dev/null
+++ b/plugins/discourse-ai/spec/requests/admin/ai_logs_controller_spec.rb
@@ -0,0 +1,445 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Admin::AiLogsController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+ fab!(:llm_model)
+
+ let(:index_path) { "/admin/plugins/discourse-ai/ai-logs.json" }
+
+ before do |example|
+ enable_current_plugin
+ sign_in(admin) if !example.metadata[:anonymous]
+ end
+
+ def request_ai_logs_endpoint(endpoint, log, headers: {})
+ case endpoint
+ when :index
+ get index_path, headers:
+ when :show
+ get "/admin/plugins/discourse-ai/ai-logs/#{log.id}.json", headers:
+ when :retention
+ put "/admin/plugins/discourse-ai/ai-logs/retention.json",
+ params: {
+ detailed_days: 30,
+ summary_days: 180,
+ },
+ headers:
+ end
+ end
+
+ it "defines a display name for every audit provider" do
+ AiApiAuditLog::Provider.constants.each do |constant|
+ provider_id = AiApiAuditLog::Provider.const_get(constant)
+ expect(DiscourseAi::Admin::AiLogSerializerHelpers.provider_name(provider_id)).to be_present
+ end
+ end
+
+ describe "administrator-only access" do
+ fab!(:post)
+ fab!(:log) do
+ Fabricate(
+ :ai_api_audit_log,
+ topic: post.topic,
+ post:,
+ raw_request_payload: "sensitive request",
+ raw_response_payload: "sensitive response",
+ )
+ end
+
+ it "denies anonymous users from every endpoint", :anonymous do
+ %i[index show retention].each do |endpoint|
+ request_ai_logs_endpoint(endpoint, log)
+ expect(response.status).to eq(404),
+ "expected #{endpoint} to be hidden from anonymous users, got #{response.status}"
+ expect(response.body).not_to include("sensitive request", "sensitive response")
+ end
+ end
+
+ it "denies regular users and moderators from every endpoint even when they can see the topic" do
+ [user, moderator].each do |non_admin|
+ sign_in(non_admin)
+
+ %i[index show retention].each do |endpoint|
+ request_ai_logs_endpoint(endpoint, log)
+ expect(response.status).to eq(404),
+ "expected #{endpoint} to be hidden from #{non_admin.username}"
+ end
+ end
+ end
+
+ it "denies non-admin API keys from every endpoint", :anonymous do
+ api_key = Fabricate(:api_key, user:)
+ headers = { "Api-Key" => api_key.key, "Api-Username" => user.username }
+
+ %i[index show retention].each do |endpoint|
+ request_ai_logs_endpoint(endpoint, log, headers:)
+ expect(response.status).to eq(404),
+ "expected #{endpoint} to be hidden from a non-admin API key"
+ end
+ end
+
+ it "keeps every endpoint unavailable when the plugin is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+
+ %i[index show retention].each do |endpoint|
+ request_ai_logs_endpoint(endpoint, log)
+ expect(response.status).to eq(404), "expected #{endpoint} to require the enabled plugin"
+ end
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-ai/ai-logs.json" do
+ it "returns lightweight logs newest first with retention metadata" do
+ older_log =
+ Fabricate(
+ :ai_api_audit_log,
+ raw_request_payload: "secret request",
+ raw_response_payload: "secret response",
+ created_at: 2.hours.ago,
+ user:,
+ llm_model:,
+ language_model: llm_model.name,
+ feature_name: "summarize",
+ request_tokens: 10,
+ response_tokens: 5,
+ response_status: 200,
+ duration_msecs: 1_400,
+ )
+ newer_log =
+ Fabricate(
+ :ai_api_audit_log,
+ raw_request_payload: nil,
+ raw_response_payload: nil,
+ created_at: 1.hour.ago,
+ response_status: 500,
+ response_tokens: 0,
+ request_attempts: [{ "status" => 500, "delay_ms" => 0 }],
+ )
+
+ get index_path, params: { include_meta: true }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq(
+ [newer_log.id, older_log.id],
+ )
+ expect(response.parsed_body["logs"].first).to include("has_retries" => true)
+ expect(response.parsed_body["logs"].last).to include(
+ "username" => user.username,
+ "model_name" => llm_model.display_name,
+ "duration_msecs" => 1_400,
+ )
+ expect(response.parsed_body["logs"].last.keys).not_to include(
+ "raw_request_payload",
+ "raw_response_payload",
+ "feature_context",
+ "request_attempts",
+ )
+ expect(response.parsed_body.dig("meta", "retention")).to eq(
+ "detailed_days" => 0,
+ "summary_days" => 180,
+ )
+ expect(response.parsed_body.dig("meta", "storage", "total_bytes")).to be_positive
+ end
+
+ it "orders by persisted ID rather than backdated request start time" do
+ earlier_id = Fabricate(:ai_api_audit_log, created_at: 1.minute.ago)
+ later_id = Fabricate(:ai_api_audit_log, created_at: 1.day.ago)
+
+ get index_path
+
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq(
+ [later_id.id, earlier_id.id],
+ )
+ end
+
+ it "does not select heavyweight detail columns for the list" do
+ Fabricate(:ai_api_audit_log, raw_request_payload: "secret")
+
+ queries = track_sql_queries { get index_path }
+ list_query = queries.find { |query| query.include?("AS has_retries") }
+
+ expect(list_query).to be_present
+ %w[raw_request_payload raw_response_payload feature_context request_attempts].each do |column|
+ expect(list_query).not_to include(%("ai_api_audit_logs"."#{column}"))
+ end
+ end
+
+ it "only returns retention metadata and filter options when requested" do
+ Fabricate(:ai_api_audit_log)
+
+ get index_path
+ expect(response.parsed_body["meta"]).not_to have_key("retention")
+ expect(response.parsed_body).not_to have_key("models")
+ expect(response.parsed_body).not_to have_key("features")
+
+ get index_path, params: { include_meta: true }
+ expect(response.parsed_body.dig("meta", "retention")).to be_present
+ expect(response.parsed_body).to have_key("models")
+ expect(response.parsed_body).to have_key("features")
+ end
+
+ it "filters by outcome, retries, model, feature, user, and exact IDs" do
+ matching_log =
+ Fabricate(
+ :ai_api_audit_log,
+ user:,
+ llm_model:,
+ feature_name: "matching-feature",
+ response_status: 500,
+ response_tokens: 0,
+ request_attempts: [{ "status" => 500, "delay_ms" => 0 }],
+ topic_id: 123,
+ post_id: 456,
+ )
+ Fabricate(
+ :ai_api_audit_log,
+ feature_name: "other-feature",
+ response_status: 200,
+ response_tokens: 10,
+ )
+
+ get index_path, params: { username: user.username }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([matching_log.id])
+
+ get index_path, params: { unattributed: true }
+ expect(response.parsed_body["logs"].length).to eq(1)
+ expect(response.parsed_body["logs"].first["feature_name"]).to eq("other-feature")
+
+ get index_path,
+ params: {
+ outcome: "failed",
+ has_retries: true,
+ llm_id: llm_model.id,
+ feature: "matching-feature",
+ user_id: user.id,
+ }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([matching_log.id])
+
+ get index_path,
+ params: {
+ topic_id: matching_log.topic_id,
+ start_date: 50.years.from_now.to_date,
+ }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([matching_log.id])
+
+ get index_path, params: { post_id: matching_log.post_id }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([matching_log.id])
+
+ get index_path, params: { id: matching_log.id, cursor: matching_log.id }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([matching_log.id])
+ end
+
+ it "uses the health-check outcome semantics" do
+ success_with_no_tokens =
+ Fabricate(:ai_api_audit_log, response_status: 200, response_tokens: 0)
+ statusless_success = Fabricate(:ai_api_audit_log, response_status: nil, response_tokens: 1)
+ statusless_failure = Fabricate(:ai_api_audit_log, response_status: nil, response_tokens: 0)
+
+ get index_path, params: { outcome: "successful" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to contain_exactly(
+ success_with_no_tokens.id,
+ statusless_success.id,
+ )
+
+ get index_path, params: { outcome: "failed" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([statusless_failure.id])
+ end
+
+ it "caps a requested page size and rejects invalid limits" do
+ Fabricate.times(55, :ai_api_audit_log)
+
+ get index_path, params: { limit: 500 }
+ expect(response.parsed_body["logs"].length).to eq(50)
+ expect(response.parsed_body.dig("meta", "has_more")).to eq(true)
+
+ get index_path, params: { limit: 0 }
+ expect(response.status).to eq(400)
+ end
+
+ it "paginates with an ID cursor" do
+ logs = Fabricate.times(52, :ai_api_audit_log)
+
+ get index_path
+ first_page = response.parsed_body
+
+ expect(first_page["logs"].length).to eq(50)
+ expect(first_page.dig("meta", "has_more")).to eq(true)
+ expect(first_page.dig("meta", "next_cursor")).to eq(logs[-50].id)
+
+ get index_path, params: { cursor: first_page.dig("meta", "next_cursor") }
+ second_page = response.parsed_body
+
+ expect(second_page["logs"].map { |log| log["id"] }).to eq(logs.first(2).reverse.map(&:id))
+ expect(second_page.dig("meta", "has_more")).to eq(false)
+ expect(second_page["meta"]).not_to have_key("storage")
+ end
+
+ it "paginates exact topic lookups" do
+ logs = Fabricate.times(52, :ai_api_audit_log, topic_id: 789)
+
+ get index_path, params: { topic_id: 789 }
+ first_page = response.parsed_body
+
+ expect(first_page["logs"].length).to eq(50)
+ expect(first_page.dig("meta", "has_more")).to eq(true)
+
+ get index_path, params: { topic_id: 789, cursor: first_page.dig("meta", "next_cursor") }
+ second_page = response.parsed_body
+
+ expect(second_page["logs"].map { |log| log["id"] }).to eq(logs.first(2).reverse.map(&:id))
+ expect(second_page.dig("meta", "has_more")).to eq(false)
+ end
+
+ it "rejects malformed and conflicting filters" do
+ get index_path, params: { outcome: "maybe" }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { id: 1, topic_id: 2 }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { timezone: "Not/AZone", start_date: "2026-01-01" }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { has_retries: "maybe" }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { include_meta: "maybe" }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { start_date: "2026-02-01", end_date: "2026-01-01" }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { start_date: "2024-01-01", end_date: "2026-01-02" }
+ expect(response.status).to eq(400)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-ai/ai-logs/:id.json" do
+ it "returns raw details and truncates oversized payloads" do
+ log =
+ Fabricate(
+ :ai_api_audit_log,
+ raw_request_payload: "a" * (1.megabyte + 10),
+ raw_response_payload: '{"answer":"ok"}',
+ feature_context: {
+ source: "spec",
+ },
+ request_attempts: [{ "status" => 0, "delay_ms" => 500 }],
+ duration_msecs: 1_400,
+ time_to_first_token_msecs: 320,
+ estimated_cost: 0,
+ )
+
+ get "/admin/plugins/discourse-ai/ai-logs/#{log.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to include(
+ "id" => log.id,
+ "payload_available" => true,
+ "raw_request_payload_bytes" => 1.megabyte + 10,
+ "raw_request_payload_truncated" => true,
+ "raw_response_payload" => log.raw_response_payload,
+ "duration_msecs" => 1_400,
+ "time_to_first_token_msecs" => 320,
+ "spending" => 0.0,
+ )
+ expect(response.parsed_body["raw_request_payload"].bytesize).to eq(1.megabyte)
+ end
+
+ it "keeps truncated multibyte payloads valid and within the response cap" do
+ payload = "😀" * 300_000
+ log = Fabricate(:ai_api_audit_log, raw_request_payload: payload)
+
+ get "/admin/plugins/discourse-ai/ai-logs/#{log.id}.json"
+
+ returned_payload = response.parsed_body["raw_request_payload"]
+ expect(response.status).to eq(200)
+ expect(returned_payload.valid_encoding?).to eq(true)
+ expect(returned_payload.bytesize).to be <= 1.megabyte
+ expect(response.parsed_body["raw_request_payload_bytes"]).to eq(payload.bytesize)
+ expect(response.parsed_body["raw_request_payload_truncated"]).to eq(true)
+ end
+
+ it "returns a payload-unavailable record and 404 for a missing record" do
+ log = Fabricate(:ai_api_audit_log, raw_request_payload: nil, raw_response_payload: nil)
+
+ get "/admin/plugins/discourse-ai/ai-logs/#{log.id}.json"
+ expect(response.parsed_body).to include(
+ "payload_available" => false,
+ "raw_request_payload" => nil,
+ "raw_response_payload" => nil,
+ )
+
+ get "/admin/plugins/discourse-ai/ai-logs/#{log.id + 100_000}.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-ai/ai-logs/retention.json" do
+ let(:path) { "/admin/plugins/discourse-ai/ai-logs/retention.json" }
+
+ it "updates both retention settings" do
+ SiteSetting.ai_audit_logs_purge_after_days = 90
+
+ expect do put path, params: { detailed_days: 30, summary_days: 180 } end.to change {
+ UserHistory.where(action: UserHistory.actions[:change_site_setting]).count
+ }.by(2)
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["retention"]).to eq("detailed_days" => 30, "summary_days" => 180)
+ expect(SiteSetting.ai_audit_logs_detailed_retention_days).to eq(30)
+ expect(SiteSetting.ai_audit_logs_purge_after_days).to eq(180)
+ end
+
+ it "supports keeping complete logs forever" do
+ SiteSetting.ai_audit_logs_detailed_retention_days = 30
+ SiteSetting.ai_audit_logs_purge_after_days = 180
+
+ put path, params: { detailed_days: 0, summary_days: 0 }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["retention"]).to eq("detailed_days" => 0, "summary_days" => 0)
+ end
+
+ it "supports full detail until finite deletion" do
+ put path, params: { detailed_days: 0, summary_days: 180 }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["retention"]).to eq("detailed_days" => 0, "summary_days" => 180)
+ end
+
+ it "rejects impossible and malformed pairs" do
+ put path, params: { detailed_days: 181, summary_days: 180 }
+ expect(response.status).to eq(400)
+
+ put path, params: { detailed_days: -1, summary_days: 0 }
+ expect(response.status).to eq(400)
+
+ put path, params: { detailed_days: 0, summary_days: 36_501 }
+ expect(response.status).to eq(400)
+ end
+
+ it "does not partially update the pair when a setting is invalid" do
+ SiteSetting.ai_audit_logs_detailed_retention_days = 30
+ SiteSetting.ai_audit_logs_purge_after_days = 180
+
+ put path, params: { detailed_days: 10, summary_days: 36_501 }
+
+ expect(response.status).to eq(400)
+ expect(SiteSetting.ai_audit_logs_detailed_retention_days).to eq(30)
+ expect(SiteSetting.ai_audit_logs_purge_after_days).to eq(180)
+ end
+
+ it "rejects requests without a CSRF token" do
+ ActionController::Base.allow_forgery_protection = true
+
+ put path, params: { detailed_days: 30, summary_days: 180 }
+
+ expect(response.status).to eq(403)
+ ensure
+ ActionController::Base.allow_forgery_protection = false
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/system/ai_logs_spec.rb b/plugins/discourse-ai/spec/system/ai_logs_spec.rb
new file mode 100644
index 00000000000..d05d80327f6
--- /dev/null
+++ b/plugins/discourse-ai/spec/system/ai_logs_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+RSpec.describe "AI logs admin page" do
+ fab!(:admin)
+ fab!(:llm_model)
+ fab!(:log) do
+ Fabricate(
+ :ai_api_audit_log,
+ llm_model:,
+ language_model: llm_model.name,
+ feature_name: "system-test",
+ raw_request_payload: '{"prompt":"Inspect this request"}',
+ raw_response_payload: '{"answer":"Inspectable response"}',
+ request_tokens: 20,
+ response_tokens: 10,
+ response_status: 200,
+ duration_msecs: 1_400,
+ time_to_first_token_msecs: 320,
+ estimated_cost: 0,
+ )
+ end
+
+ let(:ai_logs_page) { PageObjects::Pages::AiLogs.new }
+
+ before do
+ enable_current_plugin
+ sign_in(admin)
+ end
+
+ it "applies typed feature and ID filters" do
+ ai_logs_page.visit
+
+ select I18n.t("js.discourse_ai.logs.failed"), from: I18n.t("js.discourse_ai.logs.outcome")
+ expect(ai_logs_page).to have_no_log(log)
+
+ select I18n.t("js.discourse_ai.logs.all_outcomes"), from: I18n.t("js.discourse_ai.logs.outcome")
+ expect(ai_logs_page).to have_log(log)
+
+ find("input[placeholder='#{I18n.t("js.discourse_ai.logs.feature_placeholder")}']").fill_in(
+ with: "missing-feature",
+ )
+ find("input[placeholder='#{I18n.t("js.discourse_ai.logs.feature_placeholder")}']").send_keys(
+ :enter,
+ )
+ expect(ai_logs_page).to have_no_log(log)
+
+ find("input[placeholder='#{I18n.t("js.discourse_ai.logs.id_placeholder")}']").fill_in(
+ with: log.id,
+ )
+ find(".ai-logs__id-filter .btn", text: I18n.t("js.discourse_ai.logs.find")).click
+ expect(ai_logs_page).to have_log(log)
+ end
+
+ it "restores model and period filters from the URL" do
+ other_model = Fabricate(:llm_model)
+ other_log =
+ Fabricate(
+ :ai_api_audit_log,
+ llm_model: other_model,
+ language_model: other_model.name,
+ created_at: 10.minutes.ago,
+ )
+
+ ai_logs_page.visit("model=#{other_model.id}&period=hour")
+
+ expect(ai_logs_page).to have_log(other_log)
+ expect(ai_logs_page).to have_no_log(log)
+ end
+
+ it "lets an admin inspect a raw log and open retention configuration" do
+ ai_logs_page.visit
+
+ expect(ai_logs_page).to have_log(log)
+
+ ai_logs_page.open_log(log)
+ expect(ai_logs_page).to have_payload("Inspect this request")
+ expect(page).to have_css(".ai-log-detail-modal__metadata-duration", text: "1.4 s")
+ expect(page).to have_css(".ai-log-detail-modal__metadata-first-token", text: "0.3 s")
+ expect(page).to have_no_css(".ai-log-detail-modal__metadata-cost")
+ expect(page).to have_current_path(/details=#{log.id}/, url: true)
+
+ page.go_back
+ expect(page).to have_no_css(".ai-log-detail-modal")
+ expect(page).to have_current_path(%r{/ai-logs$}, url: true)
+
+ page.go_forward
+ expect(ai_logs_page).to have_payload("Inspect this request")
+ find(".ai-log-detail-modal .modal-close").click
+ ai_logs_page.open_retention
+ expect(ai_logs_page).to have_retention_modal
+ expect(page).to have_field(
+ I18n.t("js.discourse_ai.logs.retention.detailed_title"),
+ with: SiteSetting.ai_audit_logs_detailed_retention_days,
+ )
+ expect(page).to have_no_text(I18n.t("js.discourse_ai.logs.retention.destructive_warning"))
+
+ fill_in I18n.t("js.discourse_ai.logs.retention.detailed_title"), with: 30
+ fill_in I18n.t("js.discourse_ai.logs.retention.summary_title"), with: 180
+ expect(page).to have_text(I18n.t("js.discourse_ai.logs.retention.destructive_warning"))
+
+ fill_in I18n.t("js.discourse_ai.logs.retention.summary_title"), with: 10
+ click_button I18n.t("js.discourse_ai.logs.retention.save")
+ expect(page).to have_text(I18n.t("js.discourse_ai.logs.retention.invalid_order"))
+ end
+end
diff --git a/plugins/discourse-ai/spec/system/page_objects/pages/ai_logs.rb b/plugins/discourse-ai/spec/system/page_objects/pages/ai_logs.rb
new file mode 100644
index 00000000000..f580325039b
--- /dev/null
+++ b/plugins/discourse-ai/spec/system/page_objects/pages/ai_logs.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class AiLogs < PageObjects::Pages::Base
+ def visit(query = nil)
+ path = "/admin/plugins/discourse-ai/ai-logs"
+ page.visit(query ? "#{path}?#{query}" : path)
+ self
+ end
+
+ def open_log(log)
+ find(%(.ai-logs__row[data-log-id="#{log.id}"])).find(".btn").click
+ self
+ end
+
+ def open_retention
+ find(
+ ".ai-logs .btn-primary",
+ text: I18n.t("js.discourse_ai.logs.retention.configure"),
+ ).click
+ self
+ end
+
+ def has_log?(log)
+ page.has_css?(%(.ai-logs__row[data-log-id="#{log.id}"]))
+ end
+
+ def has_no_log?(log)
+ page.has_no_css?(%(.ai-logs__row[data-log-id="#{log.id}"]))
+ end
+
+ def has_payload?(text)
+ page.has_css?(".ai-payload-viewer__content", text:)
+ end
+
+ def has_retention_modal?
+ page.has_css?(".ai-log-retention-modal")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-log-row-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-log-row-test.gjs
new file mode 100644
index 00000000000..5bbc3e61c39
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-log-row-test.gjs
@@ -0,0 +1,93 @@
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import AiLogRow from "discourse/plugins/discourse-ai/discourse/components/ai-log-row";
+
+module("Integration | Component | AiLogRow", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders statusless positive-token calls as successful", async function (assert) {
+ this.log = {
+ id: 43,
+ created_at: "2026-08-17T12:00:00Z",
+ response_status: null,
+ response_tokens: 1,
+ };
+
+ await render(
+ <template>
+ <table><tbody><AiLogRow @log={{this.log}} /></tbody></table>
+ </template>
+ );
+
+ assert
+ .dom('.ai-logs__status-dot[title="Successful"]')
+ .hasAttribute("aria-label", "Successful", "success dot is labelled");
+ });
+
+ test("renders operational metadata and opens details", async function (assert) {
+ this.log = {
+ id: 42,
+ created_at: "2026-08-17T12:00:00Z",
+ response_status: 500,
+ response_tokens: 3_000,
+ request_tokens: 12_000,
+ duration_msecs: 1_400,
+ has_retries: true,
+ feature_name: "summarize",
+ model_name: "Test model",
+ username: "user1",
+ avatar_template: "/letter_avatar_proxy/v4/letter/u/13edae/{size}.png",
+ topic_id: 10,
+ post_id: 11,
+ };
+ this.openedId = null;
+ this.open = (id) => (this.openedId = id);
+
+ await render(
+ <template>
+ <table><tbody><AiLogRow
+ @log={{this.log}}
+ @onOpen={{this.open}}
+ /></tbody></table>
+ </template>
+ );
+
+ assert
+ .dom('.ai-logs__status-dot[title="Failed"]')
+ .hasAttribute("aria-label", "Failed", "failure dot is labelled");
+ assert.dom(".ai-logs__flag").exists({ count: 1 }, "retry uses an icon");
+ assert
+ .dom('.ai-logs__flag[title="Retried"]')
+ .exists("retry state is available to assistive technology");
+ assert.dom(".ai-logs__id").doesNotExist("log ID is omitted");
+ assert.dom(".ai-logs__feature").hasText("summarize");
+ assert.dom(".ai-logs__model").hasText("Test model");
+ assert.dom(".ai-logs__user").hasAttribute("href", "/u/user1");
+ assert.dom(".ai-logs__duration-value").hasText("1.4 s");
+ assert
+ .dom('.ai-logs__col-context a[href="/t/10"]')
+ .hasText("Topic 10", "topic is linked");
+ assert
+ .dom('.ai-logs__col-context a[href="/p/11"]')
+ .hasText("Post 11", "post is linked");
+ assert
+ .dom(".ai-logs__token-summary")
+ .includesText("12k → 3k", "tokens are compact and directional");
+ assert
+ .dom(".ai-logs__token-summary .sr-only")
+ .hasText(
+ "12,000 input tokens and 3,000 output tokens",
+ "assistive text retains exact token counts"
+ );
+ assert
+ .dom('.ai-logs__row .btn[aria-label="View details"]')
+ .exists("details action is labelled");
+ assert
+ .dom(".ai-logs__row .d-icon-ellipsis")
+ .exists("details use a compact ellipsis icon");
+
+ await click(".ai-logs__row .btn");
+ assert.strictEqual(this.openedId, 42, "details open for the selected log");
+ });
+});
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-payload-viewer-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-payload-viewer-test.gjs
new file mode 100644
index 00000000000..f2e914afa90
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-payload-viewer-test.gjs
@@ -0,0 +1,78 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import AiPayloadViewer from "discourse/plugins/discourse-ai/discourse/components/ai-payload-viewer";
+
+module("Integration | Component | AiPayloadViewer", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("formats JSON as escaped text", async function (assert) {
+ const payload = JSON.stringify({ html: "<img src=x onerror=alert(1)>" });
+
+ await render(
+ <template>
+ <AiPayloadViewer
+ @payload={{payload}}
+ @copyLabel="Copy payload"
+ @emptyMessage="Payload not available"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".ai-payload-viewer__content")
+ .hasText(
+ '{\n "html": "<img src=x onerror=alert(1)>"\n}',
+ "JSON is formatted as text"
+ );
+ assert
+ .dom(".ai-payload-viewer__content")
+ .hasAttribute("tabindex", "0", "long payloads are keyboard-scrollable");
+ assert
+ .dom(".ai-payload-viewer img")
+ .doesNotExist("payload HTML is not rendered");
+ });
+
+ test("shows the unavailable and truncated states", async function (assert) {
+ await render(
+ <template>
+ <AiPayloadViewer
+ @payload=""
+ @copyLabel="Copy payload"
+ @emptyMessage="Payload not available"
+ />
+ </template>
+ );
+ assert
+ .dom(".ai-payload-viewer__empty")
+ .hasText("Payload not available", "missing payloads are explained");
+
+ await render(
+ <template>
+ <AiPayloadViewer
+ @payload={{null}}
+ @copyLabel="Copy payload"
+ @emptyMessage="Payload not available"
+ />
+ </template>
+ );
+ assert
+ .dom(".ai-payload-viewer__empty")
+ .hasText("Payload not available", "null payloads are explained");
+
+ await render(
+ <template>
+ <AiPayloadViewer
+ @payload="partial"
+ @truncated={{true}}
+ @copyLabel="Copy payload"
+ @emptyMessage="Payload not available"
+ @truncatedMessage="Payload truncated"
+ />
+ </template>
+ );
+ assert
+ .dom(".ai-payload-viewer__notice")
+ .hasText("Payload truncated", "truncation is disclosed");
+ });
+});