"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 = '