417 lines
18 KiB
JavaScript
417 lines
18 KiB
JavaScript
"use strict";
|
|
|
|
// Source-level pins + behavioral tests for adpanel:scheduler-delete-inflight-cue
|
|
// in bot.js.
|
|
//
|
|
// The finding: deleteSchedulerTask's fleet-wide re-entrancy guard
|
|
// (`if (schedulerDeleteInFlight) return;`) fired BEFORE confirm() and before
|
|
// any visual cue, and renderSchedulerTasks left every delete button enabled
|
|
// during the flight (bounded at 20000 by adpanel:scheduler-fetch-bound, but
|
|
// still up to ~20s). Delete task A, click delete on task B → a complete
|
|
// silent no-op; the button just looked broken. The create path shows its
|
|
// state (schedulerCreateBtn disabled + "Creating...") — the delete path had
|
|
// no equivalent.
|
|
//
|
|
// The fix mirrors the create path's in-flight affordance WITHOUT changing the
|
|
// guard's contract:
|
|
// (a) after the guard passes and the user confirms, every rendered delete
|
|
// button is disabled for the whole flight and restored in the finally;
|
|
// (b) the early-return guard alerts ("A delete is already in progress…")
|
|
// instead of dropping the click in silence — still BEFORE confirm(),
|
|
// so a refused delete can never even open a second dialog. The alert
|
|
// is load-bearing, not cosmetic: a mid-flight refresh
|
|
// (schedulerRefreshBtn → loadSchedulerTasks → renderSchedulerTasks)
|
|
// re-renders FRESH ENABLED delete buttons while the flight is still
|
|
// held, so a click on those lands on the guard.
|
|
// (c) unchanged by design: one delete in flight fleet-wide, the confirm
|
|
// dialog, the 20000 bound, the schedulerDelete token flow, and the
|
|
// set-after-confirm/cleared-in-finally guard mechanics.
|
|
//
|
|
// Restore strategy (why a re-query, not a captured NodeList): after a
|
|
// SUCCESS loadSchedulerTasks() is called fire-and-forget and its synchronous
|
|
// prologue swaps the list to "Loading tasks..." BEFORE its first await, so by
|
|
// the time the finally runs the old buttons are detached — a re-query
|
|
// restores only what is still in the DOM (nothing) and the fresh re-render
|
|
// ships enabled buttons; after a FAILURE the same nodes are still there and
|
|
// get re-enabled. Capturing node references would write to detached nodes.
|
|
//
|
|
// bot.js is one IIFE: the structural pins below read the source and assert on
|
|
// well-anchored windows (the bot-scheduler-*.test.js convention), and the
|
|
// behavioral tests slice the REAL deleteSchedulerTask body out of bot.js and
|
|
// drive it in a vm sandbox with a minimal DOM stub (the
|
|
// bot-store-confirm-guard.test.js convention). If the function is renamed or
|
|
// moved, its anchor assertions fail loudly rather than testing a stale copy.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const vm = require("node:vm");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
|
|
const botSrc = fs.readFileSync(BOT_JS, "utf8");
|
|
|
|
function sourceWindow(src, startAnchor, endAnchor, label) {
|
|
const start = src.indexOf(startAnchor);
|
|
assert.notStrictEqual(start, -1, `${label || "window"}: start anchor not found: ${startAnchor}`);
|
|
const end = src.indexOf(endAnchor, start + startAnchor.length);
|
|
assert.notStrictEqual(end, -1, `${label || "window"}: end anchor not found: ${endAnchor}`);
|
|
return src.slice(start, end);
|
|
}
|
|
|
|
const deleteWindow = sourceWindow(
|
|
botSrc,
|
|
"async function deleteSchedulerTask(taskId) {",
|
|
"async function createSchedulerTask() {",
|
|
"deleteSchedulerTask"
|
|
);
|
|
|
|
// The state declaration lives with the rest of the scheduler scene state.
|
|
const stateDecl = botSrc.match(/^[ \t]*let schedulerDeleteInFlight = false;[ \t]*$/m);
|
|
assert.ok(stateDecl, "the schedulerDeleteInFlight guard declaration must stay at scheduler-scene state");
|
|
|
|
// ── Structural pins: guard feedback, disable/restore placement, prior fixes ─
|
|
|
|
const GUARD_ALERT = "A delete is already in progress — please wait.";
|
|
const CONFIRM_LITERAL = "Are you sure you want to delete this scheduled task?";
|
|
|
|
test("the in-flight guard alerts instead of silently returning, still before confirm()", () => {
|
|
assert.ok(
|
|
deleteWindow.includes("adpanel:scheduler-delete-inflight-cue"),
|
|
"the constraint comment must travel with the guard"
|
|
);
|
|
// Strip comments so prose occurrences cannot count as code.
|
|
const code = deleteWindow.replace(/\/\/[^\n]*/g, "");
|
|
|
|
const guardAt = code.indexOf("if (schedulerDeleteInFlight) {");
|
|
assert.notStrictEqual(guardAt, -1, "the guard must be an if-BLOCK now (it alerts), not a bare one-line return");
|
|
const alertAt = code.indexOf("alert('" + GUARD_ALERT + "')", guardAt);
|
|
assert.notStrictEqual(alertAt, -1, "the guard must alert in the scene's 'already in progress' idiom");
|
|
const guardReturnAt = code.indexOf("return;", alertAt);
|
|
assert.notStrictEqual(guardReturnAt, -1, "the guard must still return after the alert");
|
|
const confirmAt = code.indexOf("confirm('" + CONFIRM_LITERAL + "')");
|
|
assert.notStrictEqual(confirmAt, -1, "the confirm dialog must stay");
|
|
const setAt = code.indexOf("schedulerDeleteInFlight = true;");
|
|
assert.notStrictEqual(setAt, -1, "the guard must still be set");
|
|
|
|
assert.ok(
|
|
guardAt < alertAt && alertAt < guardReturnAt && guardReturnAt < confirmAt && confirmAt < setAt,
|
|
"ordering must stay: guard → alert → return → confirm → set (the guard's position is unchanged; only the silence is fixed)"
|
|
);
|
|
assert.strictEqual(
|
|
(code.match(/schedulerDeleteInFlight = true;/g) || []).length,
|
|
1,
|
|
"the guard must be set exactly once — still only after confirm()"
|
|
);
|
|
});
|
|
|
|
test("flight start disables the rendered delete buttons through the one canonical selector", () => {
|
|
const code = deleteWindow.replace(/\/\/[^\n]*/g, "");
|
|
const setAt = code.indexOf("schedulerDeleteInFlight = true;");
|
|
const fetchAt = code.indexOf("fetchWithServerActionToken(`/api/scheduler/");
|
|
assert.notStrictEqual(fetchAt, -1, "the token-gated DELETE fetch must stay");
|
|
const disableAt = code.indexOf("schedulerTasksList.querySelectorAll('.scheduler-task-delete')", setAt);
|
|
assert.notStrictEqual(
|
|
disableAt,
|
|
-1,
|
|
"the disable must scope to schedulerTasksList with the SAME '.scheduler-task-delete' selector the click handlers bind through — one definition of the delete buttons"
|
|
);
|
|
const disabledAt = code.indexOf("btn.disabled = true;", disableAt);
|
|
assert.notStrictEqual(disabledAt, -1, "the disable must set the disabled property");
|
|
assert.ok(
|
|
disableAt > setAt && disableAt < fetchAt && disabledAt > setAt && disabledAt < fetchAt,
|
|
"the disable must run after the guard is set and before the DELETE fetch — the whole flight is covered, and a cancelled confirm disables nothing"
|
|
);
|
|
assert.ok(
|
|
code.slice(setAt, fetchAt).includes("if (schedulerTasksList) {"),
|
|
"the disable must be null-guarded on the list container"
|
|
);
|
|
});
|
|
|
|
test("the finally restores via a re-query, after the guard release", () => {
|
|
const code = deleteWindow.replace(/\/\/[^\n]*/g, "");
|
|
const finallyAt = code.indexOf("} finally {");
|
|
assert.notStrictEqual(finallyAt, -1, "the finally must stay");
|
|
const clearAt = code.indexOf("schedulerDeleteInFlight = false;", finallyAt);
|
|
assert.notStrictEqual(clearAt, -1, "the guard release must stay in the finally");
|
|
const restoreAt = code.indexOf("schedulerTasksList.querySelectorAll('.scheduler-task-delete')", clearAt);
|
|
assert.notStrictEqual(restoreAt, -1, "the restore must re-query the list inside the finally (never a captured NodeList)");
|
|
const enabledAt = code.indexOf("btn.disabled = false;", restoreAt);
|
|
assert.notStrictEqual(enabledAt, -1, "the restore must clear the disabled property");
|
|
assert.ok(
|
|
code.slice(clearAt).includes("if (schedulerTasksList) {"),
|
|
"the restore must be null-guarded on the list container"
|
|
);
|
|
assert.strictEqual(
|
|
(code.match(/schedulerDeleteInFlight = false;/g) || []).length,
|
|
1,
|
|
"the guard must be cleared exactly once — in the finally (the cancelled-confirm and failed-request paths can never leave it stuck)"
|
|
);
|
|
});
|
|
|
|
test("the prior fixes in this function are untouched", () => {
|
|
// adpanel:scheduler-fetch-bound (C6): the 20 s bound and the token flow.
|
|
assert.match(
|
|
deleteWindow,
|
|
/'schedulerDelete', \{ refreshBefore: true, timeoutMs: 20000 \}/,
|
|
"the schedulerDelete token flow with the 20000 bound must stay exactly as pinned by bot-scheduler-fetch-bounds.test.js"
|
|
);
|
|
// The failure alert stays gated on the scene being on screen.
|
|
assert.match(
|
|
deleteWindow,
|
|
/if \(schedulerModalIsActive\(\)\) alert\('Failed to delete task: ' \+ \(err\.message \|\| err\)\);/,
|
|
"the failure alert's schedulerModalIsActive() gating must stay"
|
|
);
|
|
// Success still reloads the list.
|
|
assert.match(deleteWindow, /\n\s*loadSchedulerTasks\(\);/, "the success path must still reload the tasks list");
|
|
});
|
|
|
|
// ── Behavioral: drive the REAL sliced deleteSchedulerTask in a vm sandbox ───
|
|
|
|
function extractSlices() {
|
|
return [
|
|
stateDecl[0].trim(),
|
|
// The REAL deleteSchedulerTask, comments included (harmless in JS).
|
|
deleteWindow,
|
|
].join("\n\n");
|
|
}
|
|
|
|
const PROLOGUE = `
|
|
"use strict";
|
|
const __h = globalThis.__h;
|
|
|
|
// Module-scope DOM binding the real deleteSchedulerTask closes over.
|
|
const schedulerTasksList = globalThis.__tasksList;
|
|
const bot = "srv-test";
|
|
|
|
function hasPerm() { return __h.hasPerm; }
|
|
function confirm(msg) { __h.confirms.push(String(msg)); return __h.confirmAnswer; }
|
|
function alert(msg) { __h.alerts.push(String(msg)); }
|
|
function schedulerModalIsActive() { return __h.modalActive; }
|
|
|
|
// The token/POST boundary: recorded, never real network.
|
|
async function fetchWithServerActionToken(url, options, tokenKey, opts) {
|
|
__h.deletes.push({ url: String(url), method: options && options.method, tokenKey: String(tokenKey), opts });
|
|
return __h.deleteResponder();
|
|
}
|
|
|
|
// Mimics the real loadSchedulerTasks' load-bearing synchronous property:
|
|
// the list swap to the loading markup happens BEFORE the first await, so
|
|
// by the time deleteSchedulerTask's finally runs the old delete buttons are
|
|
// already detached. The eventual re-render ships fresh enabled buttons.
|
|
function loadSchedulerTasks() {
|
|
schedulerTasksList.innerHTML = '<div class="scheduler-loading">Loading tasks...</div>';
|
|
return Promise.resolve().then(() => {
|
|
schedulerTasksList.buttons = __h.reRenderButtons();
|
|
});
|
|
}
|
|
`;
|
|
|
|
const EPILOGUE = `
|
|
globalThis.__snapGuard = () => schedulerDeleteInFlight;
|
|
globalThis.__setGuard = (v) => { schedulerDeleteInFlight = v; };
|
|
globalThis.__deleteSchedulerTask = deleteSchedulerTask;
|
|
`;
|
|
|
|
function makeButton(id) {
|
|
return { disabled: false, dataset: { id: String(id) } };
|
|
}
|
|
|
|
function makeHarness() {
|
|
const hooks = {
|
|
alerts: [],
|
|
confirms: [],
|
|
deletes: [],
|
|
hasPerm: true,
|
|
confirmAnswer: true,
|
|
modalActive: true,
|
|
deleteResponder: () => ({ ok: true, status: 200, json: async () => ({ ok: true }) }),
|
|
reRenderButtons: () => [],
|
|
};
|
|
const tasksList = {
|
|
__innerHTML: "",
|
|
buttons: [],
|
|
set innerHTML(v) { this.__innerHTML = String(v); this.buttons = []; },
|
|
get innerHTML() { return this.__innerHTML; },
|
|
querySelectorAll(sel) {
|
|
return sel === ".scheduler-task-delete" ? this.buttons.slice() : [];
|
|
},
|
|
};
|
|
const sandbox = {
|
|
setTimeout,
|
|
clearTimeout,
|
|
console,
|
|
__h: hooks,
|
|
__tasksList: tasksList,
|
|
};
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(PROLOGUE + "\n\n" + extractSlices() + "\n\n" + EPILOGUE, sandbox, {
|
|
timeout: 4000,
|
|
filename: "bot-scheduler-delete-cue-sandbox.js",
|
|
});
|
|
return { sandbox, hooks, list: tasksList };
|
|
}
|
|
|
|
async function flush() {
|
|
for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
}
|
|
|
|
test("a click while a delete is in flight alerts and never opens confirm or POSTs", async () => {
|
|
const h = makeHarness();
|
|
h.sandbox.__setGuard(true);
|
|
|
|
await h.sandbox.__deleteSchedulerTask("task-b");
|
|
await flush();
|
|
|
|
assert.deepStrictEqual(
|
|
h.hooks.alerts,
|
|
["A delete is already in progress — please wait."],
|
|
"the refused click must surface the in-flight alert — never silence"
|
|
);
|
|
assert.deepStrictEqual(h.hooks.confirms, [], "the refused delete must not open a second confirm");
|
|
assert.deepStrictEqual(h.hooks.deletes, [], "the refused delete must not reach the wire");
|
|
assert.strictEqual(h.sandbox.__snapGuard(), true, "the held guard must stay held");
|
|
});
|
|
|
|
test("a cancelled confirm leaves the guard, the buttons and the wire untouched", async () => {
|
|
const h = makeHarness();
|
|
h.list.buttons = [makeButton("a"), makeButton("b")];
|
|
h.hooks.confirmAnswer = false;
|
|
|
|
await h.sandbox.__deleteSchedulerTask("task-a");
|
|
await flush();
|
|
|
|
assert.deepStrictEqual(h.hooks.confirms, [CONFIRM_LITERAL], "the confirm dialog must still be offered");
|
|
assert.deepStrictEqual(h.hooks.deletes, [], "a cancelled confirm must never reach the wire");
|
|
assert.strictEqual(h.sandbox.__snapGuard(), false, "the guard is set only after confirm() passes");
|
|
assert.deepStrictEqual(
|
|
h.list.buttons.map((b) => b.disabled),
|
|
[false, false],
|
|
"a cancelled confirm must not disable anything — the flight never started"
|
|
);
|
|
});
|
|
|
|
test("flight start disables every rendered delete button until the request settles", async () => {
|
|
const h = makeHarness();
|
|
h.list.buttons = [makeButton("a"), makeButton("b"), makeButton("c")];
|
|
let release;
|
|
h.hooks.deleteResponder = () => new Promise((resolve) => { release = resolve; });
|
|
|
|
const flight = h.sandbox.__deleteSchedulerTask("task-a");
|
|
await flush();
|
|
|
|
assert.deepStrictEqual(h.hooks.confirms, [CONFIRM_LITERAL]);
|
|
assert.strictEqual(h.hooks.deletes.length, 1, "exactly one token-gated DELETE");
|
|
assert.strictEqual(h.hooks.deletes[0].method, "DELETE");
|
|
assert.strictEqual(h.hooks.deletes[0].tokenKey, "schedulerDelete");
|
|
assert.strictEqual(h.hooks.deletes[0].opts.timeoutMs, 20000, "the 20 s bound must ride the request");
|
|
assert.deepStrictEqual(
|
|
h.list.buttons.map((b) => b.disabled),
|
|
[true, true, true],
|
|
"EVERY delete button must be disabled for the flight, not just the clicked one — the guard is fleet-wide"
|
|
);
|
|
assert.strictEqual(h.sandbox.__snapGuard(), true);
|
|
|
|
release({ ok: true, status: 200, json: async () => ({ ok: true }) });
|
|
await flight;
|
|
await flush();
|
|
assert.strictEqual(h.sandbox.__snapGuard(), false, "the guard releases when the flight settles");
|
|
});
|
|
|
|
test("a failed delete re-enables the still-rendered buttons and alerts the failure", async () => {
|
|
const h = makeHarness();
|
|
h.list.buttons = [makeButton("a"), makeButton("b")];
|
|
h.hooks.deleteResponder = () => ({
|
|
ok: false,
|
|
status: 500,
|
|
json: async () => ({ error: "node busy" }),
|
|
});
|
|
|
|
await h.sandbox.__deleteSchedulerTask("task-a");
|
|
await flush();
|
|
|
|
assert.ok(
|
|
h.hooks.alerts.includes("Failed to delete task: node busy"),
|
|
"the failure alert must still fire (scene active)"
|
|
);
|
|
assert.strictEqual(h.sandbox.__snapGuard(), false);
|
|
assert.deepStrictEqual(
|
|
h.list.buttons.map((b) => b.disabled),
|
|
[false, false],
|
|
"on failure the list was never swapped, so the same nodes must be re-enabled"
|
|
);
|
|
});
|
|
|
|
test("a successful delete: the finally is a no-op over the swapped list, the re-render ships enabled buttons", async () => {
|
|
const h = makeHarness();
|
|
const oldButtons = [makeButton("a"), makeButton("b")];
|
|
h.list.buttons = oldButtons;
|
|
const freshButtons = [makeButton("c")];
|
|
h.hooks.reRenderButtons = () => freshButtons;
|
|
|
|
await h.sandbox.__deleteSchedulerTask("task-a");
|
|
await flush();
|
|
|
|
assert.deepStrictEqual(h.hooks.alerts, [], "no failure alert on success");
|
|
assert.strictEqual(h.sandbox.__snapGuard(), false);
|
|
// The synchronous prologue of the real loadSchedulerTasks swapped the list
|
|
// before the finally ran: the restore's re-query found NOTHING to re-enable
|
|
// (the old buttons are detached and must stay untouched), and the eventual
|
|
// re-render's fresh buttons ship enabled.
|
|
assert.deepStrictEqual(
|
|
oldButtons.map((b) => b.disabled),
|
|
[true, true],
|
|
"the restore must not resurrect detached nodes — they were disabled when detached and stay that way, harmlessly"
|
|
);
|
|
assert.deepStrictEqual(
|
|
h.list.buttons,
|
|
freshButtons,
|
|
"the list now holds the re-render's fresh buttons"
|
|
);
|
|
assert.deepStrictEqual(
|
|
h.list.buttons.map((b) => b.disabled),
|
|
[false],
|
|
"the re-rendered delete buttons must be enabled again"
|
|
);
|
|
});
|
|
|
|
test("a mid-flight refresh re-render followed by a click lands on the guard's alert", async () => {
|
|
// The load-bearing reason the guard needed a voice: the refresh button can
|
|
// re-render fresh ENABLED delete buttons while a delete is still in flight
|
|
// (renderSchedulerTasks is untouched by this fix), so the next click reaches
|
|
// the guard — which must alert, not drop the click in silence.
|
|
const h = makeHarness();
|
|
h.list.buttons = [makeButton("a")];
|
|
let release;
|
|
h.hooks.deleteResponder = () => new Promise((resolve) => { release = resolve; });
|
|
|
|
const flight = h.sandbox.__deleteSchedulerTask("task-a");
|
|
await flush();
|
|
assert.deepStrictEqual(h.list.buttons.map((b) => b.disabled), [true]);
|
|
|
|
// User hits refresh mid-flight: fresh enabled buttons replace the list.
|
|
h.hooks.reRenderButtons = () => [makeButton("fresh-1"), makeButton("fresh-2")];
|
|
h.list.buttons = h.hooks.reRenderButtons();
|
|
assert.deepStrictEqual(
|
|
h.list.buttons.map((b) => b.disabled),
|
|
[false, false],
|
|
"a refresh mid-flight re-renders enabled buttons (renderSchedulerTasks is unchanged by this fix)"
|
|
);
|
|
|
|
// The click on the fresh button reaches the fleet-wide guard.
|
|
await h.sandbox.__deleteSchedulerTask("task-fresh");
|
|
await flush();
|
|
assert.deepStrictEqual(
|
|
h.hooks.alerts,
|
|
["A delete is already in progress — please wait."],
|
|
"the guard must voice itself for a click on a re-rendered button"
|
|
);
|
|
assert.deepStrictEqual(h.hooks.deletes.length, 1, "still exactly one DELETE on the wire");
|
|
|
|
release({ ok: true, status: 200, json: async () => ({ ok: true }) });
|
|
await flight;
|
|
await flush();
|
|
assert.strictEqual(h.sandbox.__snapGuard(), false);
|
|
});
|