Skip to content

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

UX: rework AI logs filtering (#42792)

Kris66b1ed762f96
diff --git a/app/assets/stylesheets/common/components/table-layout.scss b/app/assets/stylesheets/common/components/table-layout.scss
index e1707340da7..324ea1e7fbc 100644
--- a/app/assets/stylesheets/common/components/table-layout.scss
+++ b/app/assets/stylesheets/common/components/table-layout.scss
@@ -92,6 +92,7 @@
text-align: left;
font-weight: normal;
color: var(--primary-high);
+ vertical-align: bottom;
}
.d-table__row {
diff --git a/frontend/discourse/app/ui-kit/d-filter-controls.gjs b/frontend/discourse/app/ui-kit/d-filter-controls.gjs
index 0ffa3b852f2..ef352011495 100644
--- a/frontend/discourse/app/ui-kit/d-filter-controls.gjs
+++ b/frontend/discourse/app/ui-kit/d-filter-controls.gjs
@@ -58,7 +58,10 @@ const ResetButton = <template>
* For multiple dropdowns: receives (key, value)
* @param {Function} [onDropdownChange] - Callback for dropdown selection changes
* @param {Function} [onResetFilters] - Callback for reset action (server-side mode)
- * @param {Boolean} [additionalFiltersActive=false] - Whether filters rendered in the additionalFilters block are active
+ * @param {Function} [onFilterDropdownsToggle] - Callback fired when the dropdown drawer is opened or
+ * closed, receiving the new expanded state as a boolean
+ * @param {Boolean} [additionalFiltersActive=false] - Whether filters rendered in the additionalFilters block are active.
+ * The block renders alongside the dropdowns, sharing the drawer
* @param {String} [initialTextFilter] - Initial value to seed the text filter input on mount
* @param {Boolean} [showCustomEmptyState] - Whether to show a custom empty state when no results found,
* if minItemsForFilter is set and the array is empty
@@ -174,6 +177,12 @@ export default class DFilterControls extends Component {
);
}
+ // additional filters share the dropdown row, so they follow the drawer's
+ // state; with no drawer to hide behind they render on their own
+ get showStandaloneAdditionalFilters() {
+ return !this.showDropdownFilterToggle;
+ }
+
get showFilterResetButton() {
return (
this.showResetButton &&
@@ -459,6 +468,7 @@ export default class DFilterControls extends Component {
@action
toggleFilters() {
this.showFilterDropdowns = !this.showFilterDropdowns;
+ this.args.onFilterDropdownsToggle?.(this.showFilterDropdowns);
}
<template>
@@ -561,10 +571,14 @@ export default class DFilterControls extends Component {
{{/each}}
</DSelect>
{{/if}}
- </div>
- {{/if}}
- {{#if (has-block "additionalFilters")}}
+ {{yield to="additionalFilters"}}
+ </div>
+ {{else if
+ (and
+ this.showStandaloneAdditionalFilters (has-block "additionalFilters")
+ )
+ }}
<div class="d-filter-controls__additional-filters">
{{yield to="additionalFilters"}}
</div>
diff --git a/frontend/discourse/tests/integration/ui-kit/d-filter-controls-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-filter-controls-test.gjs
index 200a74dea2d..aeb9968d5e4 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-filter-controls-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-filter-controls-test.gjs
@@ -1250,4 +1250,34 @@ module("Integration | ui-kit | DFilterControls", function (hooks) {
.dom(".custom-empty-state")
.exists("renders the custom empty state when array is empty");
});
+
+ test("reports the drawer state when the filter toggle is used", async function (assert) {
+ this.set("data", SAMPLE_DATA);
+ this.set("dropdownOptions", {
+ category: SAMPLE_DROPDOWN_OPTIONS,
+ });
+ const states = [];
+ this.set("onToggle", (expanded) => states.push(expanded));
+
+ await render(
+ <template>
+ <DFilterControls
+ @array={{this.data}}
+ @dropdownOptions={{this.dropdownOptions}}
+ @filterDropdownsExpanded={{false}}
+ @forceShowDropdownFilterToggle={{true}}
+ @onFilterDropdownsToggle={{this.onToggle}}
+ />
+ </template>
+ );
+
+ await click(".d-filter-controls__toggle-filters");
+ await click(".d-filter-controls__toggle-filters");
+
+ assert.deepEqual(
+ states,
+ [true, false],
+ "each toggle reports the resulting expanded state"
+ );
+ });
});
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
index d254bffdcbc..52edf9b1817 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-logs.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-logs.gjs
@@ -1,31 +1,43 @@
import Component from "@glimmer/component";
import { cached, tracked } from "@glimmer/tracking";
-import { hash } from "@ember/helper";
+import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
import { next } from "@ember/runloop";
import { service } from "@ember/service";
-import withEventValue from "discourse/helpers/with-event-value";
+import UserAutocompleteResults from "discourse/components/user-autocomplete-results";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
+import discourseDebounce from "discourse/lib/debounce";
+import { INPUT_DELAY } from "discourse/lib/environment";
+import KeyValueStore from "discourse/lib/key-value-store";
+import { TextareaAutocompleteHandler } from "discourse/lib/textarea-text-manipulation";
import DiscourseURL from "discourse/lib/url";
-import UserChooser from "discourse/select-kit/components/user-chooser";
+import userSearch, { validateSearchResult } from "discourse/lib/user-search";
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 DCountI18n from "discourse/ui-kit/d-count-i18n";
import DDateTimeInputRange from "discourse/ui-kit/d-date-time-input-range";
import DFilterControls from "discourse/ui-kit/d-filter-controls";
import DLoadMore from "discourse/ui-kit/d-load-more";
import DPageSubheader from "discourse/ui-kit/d-page-subheader";
-import DSelect from "discourse/ui-kit/d-select";
import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";
+import dAutocomplete from "discourse/ui-kit/modifiers/d-autocomplete";
import { i18n } from "discourse-i18n";
import AiLogRow from "discourse/plugins/discourse-ai/discourse/components/ai-log-row";
+import { newLogsPollIntervalMs } from "../lib/ai-logs-poll-interval";
import AiLogFeatureFilter from "./ai-log-feature-filter";
import AiLogDetailModal from "./modal/ai-log-detail-modal";
import AiLogRetentionModal from "./modal/ai-log-retention-modal";
-const MAX_SAFE_ID = Number.MAX_SAFE_INTEGER;
+const ALL_FILTER_VALUE = "__all__";
+const CUSTOM_DEFAULT_DAYS = 30;
+const MAX_SEARCH_LENGTH = 200;
const PERIODS = {
hour: 1,
day: 24,
@@ -36,6 +48,7 @@ export default class AiLogs extends Component {
@service currentUser;
@service modal;
@service router;
+ @service siteSettings;
@service toasts;
@tracked logs = [];
@@ -49,25 +62,35 @@ export default class AiLogs extends Component {
@tracked hasRetries = false;
@tracked selectedModel;
@tracked selectedFeature;
- @tracked selectedUsernames = [];
+ @tracked searchText = "";
@tracked unattributed = false;
- @tracked idType = "id";
- @tracked idValue;
@tracked startDate;
@tracked endDate;
+ @tracked newLogsCount = 0;
+ @tracked loadingNewLogs = false;
+ keyValueStore = new KeyValueStore("discourse-ai-logs");
_requestId = 0;
_openRequestId = 0;
_openLogId;
+ _autocompleteCleanups = [];
+ _pollTimer;
+ _pollInFlight = false;
+ _pollEpoch = 0;
+ _emptyPolls = 0;
+ _sinceId = 0;
constructor() {
super(...arguments);
window.addEventListener("popstate", this.syncDetailsFromLocation);
+ document.addEventListener("visibilitychange", this.onVisibilityChange);
this.logs = this.args.model.logs || [];
this.meta = this.args.model.meta || {};
+ this.captureNewLogsBaseline();
this.models = this.args.model.models || [];
this.features = this.mergedFeatures(this.args.model.features, this.logs);
this.initializeFilters(this.args.queryParams);
+ this.schedulePoll();
if (this.args.queryParams.details) {
next(() =>
@@ -79,6 +102,8 @@ export default class AiLogs extends Component {
willDestroy() {
super.willDestroy(...arguments);
window.removeEventListener("popstate", this.syncDetailsFromLocation);
+ document.removeEventListener("visibilitychange", this.onVisibilityChange);
+ clearTimeout(this._pollTimer);
if (this._openLogId) {
this.modal.close();
}
@@ -111,45 +136,30 @@ export default class AiLogs extends Component {
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.searchText = params.search || "";
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();
+ : moment().subtract(CUSTOM_DEFAULT_DAYS, "days").toDate();
this.endDate = params.end_date
? moment(params.end_date).toDate()
: new Date();
}
- @cached
- get featureOptions() {
- if (this.selectedFeature && !this.features.includes(this.selectedFeature)) {
- return [...this.features, this.selectedFeature];
- }
-
- return this.features;
- }
-
get periodOptions() {
return [
- {
- value: "all",
- label: i18n("discourse_ai.logs.all_periods"),
- },
- { value: "hour", label: i18n("discourse_ai.logs.periods.hour") },
- { value: "day", label: i18n("discourse_ai.logs.periods.day") },
- { value: "week", label: i18n("discourse_ai.logs.periods.week") },
- { value: "custom", label: i18n("discourse_ai.logs.periods.custom") },
+ { 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 [
{
- value: "all",
+ value: ALL_FILTER_VALUE,
label: i18n("discourse_ai.logs.all_outcomes"),
},
{
@@ -160,14 +170,6 @@ export default class AiLogs extends Component {
];
}
- 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") },
- ];
- }
-
@cached
get modelOptions() {
const options = this.models.map((model) => ({
@@ -183,64 +185,104 @@ export default class AiLogs extends Component {
}
return [
- { value: "all", label: i18n("discourse_ai.logs.all_models") },
+ { value: ALL_FILTER_VALUE, label: i18n("discourse_ai.logs.all_models") },
...options,
];
}
+ @cached
+ get featureOptions() {
+ if (this.selectedFeature && !this.features.includes(this.selectedFeature)) {
+ return [...this.features, this.selectedFeature];
+ }
+
+ return this.features;
+ }
+
+ // one model leaves nothing to choose between, but a model carried in on the
+ // URL still needs somewhere to show and be cleared from
+ get showModelFilter() {
+ return this.models.length > 1 || Boolean(this.selectedModel);
+ }
+
@cached
get dropdownOptions() {
- return {
- period: this.periodOptions,
- outcome: this.outcomeOptions,
- model: this.modelOptions,
- };
+ const options = { outcome: this.outcomeOptions };
+ if (this.showModelFilter) {
+ options.model = this.modelOptions;
+ }
+
+ return options;
}
@cached
get dropdownValues() {
+ const values = { outcome: this.selectedOutcome || ALL_FILTER_VALUE };
+ if (this.showModelFilter) {
+ values.model = this.selectedModel || ALL_FILTER_VALUE;
+ }
+
+ return values;
+ }
+
+ @cached
+ get defaultDropdownValues() {
+ // model stays listed even while hidden: DFilterControls keeps the value it
+ // last tracked, and without a default to match it reads as an active filter
return {
- period: this.selectedPeriod || "all",
- outcome: this.selectedOutcome || "all",
- model: this.selectedModel || "all",
+ outcome: ALL_FILTER_VALUE,
+ model: ALL_FILTER_VALUE,
};
}
- get hasFilters() {
+ get rememberedDrawerExpanded() {
+ return this.keyValueStore.get("filter_drawer") !== "collapsed";
+ }
+
+ @action
+ persistDrawerState(expanded) {
+ this.keyValueStore.set({
+ key: "filter_drawer",
+ value: expanded ? "expanded" : "collapsed",
+ });
+ }
+
+ get additionalFiltersActive() {
return Boolean(
- this.selectedPeriod ||
- this.selectedOutcome ||
- this.hasRetries ||
- this.selectedModel ||
- this.selectedFeature ||
- this.selectedUsernames.length ||
- this.unattributed ||
- this.idValue
+ this.selectedFeature || this.hasRetries || this.unattributed
);
}
- get additionalFiltersActive() {
+ get hasActiveDrawerFilters() {
+ return Boolean(
+ this.selectedOutcome || this.selectedModel || this.additionalFiltersActive
+ );
+ }
+
+ get hasFilters() {
return Boolean(
+ this.selectedPeriod ||
+ this.selectedOutcome ||
this.hasRetries ||
+ this.selectedModel ||
this.selectedFeature ||
- this.selectedUsernames.length ||
- this.unattributed ||
- this.idValue
+ this.searchText ||
+ this.unattributed
);
}
get requestParams() {
+ const search = this.searchText.trim().slice(0, MAX_SEARCH_LENGTH);
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;
+ if (search) {
+ params.search = search;
}
if (this.selectedPeriod === "custom") {
@@ -273,10 +315,8 @@ export default class AiLogs extends Component {
has_retries: this.hasRetries ? "true" : null,
model: this.selectedModel || null,
feature: this.selectedFeature || null,
- username: this.selectedUsernames[0] || null,
+ search: this.searchText.trim() || null,
unattributed: this.unattributed ? "true" : null,
- id_type: this.idValue ? this.idType : null,
- id_value: this.idValue || null,
};
}
@@ -299,9 +339,11 @@ export default class AiLogs extends Component {
}
@action
- async refresh() {
+ async refresh({ focusFilters = false, quiet = false, skipUrl = false } = {}) {
const requestId = ++this._requestId;
- this.loading = true;
+ if (!quiet) {
+ this.loading = true;
+ }
this.loadingMore = false;
try {
const result = await ajax("/admin/plugins/discourse-ai/ai-logs.json", {
@@ -317,12 +359,28 @@ export default class AiLogs extends Component {
this.logs = result.logs;
this.meta = { ...this.meta, ...result.meta };
+ this.captureNewLogsBaseline();
this.models = result.models || this.models;
this.features = this.mergedFeatures(
result.features || this.features,
result.logs
);
- await this.updateUrl();
+ // a fresh list supersedes any in-flight new-log poll and clears the banner
+ this._pollEpoch++;
+ this.newLogsCount = 0;
+ this._emptyPolls = 0;
+ if (!skipUrl) {
+ await this.updateUrl();
+ if (focusFilters) {
+ next(() =>
+ document
+ .querySelector(
+ ".ai-logs .d-filter-controls__input, .ai-logs .d-filter-controls__toggle-filters"
+ )
+ ?.focus()
+ );
+ }
+ }
} catch (error) {
if (
requestId === this._requestId &&
@@ -337,7 +395,9 @@ export default class AiLogs extends Component {
!this.isDestroying &&
!this.isDestroyed
) {
- this.loading = false;
+ if (!quiet) {
+ this.loading = false;
+ }
}
}
}
@@ -386,6 +446,111 @@ export default class AiLogs extends Component {
}
}
+ get hasNewLogs() {
+ return this.newLogsCount > 0;
+ }
+
+ // an empty filtered list has no newest row to poll against, so fall back to
+ // the table's high-water mark — otherwise every row would count as new
+ captureNewLogsBaseline() {
+ this._sinceId = this.logs[0]?.id || this.meta.max_id || 0;
+ }
+
+ get pollIntervalMs() {
+ return newLogsPollIntervalMs(this._emptyPolls);
+ }
+
+ schedulePoll() {
+ clearTimeout(this._pollTimer);
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this._pollTimer = setTimeout(
+ () => this.pollForNewLogs(),
+ this.pollIntervalMs
+ );
+ }
+
+ @action
+ onVisibilityChange() {
+ if (document.visibilityState === "visible") {
+ // returning to the tab refreshes the banner immediately
+ this.pollForNewLogs();
+ }
+ }
+
+ @action
+ async pollForNewLogs() {
+ clearTimeout(this._pollTimer);
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ if (
+ this._openLogId ||
+ document.visibilityState === "hidden" ||
+ this.loading ||
+ this.loadingMore ||
+ this._pollInFlight
+ ) {
+ this.schedulePoll();
+ return;
+ }
+
+ const epoch = this._pollEpoch;
+ this._pollInFlight = true;
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-ai/ai-logs/new.json",
+ {
+ data: { ...this.requestParams, since_id: this._sinceId },
+ }
+ );
+ if (this.isDestroying || this.isDestroyed || epoch !== this._pollEpoch) {
+ return;
+ }
+ if (result.new_logs_count !== undefined) {
+ this.newLogsCount = result.new_logs_count;
+ // back off while the list is quiet; snap back the moment something
+ // arrives so the next wave is noticed without delay
+ this._emptyPolls = result.new_logs_count > 0 ? 0 : this._emptyPolls + 1;
+ }
+ } catch {
+ // transient failures are expected while offline; the next tick retries
+ } finally {
+ this._pollInFlight = false;
+ this.schedulePoll();
+ }
+ }
+
+ @action
+ async showIncomingLogs(event) {
+ event?.preventDefault();
+ if (this.loadingNewLogs) {
+ return;
+ }
+ this.loadingNewLogs = true;
+ try {
+ await this.refresh({ quiet: true });
+ } finally {
+ this.loadingNewLogs = false;
+ }
+ }
+
+ @action
+ selectPeriod(period) {
+ this.selectedPeriod = this.selectedPeriod === period ? undefined : period;
+ if (this.selectedPeriod) {
+ this.endDate = new Date();
+ this.startDate =
+ this.selectedPeriod === "custom"
+ ? moment().subtract(CUSTOM_DEFAULT_DAYS, "days").toDate()
+ : moment().subtract(PERIODS[this.selectedPeriod], "hours").toDate();
+ }
+ this.refresh();
+ }
+
@action
changeDateRange(value) {
this.startDate = value.from;
@@ -394,17 +559,9 @@ export default class AiLogs extends Component {
@action
changeDropdown(key, value) {
- const selectedValue = value === "all" ? undefined : value;
-
- if (key === "period") {
- this.selectedPeriod = selectedValue;
- if (this.selectedPeriod && this.selectedPeriod !== "custom") {
- this.endDate = new Date();
- this.startDate = moment()
- .subtract(PERIODS[this.selectedPeriod], "hours")
- .toDate();
- }
- } else if (key === "outcome") {
+ const selectedValue = value === ALL_FILTER_VALUE ? undefined : value;
+
+ if (key === "outcome") {
this.selectedOutcome = selectedValue;
} else if (key === "model") {
this.selectedModel = selectedValue;
@@ -420,61 +577,95 @@ export default class AiLogs extends Component {
}
@action
- changeUser(usernames) {
- const selectedUsernames = usernames || [];
- this.selectedUsernames = selectedUsernames;
- this.unattributed = false;
- this.refresh();
+ onTextFilterChange(event) {
+ // keep the live-search state in sync with the server's 200-char cap so a
+ // long paste surfaces as a truncation instead of a 400 error
+ this.searchText = (event.target.value || "").slice(0, MAX_SEARCH_LENGTH);
+ discourseDebounce(this, this.performLiveSearch, {}, INPUT_DELAY);
}
- @action
- toggleRetries() {
- this.hasRetries = !this.hasRetries;
- this.refresh();
+ async performLiveSearch() {
+ // Update the URL via replaceState (not a router transition) so typing is
+ // never interrupted by the focus churn a transition causes — a keystroke
+ // landing on <body> in that window would be silently dropped.
+ const url = new URL(window.location.href);
+ const search = this.searchText.trim();
+ if (search) {
+ url.searchParams.set("search", search);
+ } else {
+ url.searchParams.delete("search");
+ }
+ // URLSearchParams encodes spaces as "+"; emit %20 to match router URLs
+ url.search = url.search.replace(/\+/g, "%20");
+ DiscourseURL.replaceState(`${url.pathname}${url.search}${url.hash}`);
+ await this.refresh({ quiet: true, skipUrl: true });
}
@action
- toggleUnattributed() {
- this.unattributed = !this.unattributed;
- if (this.unattributed) {
- this.selectedUsernames = [];
+ attachUserAutocomplete(element) {
+ if (!this.siteSettings.enable_mentions) {
+ return;
}
- this.refresh();
+
+ const input = element.querySelector(".d-filter-controls__input");
+ if (!input || this._autocompleteCleanups.length) {
+ return;
+ }
+
+ const handler = new TextareaAutocompleteHandler(input);
+ const modifiers = [
+ dAutocomplete.setupAutocomplete(getOwner(this), input, handler, {
+ component: UserAutocompleteResults,
+ key: UserAutocompleteResults.TRIGGER_KEY,
+ autoSelectFirstSuggestion: false,
+ transformComplete: (result) => {
+ validateSearchResult(result);
+ return result.username || result.name;
+ },
+ dataSource: (term) =>
+ term.includes(" ") || term.trim().length < 2
+ ? []
+ : userSearch({ term }),
+ fixedTextareaPosition: true,
+ offset: 2,
+ }),
+ ];
+
+ this._autocompleteCleanups.push(() =>
+ modifiers.forEach((modifier) => modifier.cleanup())
+ );
}
@action
- setIdValue(value) {
- this.idValue = value || undefined;
+ teardownUserAutocomplete() {
+ this._autocompleteCleanups.forEach((cleanup) => cleanup());
+ this._autocompleteCleanups = [];
}
@action
- changeIdType(value) {
- this.idType = value;
- if (this.idValue) {
- this.refresh();
- }
+ toggleRetries() {
+ this.hasRetries = !this.hasRetries;
+ this.refresh();
}
@action
- findById(event) {
- event.preventDefault();
+ toggleUnattributed() {
+ this.unattributed = !this.unattributed;
this.refresh();
}
@action
clearFilters() {
this.selectedPeriod = undefined;
- this.startDate = moment().subtract(24, "hours").toDate();
+ this.startDate = moment().subtract(CUSTOM_DEFAULT_DAYS, "days").toDate();
this.endDate = new Date();
this.selectedOutcome = undefined;
- this.hasRetries = false;
this.selectedModel = undefined;
this.selectedFeature = undefined;
- this.selectedUsernames = [];
+ this.searchText = "";
+ this.hasRetries = false;
this.unattributed = false;
- this.idType = "id";
- this.idValue = undefined;
- return this.refresh();
+ this.refresh({ focusFilters: true });
}
@action
@@ -519,7 +710,11 @@ export default class AiLogs extends Component {
}
<template>
- <section class="ai-logs admin-detail">
+ <section
+ class="ai-logs admin-detail"
+ {{didInsert this.attachUserAutocomplete}}
+ {{willDestroy this.teardownUserAutocomplete}}
+ >
<DPageSubheader
@titleLabel={{i18n "discourse_ai.logs.short_title"}}
@descriptionLabel={{i18n "discourse_ai.logs.description"}}
@@ -538,29 +733,62 @@ export default class AiLogs extends Component {
</:actions>
</DPageSubheader>
- <DFilterControls
- @array={{this.logs}}
- @dropdownOptions={{this.dropdownOptions}}
- @dropdownValue={{this.dropdownValues}}
- @additionalFiltersActive={{this.additionalFiltersActive}}
- @filterDropdownsExpanded={{true}}
- @showDropdownFilterToggle={{false}}
- @showTextFilter={{false}}
- @showNoResults={{false}}
- @loading={{this.loading}}
- @onDropdownFilterChange={{this.changeDropdown}}
- @onResetFilters={{this.clearFilters}}
+ <div
+ class="ai-logs__filters
+ {{if this.hasActiveDrawerFilters 'ai-logs__filters--drawer-active'}}"
>
- <:aboveFilters>
- <h2 class="ai-logs__filters-title">
- {{i18n "discourse_ai.logs.filters.title"}}
- </h2>
- </:aboveFilters>
-
- <:additionalFilters>
- <fieldset class="ai-logs__feature-filter">
- <legend>{{i18n "discourse_ai.logs.feature"}}</legend>
+ <DFilterControls
+ @array={{this.logs}}
+ @dropdownOptions={{this.dropdownOptions}}
+ @dropdownValue={{this.dropdownValues}}
+ @defaultDropdownValue={{this.defaultDropdownValues}}
+ @additionalFiltersActive={{this.additionalFiltersActive}}
+ @filterDropdownsExpanded={{this.rememberedDrawerExpanded}}
+ @onFilterDropdownsToggle={{this.persistDrawerState}}
+ @inputPlaceholder={{i18n "discourse_ai.logs.search_placeholder"}}
+ @initialTextFilter={{this.searchText}}
+ @showNoResults={{false}}
+ @loading={{this.loading}}
+ @onDropdownFilterChange={{this.changeDropdown}}
+ @onTextFilterChange={{this.onTextFilterChange}}
+ @onResetFilters={{this.clearFilters}}
+ >
+ <:aboveFilters>
+ <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}}
+ {{#if (eq this.selectedPeriod "custom")}}
+ <div class="ai-logs__date-range">
+ <DDateTimeInputRange
+ @from={{this.startDate}}
+ @to={{this.endDate}}
+ @showFromTime={{false}}
+ @showToTime={{false}}
+ @onChange={{this.changeDateRange}}
+ />
+ <DButton
+ class="btn-default"
+ @action={{this.refresh}}
+ @label="discourse_ai.logs.apply"
+ />
+ </div>
+ {{/if}}
+ </div>
+ </:aboveFilters>
+
+ <:additionalFilters>
<AiLogFeatureFilter
+ class="ai-logs__feature-filter"
@valueProperty={{null}}
@nameProperty={{null}}
@value={{this.selectedFeature}}
@@ -571,123 +799,83 @@ export default class AiLogs extends Component {
translatedFilterPlaceholder=(i18n
"discourse_ai.logs.feature_placeholder"
)
+ headerAriaLabel=(i18n "discourse_ai.logs.feature")
}}
/>
- </fieldset>
-
- {{#if (eq this.selectedPeriod "custom")}}
- <fieldset class="ai-logs__date-range-filter">
- <legend>{{i18n "discourse_ai.logs.filters.date_range"}}</legend>
- <DDateTimeInputRange
- @from={{this.startDate}}
- @to={{this.endDate}}
- @showFromTime={{false}}
- @showToTime={{false}}
- @onChange={{this.changeDateRange}}
- />
- <DButton
- class="btn-default"
- @action={{this.refresh}}
- @label="discourse_ai.logs.apply"
- />
- </fieldset>
- {{/if}}
- <fieldset class="ai-logs__user-filter">
- <legend>{{i18n "discourse_ai.logs.user"}}</legend>
- <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")
- }}
- />
- </fieldset>
-
- <form class="ai-logs__id-filter" {{on "submit" this.findById}}>
- <label class="ai-logs__id-type">
- <span>{{i18n "discourse_ai.logs.filters.id_type"}}</span>
- <DSelect
- @value={{this.idType}}
- @includeNone={{false}}
- @onChange={{this.changeIdType}}
- as |select|
- >
- {{#each this.idTypeOptions as |idType|}}
- <select.Option @value={{idType.id}}>
- {{idType.name}}
- </select.Option>
- {{/each}}
- </DSelect>
- </label>
-
- <label class="ai-logs__id-value">
- <span>{{i18n "discourse_ai.logs.filters.id_value"}}</span>
- <input
- type="number"
- min="1"
- max={{MAX_SAFE_ID}}
- placeholder={{i18n "discourse_ai.logs.id_placeholder"}}
- value={{this.idValue}}
- {{on "input" (withEventValue this.setIdValue)}}
+ <div class="ai-logs__toggles">
+ <DToggleSwitch
+ @label="discourse_ai.logs.has_retries"
+ @state={{this.hasRetries}}
+ {{on "click" this.toggleRetries}}
/>
- </label>
- <DButton
- type="submit"
- class="btn-default ai-logs__find"
- @label="discourse_ai.logs.find"
- />
- </form>
-
- <div class="ai-logs__toggles">
- <DToggleSwitch
- @state={{this.hasRetries}}
- @label="discourse_ai.logs.has_retries"
- aria-label={{i18n "discourse_ai.logs.has_retries"}}
- {{on "click" this.toggleRetries}}
- />
-
- <DToggleSwitch
- @state={{this.unattributed}}
- @label="discourse_ai.logs.unattributed"
- aria-label={{i18n "discourse_ai.logs.unattributed"}}
- {{on "click" this.toggleUnattributed}}
- />
- </div>
- </:additionalFilters>
- </DFilterControls>
+ <DToggleSwitch
+ @label="discourse_ai.logs.unattributed"
+ @state={{this.unattributed}}
+ {{on "click" this.toggleUnattributed}}
+ />
+ </div>
+ </:additionalFilters>
+ </DFilterControls>
+ </div>
<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">
+ <div class="ai-logs__table-wrap">
+ {{#if this.hasNewLogs}}
+ <div class="show-more has-topics">
+ <a
+ tabindex="0"
+ href
+ class="alert alert-info clickable
+ {{if this.loadingNewLogs 'loading'}}"
+ {{on "click" this.showIncomingLogs}}
+ >
+ <DCountI18n
+ @key="discourse_ai.logs.new_logs_count"
+ @count={{this.newLogsCount}}
+ />
+ {{#if this.loadingNewLogs}}
+ {{dLoadingSpinner size="small"}}
+ {{/if}}
+ </a>
+ </div>
+ {{/if}}
+
+ {{#if this.logs.length}}
+ <DLoadMore
+ @action={{this.loadMore}}
+ @enabled={{this.meta.has_more}}
+ @isLoading={{this.loadingMore}}
+ >
+ <table class="d-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">
+ <th
+ class="d-table__header-cell ai-logs__col-outcome"
+ scope="col"
+ ><span class="sr-only">{{i18n
+ "discourse_ai.logs.outcome"
+ }}</span></th>
+ <th
+ class="d-table__header-cell ai-logs__col-time"
+ scope="col"
+ >{{i18n "discourse_ai.logs.when"}}</th>
+ <th
+ class="d-table__header-cell ai-logs__col-request"
+ scope="col"
+ >{{i18n "discourse_ai.logs.request"}}</th>
+ <th
+ class="d-table__header-cell ai-logs__col-user"
+ scope="col"
+ >{{i18n "discourse_ai.logs.user"}}</th>
+ <th
+ class="d-table__header-cell ai-logs__col-duration"
+ scope="col"
+ >
<span class="ai-logs__duration-heading">{{i18n
"discourse_ai.logs.duration"
}}</span>
@@ -695,15 +883,19 @@ export default class AiLogs extends Component {
"discourse_ai.logs.tokens_direction"
}}</span>
</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>
+ <th
+ class="d-table__header-cell ai-logs__col-context"
+ scope="col"
+ >{{i18n "discourse_ai.logs.context"}}</th>
+ <th
+ class="d-table__header-cell ai-logs__col-actions"
+ scope="col"
+ ><span class="sr-only">{{i18n
+ "discourse_ai.logs.actions"
+ }}</span></th>
</tr>
</thead>
- <tbody>
+ <tbody class="d-table__body">
{{#each this.logs as |currentLog|}}
<AiLogRow
@log={{currentLog}}
@@ -712,17 +904,17 @@ export default class AiLogs extends Component {
{{/each}}
</tbody>
</table>
+ </DLoadMore>
+ {{else}}
+ <div class="ai-logs__empty">
+ <p>{{if
+ this.hasFilters
+ (i18n "discourse_ai.logs.no_results")
+ (i18n "discourse_ai.logs.no_logs")
+ }}</p>
</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>
- </div>
- {{/if}}
+ {{/if}}
+ </div>
</DConditionalLoadingSpinner>
</section>
</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
index 4f3f4982fea..87ef3b8d4c3 100644
--- 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
@@ -9,10 +9,8 @@ export default class DiscourseAiLogsController extends Controller {
"has_retries",
{ selectedModel: "model" },
"feature",
- "username",
+ "search",
"unattributed",
- "id_type",
- "id_value",
"details",
];
@@ -23,9 +21,7 @@ export default class DiscourseAiLogsController extends Controller {
has_retries = null;
selectedModel = null;
feature = null;
- username = null;
+ search = null;
unattributed = null;
- id_type = null;
- id_value = null;
details = null;
}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/lib/ai-logs-poll-interval.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/lib/ai-logs-poll-interval.js
new file mode 100644
index 00000000000..e3e553e8370
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/lib/ai-logs-poll-interval.js
@@ -0,0 +1,14 @@
+export const NEW_LOGS_POLL_INTERVAL_MS = 20_000;
+export const NEW_LOGS_POLL_BACKOFF_STEP_MS = 10_000;
+export const NEW_LOGS_POLL_MAX_INTERVAL_MS = 60_000;
+
+export function newLogsPollIntervalMs(emptyPollCount = 0) {
+ const steps = Math.floor(
+ (NEW_LOGS_POLL_MAX_INTERVAL_MS - NEW_LOGS_POLL_INTERVAL_MS) /
+ NEW_LOGS_POLL_BACKOFF_STEP_MS
+ );
+ return (
+ NEW_LOGS_POLL_INTERVAL_MS +
+ Math.min(Math.max(emptyPollCount, 0), steps) * NEW_LOGS_POLL_BACKOFF_STEP_MS
+ );
+}
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
index b67b967d54c..3c2d0f00f8d 100644
--- 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
@@ -13,10 +13,8 @@ export default class DiscourseAiLogsRoute extends DiscourseRoute {
has_retries: { replace: true },
selectedModel: { replace: true },
feature: { replace: true },
- username: { replace: true },
+ search: { replace: true },
unattributed: { replace: true },
- id_type: { replace: true },
- id_value: { replace: true },
details: { replace: false },
};
@@ -24,9 +22,6 @@ export default class DiscourseAiLogsRoute extends DiscourseRoute {
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;
@@ -35,17 +30,14 @@ export default class DiscourseAiLogsRoute extends DiscourseRoute {
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 search = (params.search || "").trim().slice(0, 200);
const filterQueryParams = {
...params,
period,
outcome,
has_retries: hasRetries,
unattributed,
- id_type: idType,
- id_value: idValue,
+ search,
model: selectedModel,
};
delete filterQueryParams.selectedModel;
@@ -53,8 +45,6 @@ export default class DiscourseAiLogsRoute extends DiscourseRoute {
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;
@@ -72,10 +62,6 @@ export default class DiscourseAiLogsRoute extends DiscourseRoute {
}
}
- if (idValue) {
- requestParams[idType] = idValue;
- }
-
return {
data: await ajax("/admin/plugins/discourse-ai/ai-logs.json", {
data: requestParams,
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
index f7ed3db645a..f67d9c5eb10 100644
--- 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
@@ -10,6 +10,8 @@ module DiscourseAi
MAX_RETENTION_DAYS = 36_500
MAX_PAYLOAD_BYTES = 1.megabyte
MIN_PAYLOAD_CHARACTERS = MAX_PAYLOAD_BYTES / 4
+ MAX_SEARCH_LENGTH = 200
+ MAX_ID = 2**63 - 1
DETAIL_COLUMNS = %i[
id
provider_id
@@ -81,6 +83,7 @@ module DiscourseAi
meta: {
next_cursor: has_more ? logs.last&.id : nil,
has_more:,
+ max_id: AiApiAuditLog.maximum(:id),
},
}
@@ -101,6 +104,12 @@ module DiscourseAi
render json: response
end
+ def new_logs
+ since_id = since_id_param
+ count = filtered_logs.where("ai_api_audit_logs.id > ?", since_id).count
+ render json: { new_logs_count: count }
+ end
+
def show
log =
AiApiAuditLog
@@ -191,9 +200,14 @@ module DiscourseAi
scope = scope.where.not(request_attempts: nil) if boolean_param(:has_retries)
scope = scope.where(llm_id: params[:llm_id]) if params[:llm_id].present?
scope = scope.where(feature_name: params[:feature].to_s) if params[:feature].present?
+ scope = apply_search_filter(scope) if params[:search].present?
+
+ if boolean_param(:unattributed) &&
+ (params[:user_id].present? || params[:username].present? || search_usernames.any?)
+ raise Discourse::InvalidParameters.new(:unattributed)
+ end
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)
@@ -246,6 +260,68 @@ module DiscourseAi
raise Discourse::InvalidParameters.new(name)
end
+ def apply_search_filter(scope)
+ parsed = parsed_search
+
+ parsed[:ids].each { |column, value| scope = scope.where(column => value) }
+
+ parsed[:numerics].each do |value|
+ scope =
+ scope.where(
+ "ai_api_audit_logs.id = ? OR ai_api_audit_logs.topic_id = ? OR ai_api_audit_logs.post_id = ?",
+ value,
+ value,
+ value,
+ )
+ end
+
+ if parsed[:usernames].any?
+ clause = Array.new(parsed[:usernames].length, "users.username ILIKE ?").join(" AND ")
+ values = parsed[:usernames].map { |value| "%#{value}%" }
+ scope = scope.joins(:user).where(clause, *values)
+ end
+
+ scope
+ end
+
+ def search_usernames
+ params[:search].present? ? parsed_search[:usernames] : []
+ end
+
+ def parsed_search
+ return @parsed_search if @parsed_search
+
+ search = params[:search].to_s.strip
+ raise Discourse::InvalidParameters.new(:search) if search.length > MAX_SEARCH_LENGTH
+
+ id_columns = { "log" => "id", "topic" => "topic_id", "post" => "post_id" }
+ parsed = { ids: [], numerics: [], usernames: [] }
+
+ search
+ .split(/\s+/)
+ .each do |token|
+ if (match = token.match(/\A(log|topic|post):(\d+)\z/))
+ parsed[:ids] << [id_columns.fetch(match[1]), bounded_positive_id!(match[2])]
+ elsif token.match?(/\A\d+\z/)
+ parsed[:numerics] << bounded_positive_id!(token)
+ else
+ username = token.delete_prefix("@")
+ if username.present?
+ parsed[:usernames] << username.gsub(/[\\%_]/) { |char| "\\#{char}" }
+ end
+ end
+ end
+
+ @parsed_search = parsed
+ end
+
+ def bounded_positive_id!(value)
+ parsed = Integer(value, exception: false)
+ raise Discourse::InvalidParameters.new(:search) if !positive_id?(parsed)
+
+ parsed
+ end
+
def apply_outcome_filter(scope)
case params[:outcome]
when nil, ""
@@ -279,11 +355,16 @@ module DiscourseAi
def positive_integer!(name)
value = Integer(params[name], exception: false)
- raise Discourse::InvalidParameters.new(name) if !value || value <= 0
+ raise Discourse::InvalidParameters.new(name) if !positive_id?(value)
value
end
+ # anything wider than a bigint overflows the column comparison in Postgres
+ def positive_id?(value)
+ value&.positive? && value <= MAX_ID
+ end
+
def non_negative_integer!(name)
value = Integer(params[name], exception: false)
if !value || value.negative? || value > MAX_RETENTION_DAYS
@@ -293,6 +374,15 @@ module DiscourseAi
value
end
+ def since_id_param
+ value = Integer(params[:since_id], exception: false)
+ if !value || value.negative? || value > MAX_ID
+ raise Discourse::InvalidParameters.new(:since_id)
+ end
+
+ value
+ end
+
def retention_metadata
total_bytes =
DB.query_single("SELECT pg_total_relation_size('ai_api_audit_logs')").first.to_i
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
index b9c64861122..b217f7484f9 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-log-row.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-log-row.gjs
@@ -1,10 +1,12 @@
import Component from "@glimmer/component";
import { fn } from "@ember/helper";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
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 dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import I18n, { i18n } from "discourse-i18n";
@@ -46,6 +48,10 @@ export default class AiLogRow extends Component {
return this.status === "successful" ? "--success" : "--failed";
}
+ get statusIcon() {
+ return this.status === "successful" ? "circle-check" : "circle-xmark";
+ }
+
get featureName() {
return this.args.log.feature_name || "—";
}
@@ -121,21 +127,28 @@ export default class AiLogRow extends Component {
<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>
+ <DTooltip @content={{this.statusLabel}}>
+ <:trigger>
+ {{dIcon
+ this.statusIcon
+ class=(dConcatClass "ai-logs__status-icon" this.statusClass)
+ aria-label=this.statusLabel
+ }}
+ </:trigger>
+ </DTooltip>
+
{{#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>
+ <DTooltip @content={{i18n "discourse_ai.logs.retried"}}>
+ <:trigger>
+ <span
+ class="ai-logs__flag"
+ role="img"
+ aria-label={{i18n "discourse_ai.logs.retried"}}
+ >
+ {{dIcon "arrows-rotate"}}
+ </span>
+ </:trigger>
+ </DTooltip>
{{/if}}
</div>
</td>
@@ -194,11 +207,11 @@ export default class AiLogRow extends Component {
{{/unless}}
</div>
</td>
- <td class="d-table__cell ai-logs__col-actions --controls">
+ <td class="d-table__cell ai-logs__col-actions">
<DButton
- class="btn-flat"
- @icon="ellipsis"
+ class="btn-default btn-small"
@action={{fn @onOpen @log.id}}
+ @icon="far-file-lines"
@title="discourse_ai.logs.view_details"
@ariaLabel="discourse_ai.logs.view_details"
/>
diff --git a/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss b/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss
index e64bf67f7eb..7ae6084b53c 100644
--- a/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss
+++ b/plugins/discourse-ai/assets/stylesheets/admin/ai-logs.scss
@@ -3,128 +3,77 @@
.ai-logs {
padding: var(--space-4);
- > .d-filter-controls {
- margin-bottom: var(--space-4);
- }
-
- &__filters-title {
- margin-block: var(--space-4) var(--space-2);
- font-size: var(--font-up-1);
+ &__table-wrap {
+ position: relative;
}
- .d-filter-controls__dropdowns {
- grid-template-columns: repeat(auto-fit, minmax(min(12rem, 100%), 1fr));
- }
+ &__filters {
+ margin-bottom: var(--space-4);
- .d-filter-controls__additional-filters {
- display: grid;
- grid-template-columns: minmax(0, 1fr);
- align-items: start;
+ // the drawer's contents are hidden while collapsed, so tint the toggle to
+ // signal that filters are still narrowing the list
+ &.ai-logs__filters--drawer-active
+ .d-filter-controls:not(:has(.d-filter-controls__dropdowns))
+ .d-filter-controls__toggle-filters {
+ --d-button-default-icon-color: var(--tertiary);
+ --d-button-default-icon-color--hover: var(--tertiary-hover);
+ }
- @include viewport.from(md) {
- grid-template-columns: minmax(0, 18rem) minmax(0, 1fr);
+ // the row mixes selects with switches, so it sizes to its contents rather
+ // than forcing every filter into an equal column
+ .d-filter-controls__dropdowns {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
}
- }
- &__date-range-filter,
- &__feature-filter,
- &__user-filter {
- min-width: 0;
- margin: 0;
- padding: 0;
- border: 0;
+ .d-filter-controls__dropdown,
+ .ai-logs__feature-filter {
+ flex: 1 1 12rem;
+ }
}
- &__date-range-filter {
+ &__periods {
display: flex;
- grid-column: 1 / -1;
flex-wrap: wrap;
- align-items: end;
+ align-items: center;
gap: var(--space-2);
- legend {
- flex-basis: 100%;
+ > button:last-of-type {
+ margin-right: auto;
}
}
- &__feature-filter,
- &__user-filter {
- display: flex;
- flex-direction: column;
- gap: var(--space-1);
-
- // a rendered legend sits outside flex layout, so gap does not apply to it
- legend {
- margin-bottom: var(--space-1);
- }
-
- .select-kit {
- width: 100%;
- }
- }
-
- &__id-filter {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr)) auto;
- align-items: end;
- gap: var(--space-2);
- margin: 0;
- }
-
- &__id-type,
- &__id-value {
- display: flex;
- flex-direction: column;
- gap: var(--space-1);
- min-width: 0;
- margin: 0;
-
- select,
- input {
- width: 100%;
- min-height: 2.375rem;
- margin: 0;
- }
+ // select-kit bolds its header; the plain selects beside it do not
+ &__feature-filter.select-kit .select-kit-header {
+ font-weight: normal;
}
+ // the switches read as one control, so they stay together and keep their
+ // own width instead of stretching with the selects
&__toggles {
display: flex;
- grid-column: 1 / -1;
+ flex: none;
flex-wrap: wrap;
+ align-items: center;
gap: var(--space-3);
}
- @include viewport.until(sm) {
- &__date-range-filter .d-date-time-input-range {
- flex-basis: 100%;
- }
-
- &__id-filter {
- grid-template-columns: minmax(0, 1fr);
- }
-
- &__find {
- justify-self: start;
- }
- }
-
- &__table-wrapper {
- border-block: 1px solid var(--content-border-color);
+ &__date-range {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2);
}
- &__table {
- width: 100%;
- table-layout: fixed;
-
- th,
- td {
- vertical-align: middle;
- }
+ .d-date-time-input-range {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
- th {
- color: var(--primary-high);
- font-size: var(--font-down-1);
- font-weight: 600;
+ .from,
+ .to {
+ margin: 0;
}
}
@@ -142,30 +91,16 @@
}
}
- &__col-time {
- width: 6rem;
- }
-
- td.ai-logs__col-time {
+ .ai-logs__col-time {
color: var(--primary-high);
white-space: nowrap;
}
&__col-outcome {
- width: 2rem;
text-align: center;
}
- &__col-user {
- width: 7rem;
- }
-
- &__col-request {
- width: 15rem;
- }
-
&__col-duration {
- width: 10rem;
text-align: end;
font-variant-numeric: tabular-nums;
}
@@ -198,10 +133,6 @@
&__col-actions {
width: 3rem;
text-align: end;
-
- .btn-flat {
- color: var(--primary-high);
- }
}
&__model,
@@ -215,24 +146,20 @@
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;
+ @include viewport.from(md) {
+ justify-content: center;
+ }
+ }
+ &__status-icon {
&.--success {
- background: var(--success);
+ color: var(--success);
}
&.--failed {
- background: var(--danger);
+ color: var(--danger);
}
}
@@ -284,44 +211,20 @@
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: 9.5rem;
- }
-
- &__model {
- display: none;
- }
- }
-
- @include viewport.until(lg) {
- &__table {
+ .d-table {
display: block;
margin-bottom: 0;
table-layout: auto;
- thead,
- tbody {
+ .d-table__header,
+ .d-table__body {
display: block;
}
- thead {
+ .d-table__header {
position: absolute;
width: 1px;
height: 1px;
@@ -342,43 +245,52 @@
align-items: center;
padding-block: var(--space-1);
- > .d-table__cell {
+ .d-table__cell {
width: auto;
padding: var(--space-1) var(--space-2);
border-top: 0;
}
- > .ai-logs__col-time {
+ .ai-logs__col-time {
grid-area: time;
}
- > .ai-logs__col-outcome {
+ .ai-logs__col-outcome {
grid-area: outcome;
}
- > .ai-logs__col-request {
+ .ai-logs__col-request {
grid-area: request;
}
- > .ai-logs__col-user {
+ .ai-logs__col-user {
grid-area: user;
min-width: 0;
+ display: flex;
}
- > .ai-logs__col-duration {
+ .ai-logs__col-duration {
grid-area: duration;
text-align: end;
}
- > .ai-logs__col-actions {
+ .ai-logs__col-actions {
position: static;
grid-area: actions;
}
+
+ .ai-logs__col-context {
+ grid-column: 1 / -1;
+ }
}
&__status-cell {
justify-content: start;
}
+
+ &__model {
+ display: none;
+ }
}
}
@@ -443,7 +355,7 @@
}
&__error {
- padding: var(--space-6);
+ margin: var(--space-6);
text-align: center;
}
}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 431f2b7e907..78df533321f 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -674,9 +674,7 @@ en:
refresh: "Refresh logs"
retry: "Try again"
apply: "Apply"
- find: "Find"
clear_filters: "Clear all filters"
- all_periods: "All time periods"
all_outcomes: "All outcomes"
all_models: "All models"
all_features: "All features"
@@ -686,12 +684,8 @@ en:
has_retries: "Has retries"
retried: "Retried"
unattributed: "Unattributed"
+ search_placeholder: "Search by @username or ID (e.g. @user1 topic:123 log:45)"
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"
@@ -717,15 +711,12 @@ en:
cost: "Cost"
actions: "Actions"
table_caption: "AI requests sent to language models and their outcomes"
- view_details: "View details"
+ view_details: "Details"
no_results: "No AI logs match these filters."
no_logs: "No retained AI logs were found."
- filters:
- title: "Filters"
- period: "Time period"
- date_range: "Date range"
- id_type: "ID type"
- id_value: "ID value"
+ new_logs_count:
+ one: "See %{count} new log"
+ other: "See %{count} new logs"
periods:
hour: "Last hour"
day: "Last 24 hours"
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index 5e87bfb10ea..c49cbebd01b 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -154,6 +154,7 @@ 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"
+ get "/ai-logs/new", to: "discourse_ai/admin/ai_logs#new_logs"
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"
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
index e0b8c81c7db..2c470844e02 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_logs_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_logs_controller_spec.rb
@@ -17,6 +17,8 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
case endpoint
when :index
get index_path, headers:
+ when :new_logs
+ get "/admin/plugins/discourse-ai/ai-logs/new.json", params: { since_id: 0 }, headers:
when :show
get "/admin/plugins/discourse-ai/ai-logs/#{log.id}.json", headers:
when :retention
@@ -49,7 +51,7 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
end
it "denies anonymous users from every endpoint", :anonymous do
- %i[index show retention].each do |endpoint|
+ %i[index show retention new_logs].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}"
@@ -61,7 +63,7 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
[user, moderator].each do |non_admin|
sign_in(non_admin)
- %i[index show retention].each do |endpoint|
+ %i[index show retention new_logs].each do |endpoint|
request_ai_logs_endpoint(endpoint, log)
expect(response.status).to eq(404),
"expected #{endpoint} to be hidden from #{non_admin.username}"
@@ -73,7 +75,7 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
api_key = Fabricate(:api_key, user:)
headers = { "Api-Key" => api_key.key, "Api-Username" => user.username }
- %i[index show retention].each do |endpoint|
+ %i[index show retention new_logs].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"
@@ -83,7 +85,7 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
it "keeps every endpoint unavailable when the plugin is disabled" do
SiteSetting.discourse_ai_enabled = false
- %i[index show retention].each do |endpoint|
+ %i[index show retention new_logs].each do |endpoint|
request_ai_logs_endpoint(endpoint, log)
expect(response.status).to eq(404), "expected #{endpoint} to require the enabled plugin"
end
@@ -247,6 +249,65 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([matching_log.id])
end
+ it "searches logs by username and typed ID prefixes" do
+ search_user = Fabricate(:user, username: "agent99")
+ unmatched_user = Fabricate(:user, username: "someoneelse")
+ topic_log =
+ Fabricate(:ai_api_audit_log, user: search_user, topic_id: 424_242, post_id: 777_777)
+ unmatched_log = Fabricate(:ai_api_audit_log, user: unmatched_user)
+
+ get index_path, params: { search: "agent99" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "@agent99" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "@agent99 topic:424242" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "@" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to contain_exactly(
+ topic_log.id,
+ unmatched_log.id,
+ )
+
+ get index_path, params: { search: "424242" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "topic:424242" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "post:777777" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "log:#{topic_log.id}" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "AGENT99" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "agent99 topic:424242" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "agent99 post:777777" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "agent99 log:#{topic_log.id}" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "agent99 topic:1" }
+ expect(response.parsed_body["logs"]).to eq([])
+
+ get index_path, params: { search: "424242 agent99" }
+ expect(response.parsed_body["logs"].map { |log| log["id"] }).to eq([topic_log.id])
+
+ get index_path, params: { search: "424242 someoneelse" }
+ expect(response.parsed_body["logs"]).to eq([])
+
+ get index_path, params: { search: "agent99 someoneelse" }
+ expect(response.parsed_body["logs"]).to eq([])
+ end
+
it "filters by seeded models and exposes them in filter metadata" do
seeded_model = Fabricate(:seeded_model, id: -1)
matching_log = Fabricate(:ai_api_audit_log, llm_model: seeded_model)
@@ -351,6 +412,136 @@ RSpec.describe DiscourseAi::Admin::AiLogsController do
get index_path, params: { start_date: "2024-01-01", end_date: "2026-01-02" }
expect(response.status).to eq(400)
+
+ get index_path, params: { search: ("a" * 201) }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { search: "99999999999999999999" }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { id: 2**63 }
+ expect(response.status).to eq(400)
+
+ get index_path, params: { unattributed: true, search: "@#{admin.username}" }
+ expect(response.status).to eq(400)
+ end
+
+ it "accepts ID searches beyond the range of a 32-bit integer" do
+ get index_path, params: { search: "log:#{2**31}" }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["logs"]).to eq([])
+
+ get index_path, params: { search: "log:#{2**63}" }
+ expect(response.status).to eq(400)
+ end
+
+ it "exposes the table's high-water mark so pollers can baseline an empty list" do
+ newest = Fabricate(:ai_api_audit_log, llm_model:)
+
+ get index_path, params: { search: "@#{user.username}" }
+
+ expect(response.parsed_body["logs"]).to eq([])
+ expect(response.parsed_body.dig("meta", "max_id")).to eq(newest.id)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-ai/ai-logs/new.json" do
+ fab!(:older_log) { Fabricate(:ai_api_audit_log, llm_model:) }
+
+ let(:new_logs_path) { "/admin/plugins/discourse-ai/ai-logs/new.json" }
+
+ it "counts logs created after since_id" do
+ Fabricate(:ai_api_audit_log, llm_model:, response_status: 500)
+
+ get new_logs_path, params: { since_id: older_log.id }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["new_logs_count"]).to eq(1)
+ end
+
+ it "returns zero when nothing is newer" do
+ get new_logs_path, params: { since_id: older_log.id }
+ expect(response.parsed_body["new_logs_count"]).to eq(0)
+ end
+
+ it "counts every retained log when since_id is zero" do
+ Fabricate(:ai_api_audit_log, llm_model:)
+ get new_logs_path, params: { since_id: 0 }
+ expect(response.parsed_body["new_logs_count"]).to eq(2)
+ end
+
+ it "respects the active outcome, model, feature, and user filters" do
+ other_model = Fabricate(:llm_model)
+ failed = Fabricate(:ai_api_audit_log, llm_model:, response_status: 500)
+ Fabricate(
+ :ai_api_audit_log,
+ llm_model: other_model,
+ feature_name: "spam",
+ response_status: 500,
+ user: admin,
+ )
+ Fabricate(:ai_api_audit_log, llm_model:, feature_name: "spam", response_status: 200)
+
+ get new_logs_path, params: { since_id: older_log.id, outcome: "failed" }
+ expect(response.parsed_body["new_logs_count"]).to eq(2)
+
+ get new_logs_path,
+ params: {
+ since_id: older_log.id,
+ outcome: "failed",
+ llm_id: other_model.id,
+ feature: "spam",
+ }
+ expect(response.parsed_body["new_logs_count"]).to eq(1)
+
+ get new_logs_path,
+ params: {
+ since_id: older_log.id,
+ outcome: "failed",
+ llm_id: other_model.id,
+ feature: "spam",
+ user_id: admin.id,
+ }
+ expect(response.parsed_body["new_logs_count"]).to eq(1)
+ end
+
+ it "respects the active search filter" do
+ user_log = Fabricate(:ai_api_audit_log, llm_model:, user: admin, feature_name: "summarize")
+ Fabricate(:ai_api_audit_log, llm_model:, feature_name: "else", user: admin)
+
+ get new_logs_path, params: { since_id: older_log.id, search: "@#{admin.username}" }
+ expect(response.parsed_body["new_logs_count"]).to eq(2)
+
+ get new_logs_path,
+ params: {
+ since_id: older_log.id,
+ search: "@#{admin.username} log:#{user_log.id}",
+ }
+ expect(response.parsed_body["new_logs_count"]).to eq(1)
+ end
+
+ it "rejects missing, negative, and non-numeric since_id values" do
+ get new_logs_path
+ expect(response.status).to eq(400)
+
+ get new_logs_path, params: { since_id: -1 }
+ expect(response.status).to eq(400)
+
+ get new_logs_path, params: { since_id: "abc" }
+ expect(response.status).to eq(400)
+
+ get new_logs_path, params: { since_id: 2**63 }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects the unattributed filter alongside a username search" do
+ get new_logs_path,
+ params: {
+ since_id: older_log.id,
+ unattributed: true,
+ search: "@#{admin.username}",
+ }
+ expect(response.status).to eq(400)
end
end
diff --git a/plugins/discourse-ai/spec/system/ai_logs_spec.rb b/plugins/discourse-ai/spec/system/ai_logs_spec.rb
index 6347020fcfc..eb37e79b7d2 100644
--- a/plugins/discourse-ai/spec/system/ai_logs_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_logs_spec.rb
@@ -3,6 +3,7 @@
RSpec.describe "AI logs admin page" do
fab!(:admin)
fab!(:llm_model)
+ fab!(:other_llm_model) { Fabricate(:llm_model, display_name: "Another model") }
fab!(:log) do
Fabricate(
:ai_api_audit_log,
@@ -76,21 +77,33 @@ RSpec.describe "AI logs admin page" do
ai_logs_page.select_feature("other-feature")
expect(ai_logs_page).to have_no_log(log)
- day_period = I18n.t("js.discourse_ai.logs.periods.day")
- ai_logs_page.select_period(day_period)
- expect(ai_logs_page).to have_filter_value(:period, "day")
+ ai_logs_page.select_period(I18n.t("js.discourse_ai.logs.periods.day"))
+ expect(page).to have_current_path(/period=day/, url: true)
- 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
+ # an ID search narrows within the active filters instead of bypassing them
+ ai_logs_page.search(log.id)
expect(ai_logs_page).to have_no_log(log)
- expect(ai_logs_page).to have_filter_value(:period, "day")
+ expect(page).to have_current_path(/period=day/, url: true)
ai_logs_page.select_feature(log.feature_name)
expect(ai_logs_page).to have_log(log)
end
+ it "drops the model filter when a single model leaves nothing to choose" do
+ other_llm_model.destroy!
+ ai_logs_page.visit
+
+ expect(ai_logs_page).to have_log(log)
+ expect(page).to have_css(".d-filter-controls__dropdown--outcome")
+ expect(page).to have_no_css(".d-filter-controls__dropdown--model")
+
+ # a model carried in on the URL still needs somewhere to be cleared from
+ ai_logs_page.visit("model=#{llm_model.id}")
+
+ expect(ai_logs_page).to have_log(log)
+ expect(ai_logs_page.filter_value(:model)).to eq(llm_model.id.to_s)
+ end
+
it "filters by a feature outside the initial page of logs" do
Fabricate.times(50, :ai_api_audit_log, feature_name: "recent-feature")
ai_logs_page.visit
@@ -100,17 +113,126 @@ RSpec.describe "AI logs admin page" do
expect(ai_logs_page).to have_log(log)
end
- it "keeps focus in the ID input while typing" do
+ it "searches logs by username and typed ID prefixes" do
+ topic_log = Fabricate(:ai_api_audit_log, topic_id: 424_242)
+ user_log = Fabricate(:ai_api_audit_log, user: admin)
+
+ ai_logs_page.visit
+
+ ai_logs_page.search(log.id)
+ expect(ai_logs_page).to have_log(log)
+ expect(ai_logs_page).to have_no_log(topic_log)
+
+ ai_logs_page.search("topic:#{topic_log.topic_id}")
+ expect(ai_logs_page).to have_log(topic_log)
+ expect(ai_logs_page).to have_no_log(log)
+
+ ai_logs_page.search(admin.username)
+ expect(ai_logs_page).to have_log(user_log)
+ expect(ai_logs_page).to have_no_log(log)
+
+ combined_log = Fabricate(:ai_api_audit_log, user: admin, topic_id: 555_555)
+ ai_logs_page.search("#{admin.username} topic:555555")
+ expect(ai_logs_page).to have_log(combined_log)
+ expect(ai_logs_page).to have_no_log(user_log)
+ expect(ai_logs_page).to have_no_log(topic_log)
+ expect(ai_logs_page).to have_no_log(log)
+ expect(page).to have_current_path(/search=.*%20topic%3A555555/, url: true)
+
+ # numeric token combined with a username token
+ ai_logs_page.search("#{admin.username} 555555")
+ expect(ai_logs_page).to have_log(combined_log)
+ expect(ai_logs_page).to have_no_log(user_log)
+ expect(ai_logs_page).to have_no_log(topic_log)
+ expect(ai_logs_page).to have_no_log(log)
+ end
+
+ it "suggests and inserts a user picked from an @-prefixed search" do
+ user_log = Fabricate(:ai_api_audit_log, user: admin)
+
+ ai_logs_page.visit
+
+ search_input = find("input[placeholder='#{I18n.t("js.discourse_ai.logs.search_placeholder")}']")
+ search_input.click
+ "@#{admin.username}".each_char { |char| search_input.send_keys(char) }
+
+ within(".autocomplete.ac-user") { find(".username", text: admin.username).click }
+
+ expect(page).to have_current_path(/search=%40#{Regexp.escape(admin.username)}/, url: true)
+ expect(page.evaluate_script("document.activeElement.value")).to eq("@#{admin.username} ")
+ expect(ai_logs_page).to have_log(user_log)
+ expect(ai_logs_page).to have_no_log(log)
+ end
+
+ it "closes the user picker once a space ends the @username" do
+ ai_logs_page.visit
+
+ search_input = find("input[placeholder='#{I18n.t("js.discourse_ai.logs.search_placeholder")}']")
+ search_input.click
+ "@#{admin.username}".each_char { |char| search_input.send_keys(char) }
+ expect(page).to have_css(".autocomplete.ac-user .username")
+
+ search_input.send_keys(" ")
+ expect(page).to have_no_css(".autocomplete.ac-user")
+
+ # the mention context is gone, so the next search token must not reopen it
+ search_input.send_keys("topic:")
+ expect(page).to have_no_css(".autocomplete.ac-user")
+ end
+
+ it "keeps focus in the search box while typing and searching live" do
ai_logs_page.visit
- id_input = find("input[placeholder='#{I18n.t("js.discourse_ai.logs.id_placeholder")}']")
- id_input.click
- "123".each_char { |character| id_input.send_keys(character) }
+ search_input = find("input[placeholder='#{I18n.t("js.discourse_ai.logs.search_placeholder")}']")
+ search_input.click
+ "123".each_char { |character| search_input.send_keys(character) }
+
+ expect(search_input.value).to eq("123")
+ expect(page.evaluate_script("document.activeElement.placeholder")).to eq(
+ I18n.t("js.discourse_ai.logs.search_placeholder"),
+ )
- expect(id_input.value).to eq("123")
+ # the debounced search fires and the URL updates; focus must stay in the box
+ expect(page).to have_current_path(/search=123/, url: true)
expect(page.evaluate_script("document.activeElement.placeholder")).to eq(
- I18n.t("js.discourse_ai.logs.id_placeholder"),
+ I18n.t("js.discourse_ai.logs.search_placeholder"),
)
+ expect(page.evaluate_script("document.activeElement.value")).to eq("123")
+ end
+
+ it "remembers whether the filter drawer is collapsed across reloads" do
+ ai_logs_page.visit
+ expect(ai_logs_page).to have_log(log)
+ expect(ai_logs_page).to have_expanded_filter_dropdowns
+
+ find(".d-filter-controls__toggle-filters").click
+ expect(page).to have_no_css(".ai-logs .d-filter-controls__dropdown")
+
+ page.refresh
+ expect(page).to have_css(".ai-logs .d-filter-controls__toggle-filters")
+ expect(page).to have_no_css(".ai-logs .d-filter-controls__dropdown")
+
+ find(".d-filter-controls__toggle-filters").click
+ expect(page).to have_css(".ai-logs .d-filter-controls__dropdown", count: 2)
+ end
+
+ it "flags active filters hiding behind a collapsed drawer" do
+ ai_logs_page.visit
+ unless ai_logs_page.has_expanded_filter_dropdowns?
+ find(".d-filter-controls__toggle-filters").click
+ end
+
+ ai_logs_page.select_model(llm_model.display_name)
+ expect(page).to have_css(".ai-logs__filters--drawer-active")
+ expect(ai_logs_page).to have_no_tinted_filter_toggle
+
+ find(".d-filter-controls__toggle-filters").click
+ expect(page).to have_no_css(".ai-logs .d-filter-controls__dropdown")
+ expect(ai_logs_page).to have_tinted_filter_toggle
+
+ find(".d-filter-controls__toggle-filters").click
+ expect(page).to have_css(".ai-logs .d-filter-controls__dropdown", count: 2)
+ expect(ai_logs_page).to have_no_tinted_filter_toggle
end
it "restores model and period filters from the URL" do
@@ -160,24 +282,26 @@ RSpec.describe "AI logs admin page" do
ai_logs_page.clear_filters
expect(page).to have_current_path(%r{/ai-logs$}, url: true)
- expect(page).to have_css(".d-filter-controls__dropdown--period:focus")
+ expect(page).to have_css(".d-filter-controls__input:focus")
expect(ai_logs_page).to have_log(log)
ai_logs_page.select_period(I18n.t("js.discourse_ai.logs.periods.day"))
+ ai_logs_page.select_model(llm_model.display_name)
+ ai_logs_page.search(log.id)
ai_logs_page.clear_filters
expect(page).to have_current_path(%r{/ai-logs$}, url: true)
+ expect(page).to have_css(".d-filter-controls__input:focus")
+ expect(ai_logs_page).to have_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)
- expect(page).to have_css(".ai-logs__feature-filter .combo-box")
- expect(page).to have_no_css(".d-filter-controls__toggle-filters")
+ expect(page).to have_css(".d-filter-controls__input")
+ expect(page).to have_css(".d-filter-controls__toggle-filters")
+ expect(page).to have_css(".ai-logs__feature-filter.combo-box")
expect(page).to have_no_css(".d-filter-controls__reset")
- expect(page).to have_css(
- ".ai-logs__filters-title",
- text: I18n.t("js.discourse_ai.logs.filters.title"),
- )
+ expect(page).to have_css(".ai-logs__filters")
expect(ai_logs_page).to have_expanded_filter_dropdowns
expect(page).to have_no_css(".ai-logs__retention")
expect(page).to have_button(I18n.t("js.discourse_ai.logs.retention.configure"))
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
index b2bf5634705..5a84476c222 100644
--- a/plugins/discourse-ai/spec/system/page_objects/pages/ai_logs.rb
+++ b/plugins/discourse-ai/spec/system/page_objects/pages/ai_logs.rb
@@ -9,6 +9,11 @@ module PageObjects
self
end
+ def select_period(label)
+ find(".ai-logs__periods .btn", text: label).click
+ self
+ end
+
def select_outcome(label)
select_filter(:outcome, label)
end
@@ -28,25 +33,49 @@ module PageObjects
feature_filter.value
end
- def select_period(label)
- select_filter(:period, label)
- end
-
def clear_filters
find(".d-filter-controls__reset").click
self
end
+ def search(value)
+ find("input[placeholder='#{I18n.t("js.discourse_ai.logs.search_placeholder")}']").fill_in(
+ with: value,
+ )
+ self
+ end
+
def filter_value(key)
find(".d-filter-controls__dropdown--#{key}").value
end
- def has_filter_value?(key, value)
- find(".d-filter-controls__dropdown--#{key}").value == value
+ def has_tinted_filter_toggle?
+ page.evaluate_script(<<~JS)
+ (() => {
+ const icon = document.querySelector(
+ ".ai-logs .d-filter-controls__toggle-filters .d-icon"
+ );
+ const probe = (color) => {
+ const el = document.createElement("span");
+ el.style.color = `var(${color})`;
+ document.body.appendChild(el);
+ const result = getComputedStyle(el).color;
+ el.remove();
+ return result;
+ };
+ return [probe("--tertiary"), probe("--tertiary-hover")].includes(
+ getComputedStyle(icon).color
+ );
+ })()
+ JS
+ end
+
+ def has_no_tinted_filter_toggle?
+ !has_tinted_filter_toggle?
end
def has_expanded_filter_dropdowns?
- page.has_css?(".d-filter-controls__dropdown", count: 3)
+ page.has_css?(".d-filter-controls__dropdown", count: 2)
end
def open_log(log)
@@ -81,7 +110,7 @@ module PageObjects
private
def feature_filter
- PageObjects::Components::SelectKit.new(".ai-logs__feature-filter .combo-box")
+ PageObjects::Components::SelectKit.new(".ai-logs__feature-filter")
end
def select_filter(key, label)
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
index 5bbc3e61c39..e4f06226395 100644
--- 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
@@ -21,8 +21,12 @@ module("Integration | Component | AiLogRow", function (hooks) {
);
assert
- .dom('.ai-logs__status-dot[title="Successful"]')
- .hasAttribute("aria-label", "Successful", "success dot is labelled");
+ .dom(".ai-logs__status-icon.d-icon-circle-check")
+ .hasAttribute(
+ "aria-label",
+ "Successful",
+ "success uses a labelled check icon"
+ );
});
test("renders operational metadata and opens details", async function (assert) {
@@ -54,12 +58,19 @@ module("Integration | Component | AiLogRow", function (hooks) {
);
assert
- .dom('.ai-logs__status-dot[title="Failed"]')
- .hasAttribute("aria-label", "Failed", "failure dot is labelled");
+ .dom(".ai-logs__status-icon.d-icon-circle-xmark")
+ .hasAttribute(
+ "aria-label",
+ "Failed",
+ "failure uses a labelled xmark icon"
+ );
assert.dom(".ai-logs__flag").exists({ count: 1 }, "retry uses an icon");
assert
- .dom('.ai-logs__flag[title="Retried"]')
+ .dom('.ai-logs__flag[aria-label="Retried"]')
.exists("retry state is available to assistive technology");
+ assert
+ .dom(".ai-logs__row .fk-d-tooltip__trigger")
+ .exists({ count: 2 }, "status and retry icons surface tooltips");
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");
@@ -81,11 +92,18 @@ module("Integration | Component | AiLogRow", function (hooks) {
"assistive text retains exact token counts"
);
assert
- .dom('.ai-logs__row .btn[aria-label="View details"]')
- .exists("details action is labelled");
+ .dom(".ai-logs__row .btn .d-icon-far-file-lines")
+ .exists("details is an icon-only button");
+ assert
+ .dom(".ai-logs__row .btn")
+ .hasAttribute(
+ "aria-label",
+ "Details",
+ "details icon has an accessible name"
+ );
assert
- .dom(".ai-logs__row .d-icon-ellipsis")
- .exists("details use a compact ellipsis icon");
+ .dom(".ai-logs__row .btn")
+ .hasAttribute("title", "Details", "details icon has a tooltip");
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-logs-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-logs-test.gjs
new file mode 100644
index 00000000000..4f3d90dbd46
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-logs-test.gjs
@@ -0,0 +1,298 @@
+import Service from "@ember/service";
+import { clearRender, click, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import AiLogs from "discourse/plugins/discourse-ai/discourse/components/ai-logs";
+import {
+ NEW_LOGS_POLL_BACKOFF_STEP_MS,
+ NEW_LOGS_POLL_INTERVAL_MS,
+} from "discourse/plugins/discourse-ai/discourse/lib/ai-logs-poll-interval";
+
+const LOG = {
+ id: 1,
+ created_at: "2026-01-05T10:00:00Z",
+ response_status: 200,
+ duration_msecs: 1_400,
+ feature_name: "summarize",
+ model_name: "Test model",
+ username: "user1",
+ avatar_template: "/letter_avatar_proxy/v4/letter/u/13edae/{size}.png",
+ request_tokens: 120,
+ response_tokens: 30,
+ has_retries: false,
+};
+
+class RouterStub extends Service {
+ currentRouteName = "adminPlugins.show.discourseAiLogs";
+
+ async transitionTo() {}
+ on() {}
+ off() {}
+}
+
+let pendingNewLogs;
+let timerDelays;
+let setTimeoutStub;
+
+module("Integration | Component | ai-logs new-log banner", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.afterEach(function () {
+ setTimeoutStub?.restore();
+ setTimeoutStub = undefined;
+ });
+
+ hooks.beforeEach(function () {
+ pendingNewLogs = 0;
+
+ this.owner.unregister("service:router");
+ this.owner.register("service:router", RouterStub);
+ this.owner.unregister("service:modal");
+ this.owner.register(
+ "service:modal",
+ class extends Service {
+ show() {}
+ close() {}
+ }
+ );
+ this.owner.unregister("service:toasts");
+ this.owner.register(
+ "service:toasts",
+ class extends Service {
+ success() {}
+ }
+ );
+
+ pretender.get("/admin/plugins/discourse-ai/ai-logs/new.json", () =>
+ response({ new_logs_count: pendingNewLogs })
+ );
+ pretender.get("/admin/plugins/discourse-ai/ai-logs.json", () =>
+ response({ logs: [LOG], meta: { has_more: false } })
+ );
+
+ this.set("model", {
+ logs: [LOG],
+ meta: { has_more: false },
+ models: [],
+ features: [],
+ });
+ this.set("queryParams", {});
+ });
+
+ test("surfaces new logs in a banner and loads them on click", async function (assert) {
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ await render(
+ <template>
+ <AiLogs @model={{this.model}} @queryParams={{this.queryParams}} />
+ </template>
+ );
+
+ assert.dom(".ai-logs .show-more").doesNotExist("no banner before polling");
+
+ pendingNewLogs = 2;
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+
+ assert
+ .dom(".ai-logs .show-more a.alert-info.clickable")
+ .hasText("See 2 new logs", "banner offers to load incoming logs");
+
+ await click(".ai-logs .show-more a");
+
+ assert
+ .dom(".ai-logs .show-more")
+ .doesNotExist("banner clears once the list reloads");
+ assert
+ .dom(".ai-logs__row")
+ .exists({ count: 1 }, "the reloaded list is rendered");
+ });
+
+ test("singularises the count and hides when nothing new remains", async function (assert) {
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ await render(
+ <template>
+ <AiLogs @model={{this.model}} @queryParams={{this.queryParams}} />
+ </template>
+ );
+
+ pendingNewLogs = 1;
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+ assert
+ .dom(".ai-logs .show-more a")
+ .hasText("See 1 new log", "the count is singularised");
+
+ pendingNewLogs = 0;
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+ assert
+ .dom(".ai-logs .show-more")
+ .doesNotExist("banner hides once the poll reports nothing new");
+ });
+
+ test("backs off after quiet polls and snaps back when logs arrive", async function (assert) {
+ const originalSetTimeout = window.setTimeout.bind(window);
+ timerDelays = [];
+ setTimeoutStub = sinon.stub(window, "setTimeout").callsFake((fn, delay) => {
+ timerDelays.push(delay);
+ return originalSetTimeout(fn, delay);
+ });
+
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ await render(
+ <template>
+ <AiLogs @model={{this.model}} @queryParams={{this.queryParams}} />
+ </template>
+ );
+
+ timerDelays.length = 0;
+
+ pendingNewLogs = 0;
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+ // quiet poll backs off one step
+ assert.strictEqual(
+ timerDelays.at(-1),
+ NEW_LOGS_POLL_INTERVAL_MS + NEW_LOGS_POLL_BACKOFF_STEP_MS,
+ "first quiet poll lengthens the interval"
+ );
+
+ pendingNewLogs = 0;
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+ assert.strictEqual(
+ timerDelays.at(-1),
+ NEW_LOGS_POLL_INTERVAL_MS + 2 * NEW_LOGS_POLL_BACKOFF_STEP_MS,
+ "a second quiet poll backs off further"
+ );
+
+ pendingNewLogs = 2;
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+ assert.strictEqual(
+ timerDelays.at(-1),
+ NEW_LOGS_POLL_INTERVAL_MS,
+ "finding new logs snaps the interval back to the base"
+ );
+ });
+ test("keeps the active filters on an ID-prefixed search", async function (assert) {
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ let pollQuery;
+ pretender.get("/admin/plugins/discourse-ai/ai-logs/new.json", (request) => {
+ pollQuery = request.queryParams;
+ return response({ new_logs_count: 0 });
+ });
+ this.set("queryParams", {
+ period: "hour",
+ outcome: "failed",
+ search: "topic:424242",
+ });
+
+ await render(
+ <template>
+ <AiLogs @model={{this.model}} @queryParams={{this.queryParams}} />
+ </template>
+ );
+
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+
+ assert.strictEqual(
+ pollQuery.search,
+ "topic:424242",
+ "the prefix is sent as a search term, matching a reload of the same URL"
+ );
+ assert.strictEqual(
+ pollQuery.outcome,
+ "failed",
+ "the outcome filter survives"
+ );
+ assert.true("start_date" in pollQuery, "the period filter survives");
+ assert.false(
+ "topic_id" in pollQuery,
+ "no filter-bypassing ID param is sent"
+ );
+ });
+
+ test("polls against the table high-water mark when the list is empty", async function (assert) {
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ let pollQuery;
+ pretender.get("/admin/plugins/discourse-ai/ai-logs/new.json", (request) => {
+ pollQuery = request.queryParams;
+ return response({ new_logs_count: 0 });
+ });
+ this.set("model", {
+ logs: [],
+ meta: { has_more: false, max_id: 987 },
+ models: [],
+ features: [],
+ });
+
+ await render(
+ <template>
+ <AiLogs @model={{this.model}} @queryParams={{this.queryParams}} />
+ </template>
+ );
+
+ document.dispatchEvent(new Event("visibilitychange"));
+ await settled();
+
+ assert.strictEqual(
+ pollQuery.since_id,
+ "987",
+ "an empty list baselines on the newest existing log, not on zero"
+ );
+ });
+
+ test("a poll firing after teardown does not schedule another", async function (assert) {
+ const originalSetTimeout = window.setTimeout.bind(window);
+ const timers = [];
+ setTimeoutStub = sinon.stub(window, "setTimeout").callsFake((fn, delay) => {
+ timers.push({ fn, delay });
+ return originalSetTimeout(fn, delay);
+ });
+
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ configurable: true,
+ });
+ await render(
+ <template>
+ <AiLogs @model={{this.model}} @queryParams={{this.queryParams}} />
+ </template>
+ );
+
+ const queuedPoll = timers.findLast(
+ (timer) => timer.delay === NEW_LOGS_POLL_INTERVAL_MS
+ );
+ assert.true(Boolean(queuedPoll), "a poll is queued while the page is open");
+
+ await clearRender();
+ timers.length = 0;
+ queuedPoll.fn();
+ await settled();
+
+ assert.deepEqual(
+ timers,
+ [],
+ "the destroyed component leaves no timer behind"
+ );
+ });
+});
diff --git a/plugins/discourse-ai/test/javascripts/unit/lib/ai-logs-poll-interval-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/ai-logs-poll-interval-test.js
new file mode 100644
index 00000000000..44dbadd3337
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/unit/lib/ai-logs-poll-interval-test.js
@@ -0,0 +1,39 @@
+import { module, test } from "qunit";
+import {
+ NEW_LOGS_POLL_BACKOFF_STEP_MS,
+ NEW_LOGS_POLL_INTERVAL_MS,
+ NEW_LOGS_POLL_MAX_INTERVAL_MS,
+ newLogsPollIntervalMs,
+} from "discourse/plugins/discourse-ai/discourse/lib/ai-logs-poll-interval";
+
+module("Unit | Lib | ai-logs-poll-interval", function () {
+ test("starts at the base interval with no quiet polls", function (assert) {
+ assert.strictEqual(newLogsPollIntervalMs(0), NEW_LOGS_POLL_INTERVAL_MS);
+ assert.strictEqual(newLogsPollIntervalMs(-1), NEW_LOGS_POLL_INTERVAL_MS);
+ });
+
+ test("backs off one step per quiet poll", function (assert) {
+ assert.strictEqual(
+ newLogsPollIntervalMs(1),
+ NEW_LOGS_POLL_INTERVAL_MS + NEW_LOGS_POLL_BACKOFF_STEP_MS
+ );
+ assert.strictEqual(
+ newLogsPollIntervalMs(2),
+ NEW_LOGS_POLL_INTERVAL_MS + 2 * NEW_LOGS_POLL_BACKOFF_STEP_MS
+ );
+ });
+
+ test("caps the backoff at the maximum interval", function (assert) {
+ const stepsToMax =
+ (NEW_LOGS_POLL_MAX_INTERVAL_MS - NEW_LOGS_POLL_INTERVAL_MS) /
+ NEW_LOGS_POLL_BACKOFF_STEP_MS;
+ assert.strictEqual(
+ newLogsPollIntervalMs(stepsToMax),
+ NEW_LOGS_POLL_MAX_INTERVAL_MS
+ );
+ assert.strictEqual(
+ newLogsPollIntervalMs(stepsToMax + 5),
+ NEW_LOGS_POLL_MAX_INTERVAL_MS
+ );
+ });
+});