460 lines
20 KiB
JavaScript
460 lines
20 KiB
JavaScript
"use strict";
|
|
|
|
// Source-level pin for the scheduler-scene bounded fetches in bot.js
|
|
// (adpanel:scheduler-fetch-bound).
|
|
//
|
|
// Three scheduler-scene data fetches were bare `fetch()` calls: a stalled
|
|
// response wedged the scene's guards — "Loading tasks..." plus a spinning
|
|
// refresh forever, schedulerCreateInFlight/schedulerDeleteInFlight (disabled
|
|
// buttons) until the browser killed the socket (~300s), and the planner
|
|
// preview stuck on "Loading…". They now go through the established
|
|
// fetchWithTimeout helper (the checkSchedulerStatus pattern).
|
|
//
|
|
// fetchWithServerActionToken's inner fetch is deliberately OPT-IN bounded
|
|
// (opts.timeoutMs, undefined default = unbounded): several of its call sites
|
|
// (file extract, archive, backup create/restore, reinstall) legitimately
|
|
// answer only after a minutes-long daemon job, so no blanket cap may exist.
|
|
// The two scheduler token-gated call sites pass timeoutMs: 20000 and the
|
|
// backups delete passes 360000 just above its relay's 330s budget (section
|
|
// f), and the bound applies PER ATTEMPT so the 403-token retry gets a fresh
|
|
// window.
|
|
//
|
|
// fetchPerms' permissions GET was the uncovered arm of the same doctrine: it
|
|
// runs INSIDE the bounded scheduler create/delete flows (ensureServerAction
|
|
// Token's refreshBefore arm), so a stalled response still wedged the in-flight
|
|
// guards on a bare fetch. It is now bounded at 15000 (generous for a small
|
|
// JSON GET); the abort lands in its existing catch, whose null every caller
|
|
// already tolerates (the token mint falls back to the cached token, the
|
|
// bootstrap step logs and moves on).
|
|
//
|
|
// bot.js is one IIFE with structure-pin precedent (the bot-*.test.js files
|
|
// read the source and assert on well-anchored windows) — never require() it.
|
|
|
|
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);
|
|
}
|
|
|
|
// ── (a) tasks list: fetchWithTimeout at 15000 ───────────────────────────────
|
|
|
|
const loadTasksWindow = sourceWindow(
|
|
botSrc,
|
|
"async function loadSchedulerTasks() {",
|
|
"function renderSchedulerTasks(",
|
|
"loadSchedulerTasks"
|
|
);
|
|
|
|
test("loadSchedulerTasks fetches the tasks list through fetchWithTimeout at 15000", () => {
|
|
assert.match(
|
|
loadTasksWindow,
|
|
/await fetchWithTimeout\(`\/api\/scheduler\/\$\{encodeURIComponent\(bot\)\}\/tasks`, \{\}, 15000\)/,
|
|
"the tasks-list fetch must be bounded (a stall must not leave 'Loading tasks...' and a spinning refresh up forever)"
|
|
);
|
|
assert.ok(
|
|
!/^[ \t]*const res = await fetch\(`\/api\/scheduler/m.test(loadTasksWindow),
|
|
"no bare fetch may remain for the tasks list"
|
|
);
|
|
});
|
|
|
|
test("loadSchedulerTasks maps an aborted (timed-out) fetch to the plain failure text", () => {
|
|
// The existing catch/finally already reset the spinner and render an error
|
|
// row; an AbortError just carried the browser's opaque message.
|
|
assert.match(
|
|
loadTasksWindow,
|
|
/err\?\.name === 'AbortError' \|\| err\?\.name === 'TimeoutError' \? 'Failed to load tasks' : \(err\.message \|\| 'Failed to load tasks'\)/,
|
|
"the abort must surface as the existing 'Failed to load tasks' text, not the browser's opaque abort message"
|
|
);
|
|
// The spinner reset stays in the finally so an abort cannot wedge it.
|
|
assert.match(
|
|
loadTasksWindow,
|
|
/finally \{\s*\n\s*if \(seq === schedulerTasksLoadSeq && schedulerRefreshBtn\) \{\s*\n\s*schedulerRefreshBtn\.classList\.remove\('spinning'\);/,
|
|
"the finally must keep resetting the refresh button's spinning class"
|
|
);
|
|
});
|
|
|
|
test("Scheduler aborts a stalled JSON body and releases the refresh spinner", async () => {
|
|
const transport = sourceWindow(botSrc, "function fetchWithTimeout(", "function compareSemverDesc(", "fetchWithTimeout");
|
|
const controller = new AbortController();
|
|
const tasksList = { innerHTML: "" };
|
|
const loading = new Set();
|
|
let readingBody = false;
|
|
const pending = vm.runInNewContext(`${transport}\n${loadTasksWindow}\nloadSchedulerTasks()`, {
|
|
bot: "fixture",
|
|
schedulerTasksList: tasksList,
|
|
schedulerTasksLoadSeq: 0,
|
|
schedulerRefreshBtn: { classList: { add: name => loading.add(name), remove: name => loading.delete(name) } },
|
|
AbortSignal: { timeout(ms) { assert.equal(ms, 15000); return controller.signal; } },
|
|
fetch: async (_url, { signal }) => ({
|
|
ok: true,
|
|
json() {
|
|
readingBody = true;
|
|
return new Promise((_resolve, reject) => {
|
|
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
|
});
|
|
},
|
|
}),
|
|
escapeHtml: String,
|
|
console: { error() {} },
|
|
});
|
|
await new Promise(setImmediate);
|
|
assert.equal(readingBody, true);
|
|
assert.equal(loading.has("spinning"), true);
|
|
controller.abort(new DOMException("deadline", "TimeoutError"));
|
|
await pending;
|
|
assert.equal(loading.has("spinning"), false);
|
|
assert.match(tasksList.innerHTML, /Failed to load tasks/);
|
|
});
|
|
|
|
// ── (b) fetchWithServerActionToken: opt-in per-attempt bound ────────────────
|
|
|
|
const tokenFetchWindow = sourceWindow(
|
|
botSrc,
|
|
"async function fetchWithServerActionToken(url, options = {}, tokenKey, opts = {}) {",
|
|
"async function writeServerFileWithActionToken(",
|
|
"fetchWithServerActionToken"
|
|
);
|
|
|
|
test("runRequest's inner fetch is fetchWithTimeout-wrapped when opts.timeoutMs is set", () => {
|
|
assert.match(
|
|
tokenFetchWindow,
|
|
/const \{ refreshBefore = false, retryOnInvalidToken = true, timeoutMs \} = opts;/,
|
|
"timeoutMs must be an opt-in opts field with NO default (undefined = unbounded): extract, archive, backup create/restore and reinstall answer only after minutes-long daemon jobs, so a blanket cap would break them"
|
|
);
|
|
assert.match(
|
|
tokenFetchWindow,
|
|
/return timeoutMs\s*\n\s*\? fetchWithTimeout\(url, \{ \.\.\.options, headers \}, timeoutMs\)\s*\n\s*: fetch\(url, \{ \.\.\.options, headers \}\);/,
|
|
"the inner fetch must route through fetchWithTimeout(url, { ...options, headers }, timeoutMs) exactly when timeoutMs is set"
|
|
);
|
|
});
|
|
|
|
test("the token retry ladder is unchanged: one 403-refresh retry, bounded per attempt", () => {
|
|
// Each attempt goes through runRequest, so the bound applies per attempt —
|
|
// a 403-token retry gets a fresh timeout window.
|
|
assert.match(
|
|
tokenFetchWindow,
|
|
/if \(retryOnInvalidToken && response\.status === 403\) \{/,
|
|
"the 403 gate must stay"
|
|
);
|
|
assert.match(
|
|
tokenFetchWindow,
|
|
/isInvalidActionTokenErrorPayload\(errData\)/,
|
|
"the ACTION_TOKEN_INVALID payload check must stay"
|
|
);
|
|
const attempts = tokenFetchWindow.match(/await runRequest\(/g) || [];
|
|
assert.strictEqual(
|
|
attempts.length,
|
|
2,
|
|
"runRequest must be awaited exactly twice in the whole ladder — the initial attempt plus at most one 403 refresh retry"
|
|
);
|
|
});
|
|
|
|
test("only the scheduler token-gated call sites opt into the 20000 bound", () => {
|
|
const deleteWindow = sourceWindow(
|
|
botSrc,
|
|
"async function deleteSchedulerTask(taskId) {",
|
|
"async function createSchedulerTask() {",
|
|
"deleteSchedulerTask"
|
|
);
|
|
assert.match(
|
|
deleteWindow,
|
|
/'schedulerDelete', \{ refreshBefore: true, timeoutMs: 20000 \}/,
|
|
"the scheduler delete must pass timeoutMs: 20000 — a stall must not hold schedulerDeleteInFlight (disabled delete buttons) until the browser kills the socket"
|
|
);
|
|
|
|
const createWindow = sourceWindow(
|
|
botSrc,
|
|
"async function createSchedulerTask() {",
|
|
"function resetSchedulerForm() {",
|
|
"createSchedulerTask"
|
|
);
|
|
assert.match(
|
|
createWindow,
|
|
/'schedulerCreate', \{ refreshBefore: true, timeoutMs: 20000 \}/,
|
|
"the scheduler create must pass timeoutMs: 20000 — a stall must not hold schedulerCreateInFlight and the 'Creating...' button"
|
|
);
|
|
|
|
// The long-running token-gated operations keep the unbounded default: their
|
|
// call sites pass no timeoutMs (the daemon only answers when the job ends).
|
|
const extractAt = botSrc.indexOf("fetchWithServerActionToken(url, requestOptions, 'fileExtract')");
|
|
assert.notStrictEqual(extractAt, -1, "the apiExtract call site must stay");
|
|
assert.strictEqual(
|
|
botSrc.slice(extractAt, extractAt + 120).includes("timeoutMs"),
|
|
false,
|
|
"apiExtract must NOT pass timeoutMs — archive extraction legitimately runs longer than any sane fetch bound"
|
|
);
|
|
const archiveAt = botSrc.indexOf("fetchWithServerActionToken(url, requestOptions, 'fileArchive')");
|
|
assert.notStrictEqual(archiveAt, -1, "the apiArchive call site must stay");
|
|
assert.strictEqual(
|
|
botSrc.slice(archiveAt, archiveAt + 120).includes("timeoutMs"),
|
|
false,
|
|
"apiArchive must NOT pass timeoutMs — archiving legitimately runs longer than any sane fetch bound"
|
|
);
|
|
});
|
|
|
|
// ── (c) plannerRequest: fetchWithTimeout at 20000 ───────────────────────────
|
|
|
|
const plannerWindow = sourceWindow(
|
|
botSrc,
|
|
"function plannerRequest(path = '', options = {}) {",
|
|
"function derivePlannerTitle(",
|
|
"plannerRequest"
|
|
);
|
|
|
|
test("plannerRequest fetches through fetchWithTimeout at 20000 with its contract intact", () => {
|
|
assert.match(
|
|
plannerWindow,
|
|
/fetchWithTimeout\(`\$\{PLANNER_API_BASE\}\$\{path\}`, options, 20000\)/,
|
|
"the planner fetch must be bounded (a stall must not pin 'Loading…' or a drag/mutation guard up forever)"
|
|
);
|
|
// The response contract the callers key on is unchanged: the wrapper only
|
|
// bounds the transport, the .then body still maps 401/status/code.
|
|
assert.match(plannerWindow, /if \(response\.status === 401\) \{/, "the 401 session-expiry branch must stay");
|
|
assert.match(plannerWindow, /if \(!response\.ok\) \{/, "the !ok status mapping must stay");
|
|
assert.match(plannerWindow, /failure\.status = response\.status;/, "the .status contract must stay");
|
|
assert.match(plannerWindow, /failure\.code = err\.code \|\| null;/, "the .code contract must stay");
|
|
});
|
|
|
|
// ── (d) fetchPerms: the token-mint arm, bounded at 15000 ────────────────────
|
|
|
|
const fetchPermsWindow = sourceWindow(
|
|
botSrc,
|
|
"async function fetchPerms(opts = {}) {",
|
|
"const CONSOLE_COMMAND_HISTORY_LIMIT = 32;",
|
|
"fetchPerms"
|
|
);
|
|
|
|
test("fetchPerms fetches permissions through fetchWithTimeout at 15000", () => {
|
|
assert.match(
|
|
fetchPermsWindow,
|
|
/await fetchWithTimeout\(`\/api\/servers\/\$\{encodeURIComponent\(bot\)\}\/permissions`, \{ cache: 'no-store' \}, 15000\)/,
|
|
"the permissions GET must be bounded — it runs INSIDE the bounded scheduler create/delete flows (ensureServerActionToken's refreshBefore arm), so a stalled response would still wedge the in-flight guards"
|
|
);
|
|
assert.ok(
|
|
!/^[ \t]*const r = await fetch\(`/m.test(fetchPermsWindow),
|
|
"no bare fetch may remain for the permissions GET"
|
|
);
|
|
});
|
|
|
|
test("fetchPerms tolerates the bound's abort: the existing catch maps it to the null return callers already handle", () => {
|
|
assert.match(
|
|
fetchPermsWindow,
|
|
/catch \(e\) \{/,
|
|
"the catch must stay — the AbortError lands there, not in a caller"
|
|
);
|
|
assert.match(
|
|
fetchPermsWindow,
|
|
/return null;/,
|
|
"the catch must keep returning null — ensureServerActionToken falls back to the cached token and the bootstrap step logs and moves on, so no caller wedges on the abort"
|
|
);
|
|
});
|
|
|
|
// ── (e) the model-selector populates: the three shared AI-scene fetches ─────
|
|
//
|
|
// The scheduler scene's agent_prompt populate (populateSchedulerAiModelSelector)
|
|
// fans out into three shared AI-scene fetches — the saved-selection read, the
|
|
// keys read, and the per-provider models read. All three were bare `fetch()`
|
|
// calls: a stalled response left the selector wedged on "Loading models..."
|
|
// (retriable, no guard held, but unbounded — the same class the finding-4 fix
|
|
// closed for the rest of the scene). They now ride fetchWithTimeout at 15000.
|
|
//
|
|
// Abort mapping (deliberate): every surrounding catch already swallows the
|
|
// thrown AbortError and degrades ('' / the cached keys / []), so no raw
|
|
// "aborted" text can reach the user and no AbortError-name mapping like
|
|
// loadSchedulerTasks' is needed — the pins below hold those degradations in
|
|
// place so a future catch "improvement" cannot surface the opaque message.
|
|
|
|
const selectionWindow = sourceWindow(
|
|
botSrc,
|
|
"async function loadSelectedAiModelFromBackend() {",
|
|
"function queueSelectedAiModelBackendSave(",
|
|
"loadSelectedAiModelFromBackend"
|
|
);
|
|
|
|
test("loadSelectedAiModelFromBackend fetches the saved selection through fetchWithTimeout at 15000", () => {
|
|
assert.match(
|
|
selectionWindow,
|
|
/await fetchWithTimeout\('\/api\/ai\/selection', \{ cache: 'no-store' \}, 15000\)/,
|
|
"the saved-selection GET must be bounded — populateSchedulerAiModelSelector awaits it before its seq-guard re-check"
|
|
);
|
|
assert.ok(
|
|
!/^[ \t]*const response = await fetch\('/m.test(selectionWindow),
|
|
"no bare fetch may remain for the saved selection"
|
|
);
|
|
assert.match(
|
|
selectionWindow,
|
|
/catch \{\s*\n\s*return '';/,
|
|
"the existing catch must keep returning '' — it already swallows the AbortError, so no raw abort text can surface"
|
|
);
|
|
});
|
|
|
|
const aiKeysWindow = sourceWindow(
|
|
botSrc,
|
|
"async function loadAiKeysFromBackend() {",
|
|
"async function saveAiProviderConfig(",
|
|
"loadAiKeysFromBackend"
|
|
);
|
|
|
|
test("loadAiKeysFromBackend fetches the keys through fetchWithTimeout at 15000", () => {
|
|
assert.match(
|
|
aiKeysWindow,
|
|
/await fetchWithTimeout\('\/api\/ai\/keys', \{\}, 15000\)/,
|
|
"the keys GET must be bounded — it gates which provider optgroups the model-selector populate renders"
|
|
);
|
|
assert.ok(
|
|
!/^[ \t]*const response = await fetch\('/m.test(aiKeysWindow),
|
|
"no bare fetch may remain for the keys GET"
|
|
);
|
|
assert.match(
|
|
aiKeysWindow,
|
|
/catch \{\s*\n\s*return aiKeysCache \|\| \{\};/,
|
|
"the existing catch must keep falling back to the cached keys — it already swallows the AbortError"
|
|
);
|
|
});
|
|
|
|
const aiModelsWindow = sourceWindow(
|
|
botSrc,
|
|
"async function fetchModels(provider, { forceRefresh = false } = {}) {",
|
|
"function closeAiModelDropdown(",
|
|
"fetchModels"
|
|
);
|
|
|
|
test("fetchModels fetches the provider models through fetchWithTimeout at 15000", () => {
|
|
assert.match(
|
|
aiModelsWindow,
|
|
/await window\.adpanelAgentLive\.queueModelDiscovery\(\(\) =>\s*fetchWithTimeout\(`\/api\/ai\/models\/\$\{encodeURIComponent\(provider\)\}`, \{\}, 15000\)\)/,
|
|
"the per-provider models GET must be concurrency-limited and individually time-bounded"
|
|
);
|
|
assert.ok(
|
|
!/^[ \t]*const response = await fetch\(`/m.test(aiModelsWindow),
|
|
"no bare fetch may remain for the models GET"
|
|
);
|
|
assert.match(
|
|
aiModelsWindow,
|
|
/console\.warn\(`\[AI\] Failed to fetch models for \$\{provider\}:`, err\);\s*\n\s*return \[\];/,
|
|
"the existing catch must keep degrading to [] ('No models available', retriable) — never a raw abort message"
|
|
);
|
|
});
|
|
|
|
const loadBackupsWindow = sourceWindow(
|
|
botSrc, "async function loadBackups() {", "function renderBackupsList(", "loadBackups"
|
|
);
|
|
|
|
test("a stalled backups response body hits the deadline and releases the refresh spinner", async () => {
|
|
const controller = new AbortController();
|
|
const backupsList = { innerHTML: "" };
|
|
const loading = new Set();
|
|
let bodyStarted = false;
|
|
const pending = vm.runInNewContext(`${loadBackupsWindow}\nloadBackups()`, {
|
|
bot: "alpha",
|
|
backupsList,
|
|
backupsLoadSeq: 0,
|
|
backupsRefreshBtn: { classList: { add: (name) => loading.add(name), remove: (name) => loading.delete(name) } },
|
|
AbortSignal: { timeout: (ms) => {
|
|
assert.equal(ms, 15000);
|
|
return controller.signal;
|
|
} },
|
|
fetch: async (_url, { signal }) => ({
|
|
ok: true,
|
|
json() {
|
|
bodyStarted = true;
|
|
return new Promise((_resolve, reject) => {
|
|
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
|
});
|
|
},
|
|
}),
|
|
console: { error() {} },
|
|
});
|
|
|
|
await new Promise(setImmediate);
|
|
assert.equal(bodyStarted, true);
|
|
assert.equal(loading.has("is-loading"), true);
|
|
controller.abort();
|
|
await pending;
|
|
assert.equal(loading.has("is-loading"), false);
|
|
assert.match(backupsList.innerHTML, /Failed to load backups/);
|
|
});
|
|
|
|
// ── (f) deleteBackup: bounded just above the relay's 330s delete budget ─────
|
|
//
|
|
// The backups delete was the one token-gated call site holding an in-flight
|
|
// guard with no bound: backupOpInFlight is set before the fetch and cleared
|
|
// only in finally, and both Restore and Delete silently return while it is
|
|
// set — so a stalled response (hung daemon, half-open TCP after a node
|
|
// suspend) wedged every further Restore/Delete click until the browser killed
|
|
// the socket. Delete is NOT a candidate for the unbounded exemption list
|
|
// (that would keep the stall forever): its server side is fully budgeted —
|
|
// the daemon's own backupDeleteCallerWaitBudget is 5 * time.Minute and the
|
|
// panel's delete relay dials with timeoutMs: 330000 (daemon budget + 30s
|
|
// slack, nodes.js) — so the client bound is 360000 = 330000 + the same 30s
|
|
// slack again, and can never abort a legitimate delete. Create/restore stay
|
|
// unbounded by doctrine: their daemon jobs legitimately run for minutes and
|
|
// their relays budget them server-side (630000 / 1830000).
|
|
|
|
const deleteBackupWindow = sourceWindow(
|
|
botSrc,
|
|
"async function deleteBackup(id) {",
|
|
"function openBackupsModal() {",
|
|
"deleteBackup"
|
|
);
|
|
|
|
test("deleteBackup's token fetch is bounded just above the relay's 330s delete budget", () => {
|
|
assert.match(
|
|
deleteBackupWindow,
|
|
/'backupDelete', \{ refreshBefore: true, timeoutMs: 360000 \}/,
|
|
"the delete must pass timeoutMs: 360000 — a stall must not hold backupOpInFlight (the silent Restore/Delete guard) until the browser kills the socket; 360000 = the relay's own 330000 budget + 30s slack, so the bound can never abort a legitimate delete"
|
|
);
|
|
assert.match(
|
|
deleteBackupWindow,
|
|
/\/\/ adpanel:backups-delete-fetch-bound — /,
|
|
"the bound must carry the adpanel comment convention documenting the constraint"
|
|
);
|
|
});
|
|
|
|
test("deleteBackup maps deadline errors to a plain timeout notice and keeps the finally release", () => {
|
|
assert.match(
|
|
deleteBackupWindow,
|
|
/err\?\.name === 'AbortError' \|\| err\?\.name === 'TimeoutError' \? 'Request timed out\. Refresh the list to check whether it completed\.' : \(err\.message \|\| err\)/,
|
|
"the abort must be translated to a plain timeout notice — never the browser's opaque abort message (same AbortError-to-plain-text handling as the backups loader's catch)"
|
|
);
|
|
assert.match(
|
|
deleteBackupWindow,
|
|
/'Failed to delete backup: ' \+ message/,
|
|
"the alert's failure prefix must stay"
|
|
);
|
|
assert.match(
|
|
deleteBackupWindow,
|
|
/finally \{\s*\n\s*backupOpInFlight = false;/,
|
|
"the guard release must stay in finally so an abort can never stick backupOpInFlight"
|
|
);
|
|
});
|
|
|
|
test("backup create/restore stay exemption-list-unbounded by doctrine", () => {
|
|
const restoreAt = botSrc.indexOf("}, 'backupRestore', { refreshBefore: true });");
|
|
assert.notStrictEqual(restoreAt, -1, "the restore call site must stay in its current shape");
|
|
assert.strictEqual(
|
|
botSrc.slice(restoreAt, restoreAt + 120).includes("timeoutMs"),
|
|
false,
|
|
"restore must NOT pass timeoutMs — the restore daemon job legitimately runs for minutes (its relay budgets 1830000 server-side)"
|
|
);
|
|
const createAt = botSrc.indexOf("}, 'backupCreate');");
|
|
assert.notStrictEqual(createAt, -1, "the create call site must stay in its current shape");
|
|
assert.strictEqual(
|
|
botSrc.slice(createAt, createAt + 120).includes("timeoutMs"),
|
|
false,
|
|
"create must NOT pass timeoutMs — the create daemon job legitimately runs for minutes (its relay budgets 630000 server-side)"
|
|
);
|
|
});
|