diff --git a/Darling/Darling.Tests/FirstVisitFrontDoorBehaviourTests.cs b/Darling/Darling.Tests/FirstVisitFrontDoorBehaviourTests.cs
new file mode 100644
index 0000000000..887e8d83b1
--- /dev/null
+++ b/Darling/Darling.Tests/FirstVisitFrontDoorBehaviourTests.cs
@@ -0,0 +1,252 @@
+/*
+ * 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.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Text.Json;
+using Xunit;
+using static Darling.Tests.RepoFile;
+
+namespace Darling.Tests;
+
+///
+/// #9220: a first visit to a server's page through a front door of three stores. The page starts its panel reads before the server's
+/// fleet card answers (#8554), and the card of a server with no recent collection (is_online false) used to make it restart them,
+/// so the reads in flight were aborted and sent again. These run the shipped app.js and Server page under Node
+/// (web-first-visit-front-door-harness.mjs) with three stores whose fleet reads answer at their own virtual times, and count the
+/// reads the page aborted or sent twice. The same holds for a first visit by a partial server name, which the card's arrival moved to the
+/// server's own name by a new render that aborted the batch in flight and read everything again. Node is skipped when it is not installed.
+///
+[Trait("Cost", "Slow")]
+public sealed class FirstVisitFrontDoorBehaviourTests
+{
+ private const string OfflineCard = "{\"is_online\":false}";
+
+ private static JsonElement Run(string scenario, string tab, string card, int ownStoreFleetMs, int panelReadMs, params (string Key, string Value)[] env)
+ {
+ var psi = new ProcessStartInfo("node") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
+ psi.ArgumentList.Add(PathTo("Darling", "Darling.Tests", "web-first-visit-front-door-harness.mjs"));
+ psi.ArgumentList.Add(PathTo("Darling", "PerformanceMonitor.Darling.Service", "wwwroot", "js"));
+ psi.ArgumentList.Add(scenario);
+ psi.ArgumentList.Add(tab);
+ psi.Environment["CARD"] = card;
+ psi.Environment["OWN_MS"] = ownStoreFleetMs.ToString();
+ psi.Environment["PANEL_MS"] = panelReadMs.ToString();
+ foreach (var (key, value) in env) psi.Environment[key] = value;
+
+ Process proc;
+ try
+ {
+ proc = Process.Start(psi)!;
+ }
+ catch (Win32Exception)
+ {
+ Assert.Skip("Node is not installed, so the shipped page scripts cannot be run.");
+ return default;
+ }
+
+ using (proc)
+ {
+ var error = proc.StandardError.ReadToEndAsync();
+ var output = proc.StandardOutput.ReadToEnd().Trim();
+ if (!proc.WaitForExit(60000))
+ {
+ proc.Kill(entireProcessTree: true);
+ Assert.Fail("the first visit harness did not finish in 60 s for scenario " + scenario);
+ }
+
+ Assert.True(proc.ExitCode == 0, "the first visit harness failed for scenario " + scenario + ": " + error.Result);
+ using var doc = JsonDocument.Parse(output.Split('\n').First(l => l.StartsWith('{')));
+ return doc.RootElement.Clone();
+ }
+ }
+
+ private static void AssertNothingRestarted(JsonElement r)
+ {
+ Assert.Equal(0, r.GetProperty("aborted").GetArrayLength());
+ Assert.Equal(0, r.GetProperty("sentMoreThanOnce").GetArrayLength());
+ Assert.Equal(0, r.GetProperty("abortCalls").GetArrayLength());
+ Assert.True(r.GetProperty("reads").GetInt32() > 0, "the page sent no panel reads at all");
+ }
+
+ // The server's own store answers last. Case 1: after every panel read has finished. Case 2: while the panel reads are still out.
+ [Theory]
+ [InlineData("overview", 1500, 400)]
+ [InlineData("overview", 700, 1500)]
+ [InlineData("queries", 1500, 400)]
+ [InlineData("queries", 700, 1500)]
+ public void FirstVisit_OfStaleServer_KeepsThePanelBatch_AndSendsEachReadOnce(string tab, int ownStoreFleetMs, int panelReadMs)
+ {
+ AssertNothingRestarted(Run("firstVisit", tab, OfflineCard, ownStoreFleetMs, panelReadMs));
+ }
+
+ [Theory]
+ [InlineData("overview")]
+ [InlineData("queries")]
+ public void FirstVisit_OfServerWithRecentCollection_KeepsThePanelBatch(string tab)
+ {
+ AssertNothingRestarted(Run("firstVisit", tab, "", 700, 1500));
+ }
+
+ [Fact]
+ public void FirstVisit_ByLinkWithNoStore_OfStaleServer_KeepsThePanelBatch()
+ {
+ AssertNothingRestarted(Run("firstVisitBareLink", "overview", OfflineCard, 1500, 400));
+ }
+
+ // Running Jobs words its empty state by the card's is_online (ctx.offline), so this tab still draws its panels again for a stale server.
+ [Fact]
+ public void FirstVisit_OfStaleServer_OnTheActivityTab_StillDrawsRunningJobsWithTheCard()
+ {
+ var r = Run("firstVisit", "activity", OfflineCard, 1500, 400);
+ Assert.True(r.GetProperty("sentMoreThanOnce").GetArrayLength() > 0);
+ }
+
+ // A first visit by a route name that is only PART of the server's own name (it equals neither the card's display name nor its server
+ // name): the panel reads go out under that name, and the card's arrival moves the link to the server's own name. The reads in flight
+ // stay, so none is aborted and none is sent a second time under the new name.
+ private const string PartialCards = "[{\"server_name\":\"alpha.corp.test\",\"display_name\":\"alpha-prod\"},{\"server_name\":\"beta\",\"display_name\":\"beta\"}]";
+ private const string TwoMatchingCards = "[{\"server_name\":\"alpha.corp.test\",\"display_name\":\"alpha-prod\"},{\"server_name\":\"alpha2.corp.test\",\"display_name\":\"alpha-two\"}]";
+
+ private static JsonElement RunPartial(string scenario, string tab, string card, int ownStoreFleetMs, int panelReadMs, string cards) =>
+ Run(scenario, tab, card, ownStoreFleetMs, panelReadMs, ("CARDS", cards), ("ROUTE", "alpha"), ("FULL", "alpha.corp.test"), ("NEXT_TAB", tab == "queries" ? "overview" : "queries"));
+
+ private static void AssertReadsUnder(JsonElement byServer, params string[] allowedNames)
+ {
+ var total = 0;
+ foreach (var p in byServer.EnumerateObject())
+ {
+ Assert.Contains(p.Name, allowedNames);
+ total += p.Value.GetInt32();
+ }
+
+ Assert.True(total > 0, "no panel read was sent");
+ }
+
+ [Theory]
+ [InlineData("overview", 700, 1500)]
+ [InlineData("overview", 1500, 400)]
+ [InlineData("queries", 700, 1500)]
+ [InlineData("queries", 1500, 400)]
+ public void FirstVisit_ByPartialServerName_KeepsThePanelBatch_AndMovesTheLinkToTheOwnName(string tab, int ownStoreFleetMs, int panelReadMs)
+ {
+ var r = RunPartial("partialFirstVisit", tab, "", ownStoreFleetMs, panelReadMs, PartialCards);
+ AssertNothingRestarted(r);
+ // Every read went out under the route's name, once: none was sent again under the card's name.
+ AssertReadsUnder(r.GetProperty("byServer"), "alpha", "null");
+ Assert.Equal("#/s/use1/server/alpha.corp.test/" + tab, r.GetProperty("finalHash").GetString());
+ }
+
+ [Fact]
+ public void FirstVisit_ByPartialServerName_OfStaleServer_KeepsThePanelBatch()
+ {
+ var r = RunPartial("partialFirstVisit", "overview", OfflineCard, 700, 1500, PartialCards);
+ AssertNothingRestarted(r);
+ Assert.Equal("#/s/use1/server/alpha.corp.test/overview", r.GetProperty("finalHash").GetString());
+ }
+
+ // Running Jobs words its empty state by is_online, so a stale server's card still draws this tab's panels afresh, under the own name.
+ [Fact]
+ public void FirstVisit_ByPartialServerName_OfStaleServer_OnTheActivityTab_StillDrawsWithTheCard()
+ {
+ var r = RunPartial("partialFirstVisit", "activity", OfflineCard, 700, 1500, PartialCards);
+ Assert.True(r.GetProperty("aborted").GetArrayLength() > 0);
+ Assert.Equal("#/s/use1/server/alpha.corp.test/activity", r.GetProperty("finalHash").GetString());
+ }
+
+ // After the move, the page's own poll and a tab click read by the server's own name.
+ [Fact]
+ public void AfterThePartialNameMoves_ThePollAndATabClick_ReadByTheOwnName()
+ {
+ var r = RunPartial("partialThenPollAndTab", "overview", "", 700, 400, PartialCards);
+ Assert.Equal(0, r.GetProperty("aborted").GetArrayLength());
+ AssertReadsUnder(r.GetProperty("afterPoll"), "alpha.corp.test", "null");
+ AssertReadsUnder(r.GetProperty("afterTabClick"), "alpha.corp.test", "null");
+ Assert.Equal("#/s/use1/server/alpha.corp.test/queries", r.GetProperty("finalHash").GetString());
+ }
+
+ private static void AssertEveryReadUsesTheHeldRange(JsonElement byHours)
+ {
+ var total = 0;
+ foreach (var p in byHours.EnumerateObject())
+ {
+ // The held range is a live 36 hours. A read with no hours at all is not a panel read of the range (the catalog, the alert badge).
+ Assert.True(p.Name is "36" or "null", "a panel read went out with hours=" + p.Name + " instead of the held range");
+ if (p.Name == "36") total += p.Value.GetInt32();
+ }
+
+ Assert.True(total > 0, "no panel read carried the held range");
+ }
+
+ // A custom range held under the PARTIAL name (a range set from the link before the card lands) follows the move to the own name. The reads in
+ // flight were sent with it and are kept (none aborted, none sent again), the picker the new render draws names it, and the page's next poll
+ // reads the own name with the same range instead of the preset.
+ [Theory]
+ [InlineData("overview")]
+ [InlineData("queries")]
+ public void FirstVisit_ByPartialServerName_WithACustomRangeHeld_KeepsTheBatch_AndTheRangeFollowsTheMove(string tab)
+ {
+ var r = RunPartial("partialCustomRange", tab, "", 700, 1500, PartialCards);
+ AssertNothingRestarted(r);
+ AssertReadsUnder(r.GetProperty("byServer"), "alpha", "null");
+ AssertEveryReadUsesTheHeldRange(r.GetProperty("byHours"));
+ Assert.Equal(new[] { "Past 36 hours" }, r.GetProperty("pickerText").EnumerateArray().Select(e => e.GetString()).ToArray());
+ AssertReadsUnder(r.GetProperty("afterPoll"), "alpha.corp.test", "null");
+ AssertEveryReadUsesTheHeldRange(r.GetProperty("afterPollHours"));
+ Assert.Equal("#/s/use1/server/alpha.corp.test/" + tab, r.GetProperty("finalHash").GetString());
+ }
+
+ // The restart path (a stale server's Running Jobs tab draws afresh under the own name) keeps the range too: nothing reads the preset, and the
+ // picker still names the held range.
+ [Fact]
+ public void FirstVisit_ByPartialServerName_WithACustomRangeHeld_OnTheRestartPath_KeepsTheRange()
+ {
+ var r = RunPartial("partialCustomRange", "activity", OfflineCard, 700, 1500, PartialCards);
+ Assert.True(r.GetProperty("aborted").GetArrayLength() > 0, "the stale server's Running Jobs tab should draw again under the own name");
+ AssertEveryReadUsesTheHeldRange(r.GetProperty("byHours"));
+ Assert.Equal(new[] { "Past 36 hours" }, r.GetProperty("pickerText").EnumerateArray().Select(e => e.GetString()).ToArray());
+ AssertReadsUnder(r.GetProperty("afterPoll"), "alpha.corp.test", "null");
+ AssertEveryReadUsesTheHeldRange(r.GetProperty("afterPollHours"));
+ }
+
+ // A partial name that fits two servers shows its message and reads nothing once the card answers; the link stays as it was.
+ [Fact]
+ public void FirstVisit_ByAmbiguousPartialName_ReadsNothingAfterTheCard()
+ {
+ var r = RunPartial("partialAmbiguous", "overview", "", 700, 1500, TwoMatchingCards);
+ Assert.Equal(0, r.GetProperty("startedAfterTheCard").GetInt32());
+ Assert.Equal(0, r.GetProperty("rewrites").GetArrayLength());
+ Assert.Equal("#/s/use1/server/alpha/overview", r.GetProperty("finalHash").GetString());
+ }
+
+ // The reads a partial-name visit kept are still the page's reads: opening another server ends them.
+ [Fact]
+ public void LeavingForAnotherServer_AfterAPartialNameMoved_AbortsTheReadsKept()
+ {
+ var r = RunPartial("leaveForAnotherServer", "queries", "", 700, 1500, PartialCards);
+ Assert.Equal(0, r.GetProperty("abortedBeforeLeaving").GetInt32());
+ var started = r.GetProperty("startedForAlpha").GetInt32();
+ Assert.True(started > 0);
+ Assert.Equal(0, r.GetProperty("answeredForAlpha").GetInt32());
+ Assert.Equal(started, r.GetProperty("abortedForAlpha").GetInt32());
+ }
+
+ // A real navigation still ends the page's reads: the first server's reads are aborted when the person opens another server.
+ [Fact]
+ public void LeavingForAnotherServer_AbortsTheReadsOfTheServerLeft()
+ {
+ var r = Run("leaveForAnotherServer", "queries", OfflineCard, 700, 1500);
+ Assert.Equal(0, r.GetProperty("abortedBeforeLeaving").GetInt32());
+ var started = r.GetProperty("startedForAlpha").GetInt32();
+ Assert.True(started > 0);
+ Assert.Equal(0, r.GetProperty("answeredForAlpha").GetInt32());
+ Assert.Equal(started, r.GetProperty("abortedForAlpha").GetInt32());
+ }
+}
diff --git a/Darling/Darling.Tests/WebWaitsActivityTrendsPageTests.cs b/Darling/Darling.Tests/WebWaitsActivityTrendsPageTests.cs
index a760ecd04b..c45ac21bc2 100644
--- a/Darling/Darling.Tests/WebWaitsActivityTrendsPageTests.cs
+++ b/Darling/Darling.Tests/WebWaitsActivityTrendsPageTests.cs
@@ -40,7 +40,7 @@ public void TheWaitStatsTab_DrawsTheLatchAndSpinlockTrends_AfterTheirTables()
[Fact]
public void TheActivityTab_DrawsTheSessionStatsTrend()
{
- var activity = Between(Js(), " id: \"activity\",\n label: \"Activity\",\n build:", " tablePanel(\n \"Running Jobs\"");
+ var activity = Between(Js(), " id: \"activity\",\n label: \"Activity\",\n", " tablePanel(\n \"Running Jobs\"");
Assert.Contains("sessionStatsTrendPanel(server, ctx)", activity);
}
diff --git a/Darling/Darling.Tests/view-folders-harness.mjs b/Darling/Darling.Tests/view-folders-harness.mjs
index 58e620db25..be7e4217b8 100644
--- a/Darling/Darling.Tests/view-folders-harness.mjs
+++ b/Darling/Darling.Tests/view-folders-harness.mjs
@@ -299,6 +299,7 @@ try {
document: { querySelectorAll: (selector) => (selector === ".nav a" ? shell.links : []) },
isSessionExpired: () => false,
beginPageScope: () => {},
+ holdsRenamedServerRoute: () => false,
frontDoor: () => false,
gateStore: () => false,
currentRoute: () => ({ name: shell.routeName, id: null, param: null }),
diff --git a/Darling/Darling.Tests/web-first-visit-front-door-harness.mjs b/Darling/Darling.Tests/web-first-visit-front-door-harness.mjs
new file mode 100644
index 0000000000..1c032d48bf
--- /dev/null
+++ b/Darling/Darling.Tests/web-first-visit-front-door-harness.mjs
@@ -0,0 +1,278 @@
+/* #9220: runs the shipped app.js (the real route(), scheduler tick, util.js read counter and page scope) and the real Server page
+ behind a FRONT DOOR of three stores, as a first visit: the shell reads each store's /api/fleet, the page starts its panel reads
+ before the fleet card answers (#8554), and each store's fleet answer lands at its own virtual time. A fetch records its
+ AbortSignal, so the harness counts the reads the page aborted, and AbortController.prototype.abort records who called it.
+ Prints one scenario's result as one line of JSON. FirstVisitFrontDoorTests starts it as
+ node web-first-visit-front-door-harness.mjs
+ Panel reads answer after PANEL_MS of virtual time. A fleet read answers after the delay its store was given. */
+import { pathToFileURL } from "node:url";
+import path from "node:path";
+
+const jsDir = path.resolve(process.argv[2]);
+const scenario = process.argv[3];
+
+class FakeNode {
+ constructor(tag) {
+ this.tag = tag; this.children = []; this.attrs = {}; this.dataset = {}; this.style = {}; this.className = "";
+ this.listeners = {}; this.parentNode = null; this.hidden = false; this.value = ""; this.textContent = "";
+ this.classList = { add() {}, remove() {}, toggle() {}, contains: () => false };
+ }
+ get firstChild() { return this.children[0] || null; }
+ appendChild(c) { if (c && typeof c === "object") c.parentNode = this; this.children.push(c); return c; }
+ append(...cs) { cs.forEach((c) => this.appendChild(c)); }
+ prepend(c) { this.children.unshift(c); }
+ insertBefore(c, ref) { const i = ref ? this.children.indexOf(ref) : -1; if (c && typeof c === "object") c.parentNode = this; if (i < 0) this.children.push(c); else this.children.splice(i, 0, c); return c; }
+ removeChild(c) { const i = this.children.indexOf(c); if (i >= 0) this.children.splice(i, 1); return c; }
+ replaceChildren(...cs) { this.children = []; cs.forEach((c) => this.appendChild(c)); }
+ remove() {}
+ setAttribute(n, v) { this.attrs[n] = String(v); }
+ getAttribute(n) { return n in this.attrs ? this.attrs[n] : null; }
+ removeAttribute(n) { delete this.attrs[n]; }
+ addEventListener(t, f) { (this.listeners[t] ||= []).push(f); }
+ removeEventListener() {}
+ dispatch(t) { (this.listeners[t] || []).forEach((f) => f({ target: this, preventDefault() {}, stopPropagation() {} })); }
+ focus() {}
+ querySelector() { return null; }
+ querySelectorAll() { return []; }
+}
+
+const docListeners = {};
+const byId = {};
+for (const id of ["main", "server-list", "view-list", "statusbar", "refresh-hint", "store-picker"]) byId[id] = new FakeNode("div");
+const brand = new FakeNode("div");
+byId["auto-refresh-toggle"] = new FakeNode("button");
+brand.appendChild(byId["auto-refresh-toggle"]);
+
+globalThis.document = {
+ createElement: (t) => new FakeNode(t), createElementNS: (_n, t) => new FakeNode(t),
+ createTextNode: (t) => { const n = new FakeNode("#text"); n.textContent = String(t); return n; },
+ createDocumentFragment: () => new FakeNode("#frag"),
+ getElementById: (id) => byId[id] || null, querySelector: () => null, querySelectorAll: () => [],
+ addEventListener(t, f) { (docListeners[t] ||= []).push(f); }, removeEventListener() {}, body: new FakeNode("body"), documentElement: new FakeNode("html"),
+ cookie: "", hidden: false,
+};
+globalThis.Node = FakeNode;
+globalThis.MutationObserver = class { observe() {} disconnect() {} };
+globalThis.window = globalThis;
+globalThis.scrollTo = () => {};
+const rewrites = [];
+globalThis.location = { hash: "", pathname: "/", search: "", href: "http://localhost/", origin: "http://localhost", reload() { reloads++; } };
+let reloads = 0;
+globalThis.history = { pushState() {}, replaceState(_s, _t, url) { rewrites.push(String(url)); location.hash = String(url).replace(/^[^#]*/, ""); }, back() {} };
+const winListeners = {};
+globalThis.addEventListener = (t, f) => { (winListeners[t] ||= []).push(f); };
+globalThis.removeEventListener = () => {};
+globalThis.dispatchEvent = (e) => { (winListeners[e.type] || []).forEach((f) => f(e)); return true; };
+globalThis.Event = class { constructor(type) { this.type = type; } };
+globalThis.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+globalThis.requestAnimationFrame = () => 0;
+globalThis.cancelAnimationFrame = () => {};
+const storage = new Map();
+globalThis.localStorage = {
+ getItem: (k) => (storage.has(k) ? storage.get(k) : null),
+ setItem: (k, v) => { storage.set(k, String(v)); },
+ removeItem: (k) => { storage.delete(k); },
+};
+globalThis.sessionStorage = globalThis.localStorage;
+
+let now = 1_000_000;
+Date.now = () => now;
+let tick = null;
+globalThis.setInterval = (fn) => { tick = fn; return 1; };
+globalThis.clearInterval = () => {};
+globalThis.setTimeout = () => 0;
+globalThis.clearTimeout = () => {};
+
+/* Who called abort(): the first stack line outside this harness and the platform, for each abort of a signal a fetch carries. */
+const abortCalls = [];
+const realAbort = AbortController.prototype.abort;
+AbortController.prototype.abort = function (...a) {
+ const frames = String(new Error().stack).split("\n").slice(2).map((l) => l.trim()).filter((l) => l.includes("wwwroot") || l.includes("/js/") || l.includes("front-door-"));
+ abortCalls.push({ at: now, frames: frames.slice(0, 4).map((l) => l.replace(/\(.*[\\/]js[\\/]/, "(")) });
+ return realAbort.apply(this, a);
+};
+
+const PANEL_MS = process.env.PANEL_MS ? Number(process.env.PANEL_MS) : 400;
+const STORES = ["use1", "use2", "use3"];
+let fleetDelay = { use1: 100, use2: 300, use3: 600 };
+let ownStore = "use1";
+let serverCard = process.env.CARD ? JSON.parse(process.env.CARD) : null;
+const card = (id, name, extra = {}) => ({
+ server_id: id, display_name: name, server_name: name, band: "Healthy", band_label: "Healthy", is_online: true,
+ status: "ok", last_collection: null, tags: [], is_silenced: false, metric_count: 0, measured_metric_count: 0, ...extra,
+});
+/* CARDS (JSON, optional): the fleet's cards as [{server_name, display_name}], for a server whose route name is only part of its own name. */
+const cardsEnv = process.env.CARDS ? JSON.parse(process.env.CARDS) : null;
+const fleetOf = (names, extra) => ({
+ total_servers: names.length, critical_count: 0, warning_count: 0, offline_count: 0, offline_servers: 0, tags: [],
+ cards: cardsEnv ? cardsEnv.map((c, i) => card(i + 1, c.display_name, { server_name: c.server_name, ...(i === 0 ? extra : {}) })) : names.map((n, i) => card(i + 1, n, i === 0 ? extra : {})), generated_at: "2026-11-21T12:00:00Z", worst_servers: [], additional_problem_count: 0,
+});
+const json = (body, status = 200) => ({ status, body });
+const storeOf = (opts) => (opts.headers || {})["X-Darling-Store"] || "";
+const answerFor = (url, opts) => {
+ const p = url.split("?")[0];
+ if (p === "/api/session") return json({ can_edit: false, front_door: true });
+ if (p === "/api/front-door") return json({ stores: STORES.map((n) => ({ name: n, health: "ok", server_count: 1 })) });
+ if (p === "/api/front-door/locate") return json({ store: ownStore, server_name: "alpha" });
+ if (p === "/api/fleet") return json(fleetOf(["alpha"], serverCard));
+ if (p === "/api/catalog") return json({ reads: [], viz: [], compose: {} });
+ return json({});
+};
+const delayFor = (url, opts) => {
+ const p = url.split("?")[0];
+ if (p === "/api/fleet") return fleetDelay[storeOf(opts)] ?? 100;
+ if (p === "/api/session" || p === "/api/front-door") return 0;
+ if (p === "/api/front-door/locate") return 50;
+ if (p.startsWith("/api/read/")) return PANEL_MS;
+ return 0;
+};
+let pending = [];
+const fetchLog = [];
+globalThis.fetch = (url, opts = {}) => {
+ url = String(url);
+ const rec = { at: now, url, store: storeOf(opts), signal: opts.signal || null, aborted: false, answeredAt: null };
+ fetchLog.push(rec);
+ return new Promise((resolve, reject) => {
+ const a = answerFor(url, opts);
+ const p = { at: now + delayFor(url, opts), done: () => { rec.answeredAt = now; resolve({ ok: a.status < 400, status: a.status, json: async () => a.body, text: async () => JSON.stringify(a.body) }); } };
+ pending.push(p);
+ if (opts.signal) opts.signal.addEventListener("abort", () => {
+ rec.aborted = true; rec.abortedAt = now;
+ pending = pending.filter((x) => x !== p);
+ reject(Object.assign(new Error("aborted"), { name: "AbortError" }));
+ }, { once: true });
+ });
+};
+const releaseDue = () => { const due = pending.filter((p) => p.at <= now); pending = pending.filter((p) => p.at > now); due.forEach((p) => p.done()); };
+const drain = async () => { for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r)); };
+/* Moves the virtual clock in 10 ms steps, answering what is due and running the scheduler's one-second tick on each second. */
+async function advance(ms) {
+ for (let t = 0; t < ms; t += 10) {
+ now += 10; releaseDue(); await drain();
+ if ((now - 1_000_000) % 1000 === 0 && tick) { tick(); await drain(); }
+ }
+}
+const fire = (list, type) => (list[type] || []).forEach((f) => f({}));
+async function boot(hash) {
+ location.hash = hash;
+ await import(pathToFileURL(path.join(jsDir, "app.js")).href + "?run=1");
+ await drain();
+}
+const go = async (hash) => { location.hash = hash; fire(winListeners, "hashchange"); await drain(); };
+
+const panelReads = () => fetchLog.filter((r) => r.url.startsWith("/api/read/"));
+const summary = () => {
+ const reads = panelReads();
+ const byUrl = {};
+ for (const r of reads) byUrl[r.url] = (byUrl[r.url] || 0) + 1;
+ return {
+ reads: reads.length,
+ aborted: reads.filter((r) => r.aborted).map((r) => ({ url: r.url.slice(0, 60), startedAt: r.at - 1_000_000, abortedAt: r.abortedAt - 1_000_000 })),
+ sentMoreThanOnce: Object.entries(byUrl).filter(([, n]) => n > 1).map(([u, n]) => u.slice(0, 60) + " x" + n),
+ fleetReads: fetchLog.filter((r) => r.url === "/api/fleet").map((r) => r.store + "@" + (r.at - 1_000_000) + "->" + (r.answeredAt == null ? "-" : r.answeredAt - 1_000_000)),
+ abortCalls: abortCalls.map((c) => ({ at: c.at - 1_000_000, frames: c.frames })),
+ rewrites, reloads,
+ };
+};
+
+const serverOf = (r) => new URLSearchParams(r.url.split("?")[1] || "").get("server");
+const tally = (reads) => { const t = {}; for (const r of reads) { const n = serverOf(r); t[n] = (t[n] || 0) + 1; } return t; };
+const tallyBy = (reads, param) => { const t = {}; for (const r of reads) { const n = new URLSearchParams(r.url.split("?")[1] || "").get(param); t[n] = (t[n] || 0) + 1; } return t; };
+/* The text of every range picker button in the page on screen. */
+const pickerTexts = () => {
+ const found = [];
+ const walk = (n) => { if (!n || typeof n !== "object") return; if (n.className === "trp-button" || (n.attrs && n.attrs.class === "trp-button")) found.push(n.textContent); (n.children || []).forEach(walk); };
+ walk(byId.main);
+ return found;
+};
+const ROUTE = process.env.ROUTE || "alpha";
+const FULL = process.env.FULL || "alpha";
+
+/* argv: . The own store (use1) answers its fleet at OWN_MS, the others at 300 and 600. */
+const tabArg = process.argv[4] || "";
+const hashFor = (store, server) => "#/" + (store ? "s/" + store + "/" : "") + "server/" + server + (tabArg ? "/" + tabArg : "");
+const startScenario = (own) => { fleetDelay = { use1: own, use2: 300, use3: 600 }; };
+
+const scenarios = {
+ /* A first visit through a front door of three stores. The server's own store answers its fleet read at OWN_MS, after the panel reads
+ have started and, with a short PANEL_MS, after they have all finished. */
+ async firstVisit() {
+ startScenario(Number(process.env.OWN_MS || 1500));
+ await boot(hashFor("use1", "alpha"));
+ await advance(4000);
+ return summary();
+ },
+ /* The same first visit by a link with no store in it: the front door is asked which store has the server. */
+ async firstVisitBareLink() {
+ startScenario(Number(process.env.OWN_MS || 1500));
+ await boot(hashFor("", "alpha"));
+ await advance(4000);
+ return summary();
+ },
+ /* #9220: a first visit by a PARTIAL route name (ROUTE is part of the card's server_name FULL and equals neither it nor the display name).
+ The fleet card of the own store answers at OWN_MS. Reports the server name each panel read went out under, and where the link ended. */
+ async partialFirstVisit() {
+ startScenario(Number(process.env.OWN_MS || 700));
+ await boot(hashFor("use1", ROUTE));
+ await advance(4000);
+ return { ...summary(), byServer: tally(panelReads()), finalHash: location.hash };
+ },
+ /* The partial-name first visit, then the page's own 60 s poll, then a tab click by the link the page ended on. Reads sent after each
+ step are tallied by the name they carry. */
+ async partialThenPollAndTab() {
+ startScenario(Number(process.env.OWN_MS || 700));
+ await boot(hashFor("use1", ROUTE));
+ await advance(4000);
+ const first = panelReads().length;
+ await advance(65000);
+ const afterPoll = panelReads().slice(first);
+ const second = panelReads().length;
+ await go("#/s/use1/server/" + encodeURIComponent(FULL) + "/" + (process.env.NEXT_TAB || "queries"));
+ await advance(2500);
+ return { ...summary(), afterPoll: tally(afterPoll), afterTabClick: tally(panelReads().slice(second)), finalHash: location.hash };
+ },
+ /* #9220: a first visit by a PARTIAL route name while the reader holds a custom range under that name (a range set from the link before the
+ card lands). The range is a live 36 hours, not one of the presets. Reports the range each panel read carried, the picker's text
+ after the move, and the reads the page's own 60 s poll sent under the own name. */
+ async partialCustomRange() {
+ const server = await import(pathToFileURL(path.join(jsDir, "pages", "server.js")).href);
+ const HOUR = 3600000;
+ server.applyCustomRange(ROUTE, now - 36 * HOUR, now, now, { redraw: false });
+ startScenario(Number(process.env.OWN_MS || 700));
+ await boot(hashFor("use1", ROUTE));
+ await advance(12000);
+ /* What the first visit alone did, before the poll: the summary and the tallies are taken here. */
+ const first = panelReads().length;
+ const visit = { ...summary(), byServer: tally(panelReads()), byHours: tallyBy(panelReads(), "hours"), pickerText: pickerTexts() };
+ await advance(65000);
+ const afterPoll = panelReads().slice(first);
+ return {
+ ...visit,
+ afterPoll: tally(afterPoll), afterPollHours: tallyBy(afterPoll, "hours"), finalHash: location.hash,
+ };
+ },
+ /* A first visit by a partial name that fits two servers: the page says so and sends no panel read after the card answers. */
+ async partialAmbiguous() {
+ startScenario(Number(process.env.OWN_MS || 700));
+ await boot(hashFor("use1", ROUTE));
+ await advance(4000);
+ const late = panelReads().filter((r) => serverOf(r) !== null && r.at - 1_000_000 > Number(process.env.OWN_MS || 700));
+ return { ...summary(), startedAfterTheCard: late.length, finalHash: location.hash };
+ },
+ /* A first visit, then a real navigation to another server while its reads are still out. */
+ async leaveForAnotherServer() {
+ startScenario(Number(process.env.OWN_MS || 700));
+ await boot(hashFor("use1", "alpha"));
+ await advance(1000);
+ const before = summary();
+ await go("#/s/use1/server/beta" + (tabArg ? "/" + tabArg : ""));
+ await advance(10);
+ const alpha = panelReads().filter((r) => r.url.includes("server=alpha"));
+ return { startedForAlpha: alpha.length, abortedForAlpha: alpha.filter((r) => r.aborted).length, answeredForAlpha: alpha.filter((r) => r.answeredAt != null).length, abortedBeforeLeaving: before.aborted.length };
+ },
+};
+if (!Object.hasOwn(scenarios, scenario)) throw new Error("unknown scenario " + scenario);
+const result = await scenarios[scenario]();
+if (process.env.DBG) console.error(fetchLog.map((r) => (r.at - 1_000_000) + " " + r.url.slice(0, 70) + " sig=" + !!r.signal + " ab=" + r.aborted + " ans=" + r.answeredAt).join("\n"));
+console.log(JSON.stringify(result));
+process.exit(0);
diff --git a/Darling/Darling.Tests/web-scheduler-harness.mjs b/Darling/Darling.Tests/web-scheduler-harness.mjs
index 7ac6bb03c9..d37b7e7742 100644
--- a/Darling/Darling.Tests/web-scheduler-harness.mjs
+++ b/Darling/Darling.Tests/web-scheduler-harness.mjs
@@ -86,6 +86,7 @@ const sandbox = {
localTime: String,
hasInFlightReads: () => inFlight > 0,
beginPageScope() {},
+ holdsRenamedServerRoute: () => false,
readErrorCount: () => errors,
isSessionExpired: () => false,
onSessionExpired() {},
diff --git a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/app.js b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/app.js
index 6e97021045..728a235088 100644
--- a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/app.js
+++ b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/app.js
@@ -48,7 +48,7 @@ import { renderAg } from "./pages/ag.js";
import { renderSweeps } from "./pages/sweeps.js";
import { renderStoreHealth } from "./pages/store-health.js";
import { renderAdmin } from "./pages/admin.js";
-import { renderServer } from "./pages/server.js";
+import { renderServer, holdsRenamedServerRoute } from "./pages/server.js";
import { renderFinops } from "./pages/finops.js";
import { renderAlerts } from "./pages/alerts.js";
import { renderInvestigations, requestIdFromQuery } from "./pages/investigations.js";
@@ -332,7 +332,9 @@ function route(opts) {
and starts a fresh read count, so a read left behind cannot hold the new page's poll, Refresh button, tab-return
refresh or render-time back-off. The poll and the Refresh button re-render the SAME page (`poll: true`): that page
aborts its own older load, as before, and the count carries on. */
- if (!(opts && opts.poll === true)) beginPageScope();
+ /* #9220: a first visit by a partial server name moves to the server's own name with the panel reads it already has out: those reads are
+ for the page that stays, so this one route change does not end them. */
+ if (!(opts && opts.poll === true) && !holdsRenamedServerRoute()) beginPageScope();
if (frontDoor() && gateStore(opts)) return;
diff --git a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server-tabs.js b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server-tabs.js
index 1d2e0be46c..cc83997628 100644
--- a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server-tabs.js
+++ b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server-tabs.js
@@ -958,6 +958,9 @@ export const SERVER_TABS = [
{
id: "activity",
label: "Activity",
+ /* #9220: Running Jobs words its empty state by the fleet card's is_online (ctx.offline), so a card that flips it repaints this tab's
+ panels. No other tab reads ctx.offline, and a first visit on one of them keeps the reads it started before the card arrived. */
+ readsOffline: true,
build: (server, ctx) => [
perfmonPanel(server, ctx),
sessionStatsTrendPanel(server, ctx),
diff --git a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server.js b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server.js
index 4c52dff32e..62b03b780b 100644
--- a/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server.js
+++ b/Darling/PerformanceMonitor.Darling.Service/wwwroot/js/pages/server.js
@@ -340,7 +340,7 @@ export function renderServer(main, server, tabId, opts) {
const custom = customRanges.get(server);
/* A fixed custom range cannot change under the poll, so the poll keeps the panels it already drew (same server, same
tab) instead of reading the same hours again. The Refresh button passes `manual: true`: a click asks for a re-read, so it rebuilds even then. A live range, a preset and a tab or server click rebuild as before. */
- const keep = isPoll && !(opts && opts.manual === true) && !!custom && !custom.live && !!gridNode && gridKey === server + "|" + (tabId || "");
+ const keep = takeRenamedBatch(server, tabId) || (isPoll && !(opts && opts.manual === true) && !!custom && !custom.live && !!gridNode && gridKey === server + "|" + (tabId || ""));
/* #6933: every other poll, and the Refresh button, keep the same server and tab's panels on screen and read them again in place. */
const inPlace = isPoll && !keep && gridPageIsShown(main, server, tabId);
if (!isPoll && cancelRefresh) { cancelRefresh(); cancelRefresh = null; }
@@ -439,7 +439,30 @@ export function renderServer(main, server, tabId, opts) {
rememberServerId(exactName, card.server_id);
const next = storeHash("#/server/" + encodeURIComponent(exactName)) + (tabId ? "/" + encodeURIComponent(tabId) : "");
if (typeof history !== "undefined" && history.replaceState) history.replaceState(null, "", next);
- window.dispatchEvent(new Event("hashchange"));
+ /* #9220: the panels started on the route's partial name read the same one server the exact name does (the read API resolves a name by
+ the rule resolveFleetCard mirrors), so when they agree with the card they are the right reads and the render under the exact name
+ adopts them: app.js's route() does not end the page's reads for it, and renderServer keeps the grid. Without this the new render
+ aborted the batch in flight and sent every panel read again. A card that changes the tab set or the offline wording, or a range
+ waiting on the catalog, still draws afresh as before. The hold lives for the synchronous dispatch only. */
+ const tabKey = tabId || "";
+ /* The custom range is held by route name, and the panels in flight read the one held under the partial name. The render under the
+ exact name reads its own, so the range moves with the rename (the exact name takes it, the partial name lets go), on the
+ restart path too. The batch in flight agrees only when the exact name will read the same range: the partial name's own, or,
+ with none held there, no range held under the exact name either (it would read that one, where the batch read the preset). */
+ const partialRange = customRanges.get(server);
+ const sameRange = !!partialRange || !customRanges.has(exactName);
+ if (partialRange) {
+ customRanges.set(exactName, partialRange);
+ customRanges.delete(server);
+ }
+ const agrees = beforeCard && !!painted && serverTabsFor(card) === painted && !(serverIsOffline(exactName) && current.tab && current.tab.readsOffline === true)
+ && !!gridNode && gridKey === server + "|" + tabKey && !catalogWaits.has(server) && sameRange;
+ if (agrees) renameHold = { from: server, to: exactName, tabKey };
+ try {
+ window.dispatchEvent(new Event("hashchange"));
+ } finally {
+ renameHold = null;
+ }
return;
}
}
@@ -454,21 +477,48 @@ export function renderServer(main, server, tabId, opts) {
/* Repaint only when there is nothing painted yet, when the fresh card chooses a DIFFERENT registry —
the two registries are module constants, so that comparison is exact — or when it flips the server's online
- state, which the panels were built with (ctx.offline: the poll where a server first goes stale painted them
- from the remembered, still-online card). A null card never repaints over a painted page: a fleet read that
+ state on a tab that words something by it (readsOffline), which the panels were built with (ctx.offline: the poll where a
+ server first goes stale painted them from the remembered, still-online card). Any other tab keeps its panels and the reads
+ in flight, whatever the card says about the server being online (#9220). A null card never repaints over a painted page: a fleet read that
failed says nothing about which engine this server runs, and it leaves lastCard, so the online state, as it was. */
- if (!painted || (card && serverTabsFor(card) !== painted) || serverIsOffline(server) !== paintedOffline) {
+ if (!painted || (card && serverTabsFor(card) !== painted) || (serverIsOffline(server) !== paintedOffline && current.tab && current.tab.readsOffline === true)) {
painted = paintTabsKeeping(keep && !painted, tabsSlot, server, tabId, card, inPlace);
paintedOffline = serverIsOffline(server);
} else if (beforeCard) {
- /* The card agrees with the set the panels were started on (#8554): draw the tab bar and notes around them, and read nothing again. */
+ /* The card agrees with the set the panels were started on (#8554): draw the tab bar and notes around them, and read nothing again.
+ #9220: a card that says the server is offline agrees too, unless the tab words something by it (readsOffline), so a stale server's
+ first visit no longer aborts the reads in flight and sends each of them again. */
painted = paintTabsKeeping(true, tabsSlot, server, tabId, card, inPlace);
+ paintedOffline = serverIsOffline(server);
+ } else {
+ paintedOffline = serverIsOffline(server);
}
beforeCard = false;
});
}
}
+/* #9220: set for the one synchronous hashchange that moves a partial route name to the card's own name while the panels started on the
+ partial name are still in flight. `from` and `to` are the two route names and `tabKey` the tab. */
+let renameHold = null;
+
+/** True while the page is moving a first visit from a partial route name to the server's own name and keeps the panel reads it has out,
+ * so the router must not end the page's reads for that one route change (#9220). */
+export function holdsRenamedServerRoute() {
+ return renameHold !== null;
+}
+
+/** True once, for the render the rename above asked for: it is the same server and tab, and the grid on screen is the one the partial
+ * name started, so its reads are kept and its grid is adopted (#9220). */
+function takeRenamedBatch(server, tabId) {
+ const hold = renameHold;
+ if (!hold || hold.to !== server || hold.tabKey !== (tabId || "") || !gridNode || gridKey !== hold.from + "|" + hold.tabKey) return false;
+ renameHold = null;
+ const started = dataStarts.get(hold.from);
+ if (started && !dataStarts.has(server)) dataStarts.set(server, started);
+ return true;
+}
+
/** Whether the page may start a server's panel reads before its fleet card arrives (#8554). Not for a server this browser has seen as
* PostgreSQL (its tab set is the other one), not for a tab only the PostgreSQL set has, and not while a database filter is saved and
* this browser does not know the server's id: a filter is keyed by the card's server id, so reads sent without it would be the