Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Load system health AI checks lazily and finish its DS pass (#3828)

Guillem Arias Faustec0fe37e791ea
diff --git a/app/components/DS/tabs.html.erb b/app/components/DS/tabs.html.erb
index 9c7e26c0e2..78ca02ddda 100644
--- a/app/components/DS/tabs.html.erb
+++ b/app/components/DS/tabs.html.erb
@@ -3,7 +3,6 @@
testid: testid,
DS__tabs_session_key_value: session_key,
DS__tabs_url_param_key_value: url_param_key,
- DS__tabs_navigate_on_change_value: navigate_on_change,
DS__tabs_nav_btn_active_class: active_btn_classes,
DS__tabs_nav_btn_inactive_class: inactive_btn_classes
} do %>
diff --git a/app/components/DS/tabs.rb b/app/components/DS/tabs.rb
index 42c0094fe6..5a0f735bec 100644
--- a/app/components/DS/tabs.rb
+++ b/app/components/DS/tabs.rb
@@ -47,13 +47,12 @@ class DS::Tabs < DesignSystemComponent
}
}
- attr_reader :active_tab, :url_param_key, :session_key, :variant, :testid, :navigate_on_change
+ attr_reader :active_tab, :url_param_key, :session_key, :variant, :testid
- def initialize(active_tab:, url_param_key: nil, session_key: nil, navigate_on_change: false, variant: :default, active_btn_classes: "", inactive_btn_classes: "", testid: nil)
+ def initialize(active_tab:, url_param_key: nil, session_key: nil, variant: :default, active_btn_classes: "", inactive_btn_classes: "", testid: nil)
@active_tab = active_tab
@url_param_key = url_param_key
@session_key = session_key
- @navigate_on_change = navigate_on_change
@variant = variant.to_sym
@active_btn_classes = active_btn_classes
@inactive_btn_classes = inactive_btn_classes
diff --git a/app/components/DS/tabs_controller.js b/app/components/DS/tabs_controller.js
index f6818008e2..1fe66c396b 100644
--- a/app/components/DS/tabs_controller.js
+++ b/app/components/DS/tabs_controller.js
@@ -4,11 +4,7 @@ import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static classes = ["navBtnActive", "navBtnInactive"];
static targets = ["panel", "navBtn"];
- static values = {
- sessionKey: String,
- urlParamKey: String,
- navigateOnChange: Boolean,
- };
+ static values = { sessionKey: String, urlParamKey: String };
show(e) {
const btn = e.target.closest("button");
@@ -41,13 +37,9 @@ export default class extends Controller {
if (this.urlParamKeyValue) {
const url = new URL(window.location.href);
url.searchParams.set(this.urlParamKeyValue, selectedTabId);
-
- if (this.navigateOnChangeValue) {
- window.location.assign(url.toString());
- return;
- }
-
- window.history.replaceState({}, "", url);
+ // Keep Turbo's entry in the state: without it, Turbo ignores the
+ // popstate when Back returns here and the other page stays on screen.
+ window.history.replaceState(window.history.state, "", url);
}
// Update URL with the selected tab
diff --git a/app/controllers/admin/system_health_controller.rb b/app/controllers/admin/system_health_controller.rb
index b442d7f062..fd548ecfec 100644
--- a/app/controllers/admin/system_health_controller.rb
+++ b/app/controllers/admin/system_health_controller.rb
@@ -12,7 +12,7 @@ module Admin
def show
tabs = %w[background_jobs ai]
@active_tab = params[:tab].presence_in(tabs) || "background_jobs"
- if Apns::Client.hosted? && @active_tab == "background_jobs"
+ if Apns::Client.hosted?
@push_notification_test = PushNotificationTest.new(Current.user)
@push_disabled_reason = @push_notification_test.disabled_reason
@latest_push_test = @push_notification_test.latest
@@ -20,12 +20,15 @@ module Admin
end
SidekiqHealth.expire_cache!
@health = SidekiqHealth.new
- ai_tab = params[:tab] == "ai"
- @ai_health = AiHealth.new(
- run_probes: ai_tab,
- force_probes: ai_tab && params[:refresh_ai_health] == "1"
- )
- @worker_ai_health_results = WorkerAiHealth.recent if ai_tab
+ end
+
+ # Each live probe can take up to AiHealth::Probe.timeout, so the page
+ # loads this into its AI tab through a lazy frame instead of waiting on
+ # the probes before it renders.
+ def ai_status
+ @ai_health = AiHealth.new(force_probes: params[:refresh_ai_health] == "1")
+ @worker_ai_health_results = WorkerAiHealth.recent
+ render layout: false
end
# Queues an asynchronous worker-side verification (see
@@ -34,7 +37,7 @@ module Admin
# finishes, typically within a few seconds.
def verify_worker_ai
WorkerAiHealth.request_check!
- redirect_to admin_system_health_path(tab: "ai"), notice: t(".queued")
+ redirect_to admin_system_health_path(tab: "ai", locale: locale_from_param), notice: t(".queued")
end
def send_test_push
diff --git a/app/controllers/concerns/localize.rb b/app/controllers/concerns/localize.rb
index 7499c726b0..54a43e624e 100644
--- a/app/controllers/concerns/localize.rb
+++ b/app/controllers/concerns/localize.rb
@@ -4,6 +4,7 @@ module Localize
included do
around_action :switch_locale
around_action :switch_timezone
+ helper_method :locale_from_param
end
private
diff --git a/app/views/admin/system_health/_ai_status.html.erb b/app/views/admin/system_health/_ai_status.html.erb
index 5b7019218a..ce4736454f 100644
--- a/app/views/admin/system_health/_ai_status.html.erb
+++ b/app/views/admin/system_health/_ai_status.html.erb
@@ -30,9 +30,9 @@
<%= t("admin.system_health.show.ai.not_checked_help") %>
<% end %>
</p>
- <%= render DS::Button.new(
+ <%# A link, because a GET form drops the query string from its action. %>
+ <%= render DS::Link.new(
href: admin_system_health_path(tab: "ai", refresh_ai_health: "1"),
- method: :get,
variant: :outline,
size: :sm,
icon: "refresh-cw",
@@ -327,13 +327,18 @@
<h2 class="text-lg font-semibold text-primary"><%= t("admin.system_health.show.ai.worker.title") %></h2>
<p class="mt-1 text-sm text-secondary"><%= t("admin.system_health.show.ai.worker.description") %></p>
</div>
+ <%# `replace` renders the redirect back here as a morphing refresh, which
+ keeps the status on screen, even when a tab switch changed the URL
+ behind Turbo's back. The morph reloads this frame from its old src,
+ so a locale override has to make the round trip too. %>
<%= render DS::Button.new(
- href: verify_worker_ai_admin_system_health_path,
+ href: verify_worker_ai_admin_system_health_path(locale: locale_from_param),
method: :post,
variant: :outline,
size: :sm,
icon: "server",
- text: t("admin.system_health.show.ai.worker.verify_button")
+ text: t("admin.system_health.show.ai.worker.verify_button"),
+ data: { turbo_action: "replace" }
) %>
</div>
@@ -413,12 +418,15 @@
<% end %>
<% end %>
- <%= render DS::Alert.new(title: t("admin.system_health.show.ai.worker.settings_origin.title"), variant: :info) do %>
+ <% guidance_body_class = "mt-2 space-y-2 px-3 text-sm text-secondary" %>
+ <%= render DS::Disclosure.new(title: t("admin.system_health.show.ai.worker.settings_origin.title"), align: :left,
+ body_class: guidance_body_class) do %>
<p><%= t("admin.system_health.show.ai.worker.settings_origin.database_backed") %></p>
<p><%= t("admin.system_health.show.ai.worker.settings_origin.env_backed") %></p>
<% end %>
- <%= render DS::Alert.new(title: t("admin.system_health.show.ai.local_setup.title"), variant: :info) do %>
+ <%= render DS::Disclosure.new(title: t("admin.system_health.show.ai.local_setup.title"), align: :left,
+ body_class: guidance_body_class) do %>
<p><%= t("admin.system_health.show.ai.local_setup.description") %></p>
<p>
<code class="rounded bg-container-inset px-1.5 py-0.5">VECTOR_STORE_PROVIDER=pgvector</code>
diff --git a/app/views/admin/system_health/_background_jobs.html.erb b/app/views/admin/system_health/_background_jobs.html.erb
index 26ac7fcd6e..22aea338b1 100644
--- a/app/views/admin/system_health/_background_jobs.html.erb
+++ b/app/views/admin/system_health/_background_jobs.html.erb
@@ -8,19 +8,21 @@
) %>
<% end %>
- <div class="bg-container rounded-xl shadow-border-xs p-4">
- <h2 class="text-lg font-semibold mb-1"><%= t("admin.system_health.show.status_section_title") %></h2>
- <p class="text-sm text-secondary mb-4"><%= t("admin.system_health.show.status_section_description") %></p>
+ <%= render DS::Card.new(class: "gap-4") do %>
+ <div>
+ <h2 class="text-lg font-semibold text-primary"><%= t("admin.system_health.show.status_section_title") %></h2>
+ <p class="mt-1 text-sm text-secondary"><%= t("admin.system_health.show.status_section_description") %></p>
+ </div>
<dl class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div>
<dt class="text-secondary"><%= t("admin.system_health.show.labels.status") %></dt>
- <dd class="text-primary font-medium">
- <% if health.healthy? %>
- <span class="text-success"><%= t("admin.system_health.show.values.healthy") %></span>
- <% else %>
- <span class="text-warning"><%= t("admin.system_health.show.values.unhealthy") %></span>
- <% end %>
+ <dd>
+ <%= render DS::Pill.new(
+ label: t("admin.system_health.show.values.#{health.healthy? ? :healthy : :unhealthy}"),
+ tone: health.healthy? ? :success : :warning,
+ marker: false
+ ) %>
</dd>
</div>
<div>
@@ -44,11 +46,13 @@
</dd>
</div>
</dl>
- </div>
+ <% end %>
- <div class="bg-container rounded-xl shadow-border-xs p-4">
- <h2 class="text-lg font-semibold mb-1"><%= t("admin.system_health.show.counters_section_title") %></h2>
- <p class="text-sm text-secondary mb-4"><%= t("admin.system_health.show.counters_section_description") %></p>
+ <%= render DS::Card.new(class: "gap-4") do %>
+ <div>
+ <h2 class="text-lg font-semibold text-primary"><%= t("admin.system_health.show.counters_section_title") %></h2>
+ <p class="mt-1 text-sm text-secondary"><%= t("admin.system_health.show.counters_section_description") %></p>
+ </div>
<dl class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div>
@@ -68,11 +72,13 @@
<dd class="text-primary font-medium"><%= number_with_delimiter(health.processed_count) %></dd>
</div>
</dl>
- </div>
+ <% end %>
- <div class="bg-container rounded-xl shadow-border-xs p-4">
- <h2 class="text-lg font-semibold mb-1"><%= t("admin.system_health.show.queues_section_title") %></h2>
- <p class="text-sm text-secondary mb-4"><%= t("admin.system_health.show.queues_section_description") %></p>
+ <%= render DS::Card.new(class: "gap-4") do %>
+ <div>
+ <h2 class="text-lg font-semibold text-primary"><%= t("admin.system_health.show.queues_section_title") %></h2>
+ <p class="mt-1 text-sm text-secondary"><%= t("admin.system_health.show.queues_section_description") %></p>
+ </div>
<% breakdown = health.queue_breakdown %>
<% if breakdown.empty? %>
@@ -86,7 +92,7 @@
<% end %>
<% end %>
<% end %>
- </div>
+ <% end %>
<% if push_notification_test %>
<%= render "push_notifications", disabled_reason: push_disabled_reason,
latest_test: latest_push_test, results: push_test_results %>
diff --git a/app/views/admin/system_health/_push_notifications.html.erb b/app/views/admin/system_health/_push_notifications.html.erb
index 18c328cee4..0c2166d866 100644
--- a/app/views/admin/system_health/_push_notifications.html.erb
+++ b/app/views/admin/system_health/_push_notifications.html.erb
@@ -1,4 +1,5 @@
-<section id="push-notifications" class="bg-container rounded-xl shadow-border-xs p-4 space-y-4" data-testid="push-notification-status" aria-labelledby="push-notifications-title">
+<%= render DS::Card.new(id: "push-notifications", class: "gap-4", data: { testid: "push-notification-status" },
+ aria: { labelledby: "push-notifications-title" }) do %>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="space-y-1">
<h2 id="push-notifications-title" class="text-lg font-semibold text-primary"><%= t("admin.system_health.push_notifications.title") %></h2>
@@ -41,11 +42,11 @@
<%= result[:checked_at] ? l(result[:checked_at], format: :long) : t("admin.system_health.push_notifications.pending") %>
<% end %>
<% end %>
- <%= render DS::Button.new(
- href: admin_system_health_path(tab: "background_jobs", anchor: "push-notifications"), method: :get,
+ <%= render DS::Link.new(
+ href: admin_system_health_path(tab: "background_jobs", anchor: "push-notifications"),
variant: :outline, size: :sm, icon: "refresh-cw",
text: t("admin.system_health.push_notifications.refresh")
) %>
</div>
<% end %>
-</section>
+<% end %>
diff --git a/app/views/admin/system_health/ai_status.html.erb b/app/views/admin/system_health/ai_status.html.erb
new file mode 100644
index 0000000000..6aeb42b1cf
--- /dev/null
+++ b/app/views/admin/system_health/ai_status.html.erb
@@ -0,0 +1,3 @@
+<%= turbo_frame_tag "ai_status" do %>
+ <%= render "ai_status", ai_health: @ai_health, worker_ai_health_results: @worker_ai_health_results %>
+<% end %>
diff --git a/app/views/admin/system_health/show.html.erb b/app/views/admin/system_health/show.html.erb
index ad753d991c..58ac30a0eb 100644
--- a/app/views/admin/system_health/show.html.erb
+++ b/app/views/admin/system_health/show.html.erb
@@ -3,7 +3,6 @@
<%= render DS::Tabs.new(
active_tab: @active_tab,
url_param_key: "tab",
- navigate_on_change: true,
testid: "system-health-tabs"
) do |tabs| %>
<% tabs.with_nav do |nav| %>
@@ -18,6 +17,15 @@
<% end %>
<% tabs.with_panel(tab_id: "ai") do %>
- <%= render "ai_status", ai_health: @ai_health, worker_ai_health_results: @worker_ai_health_results %>
+ <%# Loads when the tab is first shown. The buttons inside navigate the page,
+ so their flash shows. A redirect back to this URL is a morphing refresh,
+ and `refresh: :morph` makes it reload the frame instead of morphing the
+ status back into the placeholder. A `?locale=` override only applies to
+ the request that carries it, so the src passes a valid one on. %>
+ <%= turbo_frame_tag "ai_status",
+ src: ai_status_admin_system_health_path(refresh_ai_health: params[:refresh_ai_health].presence_in(%w[1]), locale: locale_from_param),
+ loading: :lazy, target: "_top", refresh: :morph do %>
+ <%= render "entries/loading", message: t(".ai.loading") %>
+ <% end %>
<% end %>
<% end %>
diff --git a/app/views/entries/_loading.html.erb b/app/views/entries/_loading.html.erb
index cb9276b5f5..f0333f88cf 100644
--- a/app/views/entries/_loading.html.erb
+++ b/app/views/entries/_loading.html.erb
@@ -1,5 +1,7 @@
+<%# locals: (message: nil) %>
+
<div class="bg-container space-y-4 p-5 shadow-border-xs rounded-xl">
<div class="p-5 flex justify-center items-center">
- <%= tag.p t(".loading"), class: "text-secondary animate-pulse text-sm" %>
+ <%= tag.p message || t(".loading"), class: "text-secondary animate-pulse text-sm" %>
</div>
</div>
diff --git a/config/locales/views/admin/system_health/ca.yml b/config/locales/views/admin/system_health/ca.yml
index b6c670b201..c9581c1533 100644
--- a/config/locales/views/admin/system_health/ca.yml
+++ b/config/locales/views/admin/system_health/ca.yml
@@ -82,6 +82,7 @@ ca:
run_checks: Torna a executar les comprovacions
last_checked: Comprovacions en directe completades fa %{time_ago}. Els resultats es desen breument a la memòria cau.
not_checked_help: Obre directament l'URL d'estat de la IA o executa les comprovacions per verificar que el servei respon.
+ loading: "S'estan executant les comprovacions en directe…"
alerts:
custom_openai:
title: La comprovació del magatzem vectorial allotjat ha fallat en aquest endpoint personalitzat
diff --git a/config/locales/views/admin/system_health/de.yml b/config/locales/views/admin/system_health/de.yml
index 5bc30757dd..a31175a3c8 100644
--- a/config/locales/views/admin/system_health/de.yml
+++ b/config/locales/views/admin/system_health/de.yml
@@ -79,6 +79,7 @@ de:
seconds: "%{seconds} s"
no_queues: Es sind keine Warteschlangen registriert. Möglicherweise läuft der Worker nicht.
ai:
+ loading: "Live-Prüfungen laufen…"
labels:
failure_reason: Fehlerursache
function_calling_failure_reason: Fehlerursache beim Funktionsaufruf
diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.yml
index 455acd7611..498cf75e50 100644
--- a/config/locales/views/admin/system_health/en.yml
+++ b/config/locales/views/admin/system_health/en.yml
@@ -82,6 +82,7 @@ en:
run_checks: Run checks again
last_checked: "Live checks completed %{time_ago} ago. Results are cached briefly."
not_checked_help: Open the AI status URL directly or run the checks to verify service liveness.
+ loading: "Running live checks…"
alerts:
custom_openai:
title: The hosted vector-store check failed at this custom endpoint
diff --git a/config/locales/views/admin/system_health/fr.yml b/config/locales/views/admin/system_health/fr.yml
index 3469dc4816..5a6ecef5e5 100644
--- a/config/locales/views/admin/system_health/fr.yml
+++ b/config/locales/views/admin/system_health/fr.yml
@@ -151,6 +151,7 @@ fr:
llm:
description: Les vérifications en direct contrôlent le modèle configuré, lui demandent un appel de fonction trivial comme le fait l'assistant, puis testent séparément l'extraction de texte et le traitement vision / natif à l'aide d'un PDF synthétique d'une page ne contenant aucune donnée client. Les valeurs des identifiants ne sont jamais affichées.
title: LLM et traitement des PDF
+ loading: "Vérifications en direct en cours…"
local_setup:
description: Faites tourner le LLM via votre point de terminaison local compatible OpenAI, stockez les vecteurs de documents dans pgvector et faites pointer les paramètres d'embeddings vers un point de terminaison d'embeddings compatible OpenAI. L'image PostgreSQL doit inclure l'extension vector, et les dimensions d'embedding doivent correspondre au modèle sélectionné.
title: Installation locale recommandée
diff --git a/config/locales/views/admin/system_health/pl.yml b/config/locales/views/admin/system_health/pl.yml
index 498fb5664b..c0519d8bfd 100644
--- a/config/locales/views/admin/system_health/pl.yml
+++ b/config/locales/views/admin/system_health/pl.yml
@@ -166,6 +166,7 @@ pl:
na jednostronicowym syntetycznym PDF bez danych klienta. Wartości poświadczeń
nigdy nie są wyświetlane.
title: Przetwarzanie LLM i PDF
+ loading: "Trwają testy na żywo…"
local_setup:
description: Uruchom LLM przez lokalny endpoint kompatybilny z OpenAI,
przechowuj wektory dokumentów w pgvector i skieruj ustawienia embeddingów
diff --git a/config/locales/views/admin/system_health/pt-PT.yml b/config/locales/views/admin/system_health/pt-PT.yml
index 443e1f3054..922c2931fc 100644
--- a/config/locales/views/admin/system_health/pt-PT.yml
+++ b/config/locales/views/admin/system_health/pt-PT.yml
@@ -80,6 +80,7 @@ pt-PT:
run_checks: Executar verificações novamente
last_checked: "As verificações em direto foram concluídas há %{time_ago}. Os resultados ficam em cache por breves instantes."
not_checked_help: Abra diretamente o URL de estado da IA ou execute as verificações para confirmar que o serviço está operacional.
+ loading: "A executar as verificações em direto…"
alerts:
custom_openai:
title: A verificação do armazenamento de vetores alojado falhou neste endpoint personalizado
diff --git a/config/locales/views/admin/system_health/ru.yml b/config/locales/views/admin/system_health/ru.yml
index c57a564427..ce11a66dff 100644
--- a/config/locales/views/admin/system_health/ru.yml
+++ b/config/locales/views/admin/system_health/ru.yml
@@ -82,6 +82,7 @@ ru:
run_checks: Запустить проверки снова
last_checked: Проверки выполнены %{time_ago} назад. Результаты ненадолго кешируются.
not_checked_help: Откройте URL статуса ИИ напрямую или запустите проверки, чтобы убедиться в доступности сервисов.
+ loading: "Выполняются проверки…"
alerts:
custom_openai:
title: Проверка облачного векторного хранилища на этом пользовательском эндпоинте не пройдена
diff --git a/config/locales/views/admin/system_health/tr.yml b/config/locales/views/admin/system_health/tr.yml
index ab501e8ef1..a022281a63 100644
--- a/config/locales/views/admin/system_health/tr.yml
+++ b/config/locales/views/admin/system_health/tr.yml
@@ -82,6 +82,7 @@ tr:
run_checks: Kontrolleri yeniden çalıştır
last_checked: Canlı kontroller %{time_ago} önce tamamlandı. Sonuçlar kısa süreliğine önbelleğe alınır.
not_checked_help: Hizmetin çalıştığını doğrulamak için AI durum URL'sini doğrudan açın veya kontrolleri çalıştırın.
+ loading: "Canlı kontroller çalıştırılıyor…"
alerts:
custom_openai:
title: Barındırılan vektör deposu kontrolü bu özel uç noktada başarısız oldu
diff --git a/config/locales/views/admin/system_health/uk.yml b/config/locales/views/admin/system_health/uk.yml
index a9c145f285..3f37904215 100644
--- a/config/locales/views/admin/system_health/uk.yml
+++ b/config/locales/views/admin/system_health/uk.yml
@@ -82,6 +82,7 @@ uk:
run_checks: Запустити перевірки ще раз
last_checked: Перевірки в реальному часі завершено %{time_ago} тому. Результати ненадовго кешуються.
not_checked_help: Відкрийте URL стану ШІ напряму або запустіть перевірки, щоб переконатися, що сервіси працюють.
+ loading: "Виконуються перевірки в реальному часі…"
alerts:
custom_openai:
title: Перевірка хмарного векторного сховища на цьому власному endpoint не пройшла
diff --git a/config/routes.rb b/config/routes.rb
index 75a42fc1f9..33fc7102fb 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1013,6 +1013,7 @@ Rails.application.routes.draw do
# that happen to round-trip cleanly). The controller file is singular,
# so name it explicitly.
resource :system_health, only: :show, controller: "system_health" do
+ get :ai_status
post :verify_worker_ai
post :send_test_push
end
diff --git a/test/components/DS/tabs_test.rb b/test/components/DS/tabs_test.rb
deleted file mode 100644
index 7c9099ce64..0000000000
--- a/test/components/DS/tabs_test.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require "test_helper"
-
-class DS::TabsTest < ViewComponent::TestCase
- test "can navigate to the selected tab for server-backed content" do
- render_inline(DS::Tabs.new(
- active_tab: "background_jobs",
- url_param_key: "tab",
- navigate_on_change: true
- )) do |tabs|
- tabs.with_nav do |nav|
- nav.with_btn(id: "background_jobs", label: "Background jobs")
- nav.with_btn(id: "ai", label: "AI status")
- end
- tabs.with_panel(tab_id: "background_jobs") { "Jobs" }
- tabs.with_panel(tab_id: "ai") { "AI" }
- end
-
- assert_selector "[data-ds--tabs-url-param-key-value='tab']"
- assert_selector "[data-ds--tabs-navigate-on-change-value='true']"
- end
-end
diff --git a/test/controllers/admin/system_health_controller_test.rb b/test/controllers/admin/system_health_controller_test.rb
index f422f88aca..cd44e19022 100644
--- a/test/controllers/admin/system_health_controller_test.rb
+++ b/test/controllers/admin/system_health_controller_test.rb
@@ -46,7 +46,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_match(/Sidekiq status/, response.body)
assert_match(/Healthy/, response.body)
assert_select "button[role='tab']", text: "AI status"
- assert_select "[data-ds--tabs-navigate-on-change-value='true']"
# Nothing in the queue table takes focus, so on a narrow screen the scroll
# area has to be a named tab stop of its own for a keyboard to scroll it.
assert_select "[role='region'][aria-label='Queues']"
@@ -163,16 +162,28 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_session_path
end
+ test "only super admins can run the AI checks" do
+ AiHealth::Probe.any_instance.expects(:llm).never
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ get ai_status_admin_system_health_url
+ assert_redirected_to new_session_path
+
+ sign_in users(:family_admin)
+ get ai_status_admin_system_health_url
+ assert_redirected_to root_path
+ end
+ end
+
test "AI status reports the default OpenAI LLM and hosted vector store" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
- assert_select "button[role='tab'][aria-selected='true']", text: "AI status"
+ assert_select "turbo-frame#ai_status"
assert_match(/LLM and PDF processing/, response.body)
assert_select "[data-testid='selected-llm-provider']", text: "OpenAI"
assert_select "[data-testid='effective-llm-provider']", text: "OpenAI"
@@ -187,7 +198,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_no_match(/sk-secret-openai/, response.body)
end
- test "background jobs tab does not run AI probes" do
+ test "the page leaves the AI probes to a lazy frame on either tab" do
sign_in users(:sure_support_staff)
stub_healthy_sidekiq
AiHealth::Probe.any_instance.expects(:llm).never
@@ -197,17 +208,52 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
AiHealth::Probe.any_instance.expects(:openai_vector_store).never
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
- get admin_system_health_url
+ { "background_jobs" => "Background jobs", "ai" => "AI status" }.each do |tab, label|
+ get admin_system_health_url(tab: tab)
+
+ assert_response :success
+ assert_select "button[role='tab'][aria-selected='true']", text: label
+ assert_select "turbo-frame#ai_status[loading='lazy'][src='#{ai_status_admin_system_health_path}']",
+ text: "Running live checks…"
+ end
end
+ end
- assert_response :success
- assert_match(/Not checked/, response.body)
- assert_no_match(/sk-secret-openai/, response.body)
+ test "the lazy frame keeps the page's refresh and locale override" do
+ sign_in users(:sure_support_staff)
+
+ get admin_system_health_url(tab: "ai", refresh_ai_health: "1", locale: "de")
+
+ assert_select "turbo-frame#ai_status[src='#{ai_status_admin_system_health_path(refresh_ai_health: "1", locale: "de")}']"
+ end
+
+ test "the lazy frame drops a refresh or locale it can't use" do
+ sign_in users(:sure_support_staff)
+
+ [ { refresh_ai_health: "0", locale: "xx" }, { refresh_ai_health: { "x" => "1" }, locale: { "x" => "de" } } ].each do |query|
+ get admin_system_health_url(tab: "ai", **query)
+
+ assert_response :success
+ assert_select "turbo-frame#ai_status[src='#{ai_status_admin_system_health_path}']"
+ end
+ end
+
+ # The redirect's morph reloads the frame from its old src, so an override
+ # dropped on the way would leave the page and the frame in two languages.
+ test "a locale override survives the worker check round trip" do
+ sign_in users(:sure_support_staff)
+
+ with_ai_environment do
+ get ai_status_admin_system_health_url(locale: "de")
+ end
+ assert_select "form[action=?]", verify_worker_ai_admin_system_health_path(locale: "de")
+
+ post verify_worker_ai_admin_system_health_url(locale: "de")
+ assert_redirected_to admin_system_health_path(tab: "ai", locale: "de")
end
test "AI status warns when a custom OpenAI endpoint is paired with the hosted vector store" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_ai_environment(
"OPENAI_ACCESS_TOKEN" => "local-token",
@@ -225,7 +271,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
AiHealth::Probe.any_instance.stubs(:openai_vector_store).returns(
probe_result(:failing, failure_code: :request_failed, http_status: 404)
)
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -241,7 +287,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status names the missing function-calling support behind an unhelpful chat error" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
AiHealth::Probe.any_instance.stubs(:function_calling).returns(
probe_result(:failing, failure_code: :tools_refused, http_status: 404)
)
@@ -251,7 +296,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"OPENAI_URI_BASE" => "https://openrouter.ai/api/v1",
"OPENAI_MODEL" => "tngtech/deepseek-r1t2-chimera:free"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -263,7 +308,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status names an unavailable configured LLM model" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
AiHealth::Probe.any_instance.stubs(:llm).returns(
probe_result(:failing, failure_code: :model_not_available)
)
@@ -273,7 +317,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"OPENAI_URI_BASE" => "https://generativelanguage.googleapis.com/v1beta/openai",
"OPENAI_MODEL" => "retired-gemini-model"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -284,13 +328,12 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status separates a model that ignores tools from one that cannot use them" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
AiHealth::Probe.any_instance.stubs(:function_calling).returns(
probe_result(:failing, failure_code: :no_tool_call)
)
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -301,13 +344,12 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status reports text and vision PDF probes separately" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
AiHealth::Probe.any_instance.stubs(:pdf_vision_processing).returns(
probe_result(:failing, failure_code: :invalid_response)
)
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -323,7 +365,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status surfaces LLM and probe request timeouts as distinct values" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
# OPENAI_REQUEST_TIMEOUT bounds real LLM calls the app makes (chat, PDF
# import). AI_HEALTH_PROBE_TIMEOUT only bounds the admin "live checks".
@@ -332,7 +373,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"OPENAI_REQUEST_TIMEOUT" => "300",
"AI_HEALTH_PROBE_TIMEOUT" => "5"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -348,7 +389,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status does not probe PDF processing when it is explicitly disabled" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
AiHealth::Probe.any_instance.expects(:pdf_text_extraction).never
AiHealth::Probe.any_instance.expects(:pdf_vision_processing).never
@@ -356,7 +396,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"OPENAI_ACCESS_TOKEN" => "sk-secret-openai",
"OPENAI_SUPPORTS_PDF_PROCESSING" => "false"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -366,7 +406,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status reports Anthropic with an available pgvector store" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
Setting.stubs(:llm_provider).returns("anthropic")
connection = stub("connection")
@@ -388,7 +427,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"EMBEDDING_MODEL" => "mxbai-embed-large",
"EMBEDDING_DIMENSIONS" => "1024"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -403,7 +442,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status explains a missing pgvector table" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
Setting.stubs(:llm_provider).returns("anthropic")
VectorStore::Pgvector.stubs(:available?).returns(true)
AiHealth::Probe.any_instance.stubs(:pgvector).returns(
@@ -422,7 +460,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"EMBEDDING_MODEL" => "mxbai-embed-large",
"EMBEDDING_DIMENSIONS" => "1024"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -434,7 +472,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status explains an embedding dimensions mismatch" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
Setting.stubs(:llm_provider).returns("anthropic")
VectorStore::Pgvector.stubs(:available?).returns(true)
AiHealth::Probe.any_instance.stubs(:embedding).returns(
@@ -453,7 +490,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"EMBEDDING_MODEL" => "gemini-embedding-2-preview",
"EMBEDDING_DIMENSIONS" => "1024"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -466,7 +503,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status explains embedding probe timeouts" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
Setting.stubs(:llm_provider).returns("anthropic")
VectorStore::Pgvector.stubs(:available?).returns(true)
AiHealth::Probe.any_instance.stubs(:embedding).returns(
@@ -485,7 +521,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
"EMBEDDING_MODEL" => "gemini-embedding-2-preview",
"EMBEDDING_DIMENSIONS" => "3072"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -497,10 +533,9 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status explains when no vector store is configured" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_ai_environment do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -510,7 +545,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status marks Qdrant as scaffolded and redacts its URL" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_ai_environment(
"VECTOR_STORE_PROVIDER" => "qdrant",
@@ -524,7 +558,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
),
"QDRANT_API_KEY" => "header-secret"
) do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -534,12 +568,23 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_no_match(/qdrant-secret|query-secret|header-secret/, response.body)
end
+ test "AI status keeps its standing guidance collapsed" do
+ sign_in users(:sure_support_staff)
+
+ with_ai_environment do
+ get ai_status_admin_system_health_url
+ end
+
+ assert_response :success
+ assert_select "details:not([open]) summary", text: "Which settings need a restart?"
+ assert_select "details:not([open]) summary", text: "Recommended local setup"
+ end
+
test "AI status explains when no worker has checked in yet" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
assert_response :success
@@ -549,7 +594,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status renders a worker result and flags it matching the web configuration" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_memory_cache do
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
@@ -561,7 +605,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
vector_store_adapter: :openai
))
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
end
@@ -573,7 +617,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status flags a worker result whose configuration differs from the web process" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_memory_cache do
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
@@ -584,7 +627,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
llm_endpoint: "https://api.openai.com/v1"
))
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
end
@@ -594,7 +637,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status shows a failing worker result with its failure reason" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_memory_cache do
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
@@ -604,7 +646,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
failure_codes: [ :model_not_available ]
))
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
end
@@ -639,11 +681,10 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
end
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_memory_cache do
with_ai_environment do
WorkerAiHealth.record!(worker_snapshot(llm_status: :failing, failure_codes: reasons.keys))
- get admin_system_health_url(tab: "ai", locale: :de)
+ get ai_status_admin_system_health_url(locale: :de)
end
end
@@ -654,7 +695,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "AI status shows a stale worker result as stale rather than passing" do
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_memory_cache do
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
@@ -663,7 +703,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
checked_at: (WorkerAiHealth::STALE_AFTER + 1.minute).ago
))
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
end
end
@@ -722,7 +762,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
with_memory_cache do
with_ai_environment do
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
assert_response :success
assert_select "h2", text: "Worker-Verifikation"
assert_select "button", text: "Worker-Konfiguration prüfen"
@@ -745,7 +785,6 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
test "German worker results distinguish passing failing stale and differing configurations" do
users(:sure_support_staff).update!(locale: "de")
sign_in users(:sure_support_staff)
- stub_healthy_sidekiq
with_memory_cache do
with_ai_environment("OPENAI_ACCESS_TOKEN" => "synthetic-token") do
@@ -755,7 +794,7 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
[ { checked_at: (WorkerAiHealth::STALE_AFTER + 1.minute).ago }, "Veraltet", "Entspricht dem Web-Prozess" ]
].each do |overrides, status, configuration|
WorkerAiHealth.record!(worker_snapshot(**{ vector_store_adapter: :openai, vector_store_status: :passing }.merge(overrides)))
- get admin_system_health_url(tab: "ai")
+ get ai_status_admin_system_health_url
assert_response :success
assert_select "[data-testid='worker-ai-health-result']" do
assert_select "[data-testid='worker-process-identity']", text: "worker:1"
diff --git a/test/system/admin/system_health_test.rb b/test/system/admin/system_health_test.rb
index d50e29d946..70ab4106e4 100644
--- a/test/system/admin/system_health_test.rb
+++ b/test/system/admin/system_health_test.rb
@@ -18,12 +18,7 @@ class Admin::SystemHealthTest < ApplicationSystemTestCase
end
test "selecting AI status runs live probes" do
- ClimateControl.modify(
- "OPENAI_ACCESS_TOKEN" => "test-token",
- "OPENAI_URI_BASE" => nil,
- "OPENAI_MODEL" => nil,
- "VECTOR_STORE_PROVIDER" => nil
- ) do
+ with_openai_access_token do
visit admin_system_health_path
click_button "AI status"
@@ -39,6 +34,56 @@ class Admin::SystemHealthTest < ApplicationSystemTestCase
end
end
+ test "running the checks again stays on the AI tab and forces fresh probes" do
+ with_openai_access_token do
+ visit admin_system_health_path(tab: "ai")
+ assert_text "Live check passed"
+
+ click_on "Run checks again"
+
+ assert_current_path admin_system_health_path(tab: "ai", refresh_ai_health: "1")
+ assert_selector "turbo-frame#ai_status[src$='?refresh_ai_health=1']"
+ assert_text "Live check passed"
+ end
+ end
+
+ test "going back after switching tabs returns to system health" do
+ with_openai_access_token do
+ visit admin_system_health_path
+ click_button "AI status"
+ assert_text "Live check passed"
+
+ click_link "Preferences", match: :first
+ assert_no_selector "[data-testid='system-health-tabs']"
+ page.go_back
+
+ assert_current_path admin_system_health_path(tab: "ai")
+ assert_selector "button[role='tab'][aria-selected='true']", text: "AI status"
+ end
+ end
+
+ # The redirect comes back to this page, which the button's `replace` action
+ # turns into a morphing refresh even after a tab switch. The button has to
+ # leave the frame for the flash to show, and the frame has to keep its status
+ # through the morph instead of taking the new page's loading placeholder.
+ test "queueing a worker check keeps the AI status on screen" do
+ with_openai_access_token do
+ visit admin_system_health_path
+ click_button "AI status"
+ assert_text "Live check passed"
+ page.execute_script(<<~JS)
+ document.addEventListener("turbo:morph", () => {
+ window.aiStatusAfterMorph = document.getElementById("ai_status").textContent
+ }, { once: true })
+ JS
+
+ click_button "Verify worker configuration"
+
+ assert_text "Worker check queued"
+ assert_match "Live check passed", page.evaluate_script("window.aiStatusAfterMorph")
+ end
+ end
+
test "hosted super admin enables the test button by registering an iOS device" do
Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
Apns::Client.stubs(:configured?).returns(true)
@@ -76,6 +121,16 @@ class Admin::SystemHealthTest < ApplicationSystemTestCase
end
private
+ def with_openai_access_token(&block)
+ ClimateControl.modify(
+ "OPENAI_ACCESS_TOKEN" => "test-token",
+ "OPENAI_URI_BASE" => nil,
+ "OPENAI_MODEL" => nil,
+ "VECTOR_STORE_PROVIDER" => nil,
+ &block
+ )
+ end
+
def probe_result(status)
AiHealth::Probe::Result.new(
status: status,