/// What the run route answers when the server resolver hands back an error string (#5941 review). The resolver has three
/// shapes and each gets its own answer: a registry read fault (a store fault, not the caller's request) is logged and answers
diff --git a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/analysis-findings.js b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/analysis-findings.js
index 243d26883b..b90b111616 100644
--- a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/analysis-findings.js
+++ b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/analysis-findings.js
@@ -13,7 +13,10 @@
* by its highest-severity finding, each card showing a severity badge, the advice text, the fix script in a
* with a Copy button, and, for an incident finding, a link to that server's Queries tab.
*
- * Advise-only: nothing here runs a fix, mutes, or asks the service for a fresh analysis.
+ * Advise-only: nothing here runs a fix or mutes. Two actions reach the service (#6389), both the desktop's: "Generate now" queues an
+ * analyze_now command (POST /api/analyze-now) and re-reads the findings when the service finishes it, and "Ask AI" copies the
+ * investigation prompt the Viewer copies (GET /api/analysis/ask-ai-prompt: the service builds the text, so the page and the Viewer
+ * cannot drift). Neither holds a key or calls a model.
*
* Which findings are "incidents" follows the desktop: a finding that carries a structured_remediation is a
* standing config fix and gets no Active Queries link; every other finding with a time_range does. The link
@@ -25,7 +28,8 @@
* R4 (XSS): every value, the fix script included, reaches the DOM through el()'s text path.
*/
-import { el, readToolWithinKeptHistory, keptWindowStrip, noticeStrip, readErrorStrip, emptyStrip, loadingStrip, localTime, bandClass, dbScopeChip } from "../util.js";
+import { getSession } from "../views-api.js";
+import { el, apiGet, apiWrite, listOnlyNote, readToolWithinKeptHistory, keptWindowStrip, noticeStrip, readErrorStrip, emptyStrip, loadingStrip, localTime, bandClass, dbScopeChip } from "../util.js";
/** The desktop's severity cutoffs: >= 1.5 Critical, >= 0.75 Warning, else Info. */
export function severityLabel(severity) {
@@ -136,6 +140,123 @@ function copyButton(text) {
return btn;
}
+/** The path of the Ask AI prompt for a finding: the server, its headline and, when it has one, its UTC window. The service converts the window to the server's own clock. */
+export function askAiPath(server, f) {
+ const params = ["server=" + encodeURIComponent(server), "title=" + encodeURIComponent(findingTitle(f))];
+ if (f.time_range && f.time_range.start && f.time_range.end) {
+ params.push("start=" + encodeURIComponent(f.time_range.start), "end=" + encodeURIComponent(f.time_range.end));
+ }
+ return "/api/analysis/ask-ai-prompt?" + params.join("&");
+}
+
+function askAiButton(server, f) {
+ const btn = el("button", { class: "btn small", type: "button", text: "Ask AI", title: "Copies a prompt for your own MCP client to investigate this finding. Nothing is sent anywhere." });
+ btn.addEventListener("click", async () => {
+ const res = await apiGet(askAiPath(server, f));
+ const prompt = res.kind === "data" && res.data && typeof res.data.prompt === "string" ? res.data.prompt : null;
+ btn.textContent = prompt && (await copyText(prompt)) ? "AI prompt copied" : "Couldn't copy";
+ });
+ return btn;
+}
+
+/* ─────────────────────────── generate now ─────────────────────────── */
+
+const POLL_MS = 2000;
+/* The desktop viewer waits three minutes for the pass; the service caps it at two. */
+const GIVE_UP_MS = 3 * 60 * 1000;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+function refusalText(res) {
+ if (res.status === 0) return res.message || "The request did not reach the service.";
+ if (res.status === 403 && !(res.body && res.body.error)) return "This account has read-only access, so it cannot start an analysis.";
+ const body = res.body && typeof res.body === "object" ? res.body : {};
+ return body.error || "The service refused the request (HTTP " + res.status + ").";
+}
+
+/** Queue an analysis pass and wait for it. Returns { ok, message }. */
+export async function runAnalyzeNow(server) {
+ const queued = await apiWrite("POST", "/api/analyze-now", { server });
+ if (queued.expired) return { ok: false, message: "Your session has expired. Sign in again." };
+ if (queued.status !== 202 || !queued.body || queued.body.command_id == null) return { ok: false, message: refusalText(queued) };
+ const id = queued.body.command_id;
+ const started = Date.now();
+ while (Date.now() - started < GIVE_UP_MS) {
+ await sleep(POLL_MS);
+ const r = await apiGet("/api/analyze-now/" + id);
+ if (r.kind === "data" && r.data && r.data.finished) {
+ return r.data.succeeded ? { ok: true, message: "" } : { ok: false, message: "Analysis did not complete: " + (r.data.result_status || r.data.status) };
+ }
+ }
+ return { ok: false, message: "Analysis is still running. Refresh in a moment." };
+}
+
+/** The note for a store login that cannot queue the run. A managed store always can; a store brought along may need its roles script run again. */
+export function generateUnavailableNote(managedStore) {
+ return managedStore === true
+ ? listOnlyNote(true, "an analysis cannot be started from this page", "To generate recommendations now")
+ : "This dashboard's store login cannot queue an analysis. Re-run Darling/tools/provision-roles.sql on the store, or use the Viewer's Generate now.";
+}
+
+/* The server page rebuilds this tab on every poll, and a pass can outlast a poll, so the lock, the status line and the reload hook live
+ here and not in the elements (the same reason active-live.js keeps its state at module scope). */
+const running = new Set();
+const statusText = new Map();
+const buttons = new Map();
+const statusNodes = new Map();
+/* server -> re-read and redraw the findings of the tab that is on the page now. */
+const reloaders = new Map();
+
+function paintGenerate(server) {
+ const node = statusNodes.get(server);
+ if (node && node.isConnected) node.textContent = statusText.get(server) || "";
+ const btn = buttons.get(server);
+ if (btn && btn.isConnected) btn.disabled = running.has(server);
+}
+
+function say(server, text) {
+ statusText.set(server, text);
+ paintGenerate(server);
+}
+
+/** The "Generate now" block: nothing for a read-only seat, a note for a store login that cannot queue, else the button and its status line. */
+function generateBar(server) {
+ const slot = el("div", { class: "reco-generate" }, []);
+ (async () => {
+ const session = await getSession();
+ if (!session || !session.can_edit) return;
+ const avail = await apiGet("/api/analyze-now/available");
+ if (avail.kind !== "data" || !avail.data) return;
+ if (avail.data.can_queue !== true) {
+ slot.appendChild(noticeStrip(generateUnavailableNote(avail.data.managed_store === true)));
+ slot.dataset.status = "unavailable";
+ return;
+ }
+ const status = el("span", { class: "muted", role: "status" }, []);
+ const button = el("button", { type: "button", class: "btn", title: "Asks the service to run an analysis pass for this server now, then shows the new findings." }, ["Generate now"]);
+ button.addEventListener("click", async () => {
+ if (running.has(server)) return;
+ running.add(server);
+ say(server, "Analyzing " + server + "...");
+ try {
+ const outcome = await runAnalyzeNow(server);
+ say(server, outcome.ok ? "" : outcome.message);
+ const reload = reloaders.get(server);
+ if (reload) await reload();
+ } finally {
+ running.delete(server);
+ paintGenerate(server);
+ }
+ });
+ buttons.set(server, button);
+ statusNodes.set(server, status);
+ slot.appendChild(el("div", {}, [button, " ", status]));
+ slot.dataset.status = "ready";
+ paintGenerate(server);
+ })();
+ return slot;
+}
+
/* ─────────────────────────── rendering ─────────────────────────── */
/** The score after the label, or nothing when the row carries no numeric severity. */
@@ -163,6 +284,7 @@ function card(server, f, showTitle) {
}
const actions = [];
if (f.remediation_command) actions.push(copyButton(f.remediation_command));
+ actions.push(askAiButton(server, f));
if (showsActiveQueriesLink(f)) {
actions.push(el("a", { class: "btn small", href: "#/server/" + encodeURIComponent(server) + "/queries", text: "Open in Active Queries" }));
}
@@ -207,12 +329,14 @@ export const analysisFindingsTab = {
reachReads: ["get_analysis_findings"],
build: (server, ctx) => {
const body = el("div", { class: "panel-body" }, [loadingStrip()]);
- (async () => {
+ const load = async () => {
const res = await readToolWithinKeptHistory("get_analysis_findings", { server, hours: ctx.hours, limit: 50, full_text: true }, ctx && ctx.signal);
if (res.kind === "aborted") return;
while (body.firstChild) body.removeChild(body.firstChild);
for (const n of renderFindings(server, res)) if (n) body.appendChild(n);
- })();
- return [el("div", { class: "panel card span-2" }, [el("h3", {}, ["Recommendations", el("span", { class: "panel-sub", text: " " + ctx.label }), dbScopeChip("get_analysis_findings")]), body])];
+ };
+ reloaders.set(server, load);
+ load();
+ return [el("div", { class: "panel card span-2" }, [el("h3", {}, ["Recommendations", el("span", { class: "panel-sub", text: " " + ctx.label }), dbScopeChip("get_analysis_findings")]), generateBar(server), body])];
},
};
diff --git a/Darling/PerformanceMonitor.Darling.Storage/RecommendationAskAiPrompt.cs b/Darling/PerformanceMonitor.Darling.Storage/RecommendationAskAiPrompt.cs
new file mode 100644
index 0000000000..857d1dbe12
--- /dev/null
+++ b/Darling/PerformanceMonitor.Darling.Storage/RecommendationAskAiPrompt.cs
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2026 Erik Darling, Darling Data LLC
+ *
+ * This file is part of the SQL Server Performance Monitor.
+ *
+ * Licensed under the MIT License. See LICENSE file in the project root for full license information.
+ */
+
+using System;
+using System.Globalization;
+using PerformanceMonitor.Analysis.Baselines;
+
+namespace PerformanceMonitor.Darling.Storage;
+
+///
+/// The text "Ask AI" copies for a Recommendations finding (#6389). One builder for the Viewer's card and the web's route, so the two
+/// say the same thing for the same finding. It holds no key and calls no model: it is a prompt for the reader's own MCP client.
+///
+public static class RecommendationAskAiPrompt
+{
+ ///
+ /// The MCP investigation prompt for a finding. Pure (no clock, no UI) so the interpolation is unit-testable. The window times are
+ /// formatted in whatever zone the caller passed (both callers pass the monitored server's local time). Ported verbatim from Lite's prompt.
+ ///
+ public static string Build(string serverName, string title, DateTime from, DateTime to)
+ {
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "Using the PerformanceMonitor MCP tools, investigate this finding on server \"{0}\": " +
+ "\"{1}\". It was flagged around {2:yyyy-MM-dd HH:mm}–{3:HH:mm}. Call analyze_server / " +
+ "get_analysis_findings and the relevant wait/blocking/memory tools, then tell me the " +
+ "likely cause and what to do.",
+ serverName, title, from, to);
+ }
+
+ ///
+ /// The window of a finding that carries none: the two hours before , each end shown on
+ /// (#4766). The two hours are real hours: taking the server's "now" and subtracting two hours
+ /// from that wall-clock time spans one real hour too few across a spring-forward change.
+ ///
+ public static (DateTime From, DateTime To) FallbackWindow(ServerClock serverClock, DateTime utcNow)
+ {
+ ArgumentNullException.ThrowIfNull(serverClock);
+ return (serverClock.ToServerLocal(utcNow.AddHours(-2)), serverClock.ToServerLocal(utcNow));
+ }
+
+ /// The prompt for a finding on : its window (or the fallback when it has none) in server-local time.
+ public static string BuildFor(string serverName, string title, DateTime? windowStartUtc, DateTime? windowEndUtc, ServerClock serverClock, DateTime utcNow)
+ {
+ ArgumentNullException.ThrowIfNull(serverClock);
+ var (from, to) = windowStartUtc is { } start && windowEndUtc is { } end
+ ? (serverClock.ToServerLocal(start), serverClock.ToServerLocal(end))
+ : FallbackWindow(serverClock, utcNow);
+ return Build(serverName, title, from, to);
+ }
+}
diff --git a/Darling/PerformanceMonitor.Darling.Viewer/RecommendationsViewModel.cs b/Darling/PerformanceMonitor.Darling.Viewer/RecommendationsViewModel.cs
index 2b21758725..08403f72e2 100644
--- a/Darling/PerformanceMonitor.Darling.Viewer/RecommendationsViewModel.cs
+++ b/Darling/PerformanceMonitor.Darling.Viewer/RecommendationsViewModel.cs
@@ -355,7 +355,7 @@ public string AskAiPrompt
/// (and starts at a local time that never happened) and one real hour too many across a fall-back change.
///
internal static (DateTime From, DateTime To) FallbackWindow(ServerClock serverClock, DateTime utcNow)
- => (serverClock.ToServerLocal(utcNow.AddHours(-2)), serverClock.ToServerLocal(utcNow));
+ => PerformanceMonitor.Darling.Storage.RecommendationAskAiPrompt.FallbackWindow(serverClock, utcNow);
}
///