"use strict"; // Source-level pin for the AI-scene bounded fetches in bot.js // (adpanel:ai-fetch-bound) — the follow-up round to the scheduler-fetch-bound // census: the LAST unbounded fetches in the AI scene. // // saveSelectedAiModelToBackendNow's POST was bare and awaited inside three // guarded flows — createSchedulerTask (holding schedulerCreateInFlight and // the disabled "Creating..." button), the planner agent-send flow and the // chat-send flow — so a stalled response wedged all of them until the browser // killed the socket (~300s) BEFORE their own bounded calls could start. The // bound lives inside the ONE helper (one-true-home: all three callers benefit // through it), at 15000 — generous for a tiny settings POST. The helper has // no catch of its own by contract: the timeout rejection flows into each // caller's existing .catch(() => false) (the agent-send site and the // scheduler planner_next_to_agent create pre-save additionally discriminate // the false and cancel the send/creation — pinned by // planner-send-agent-hardening.test.js and // bot-scheduler-model-save-fail-closed.test.js; the call-site count is // pinned there too, so the helper cannot fork or lose a caller). // // saveAiProviderConfig's POST is bounded at 20000 (adpanel:ai-connect-budget). // Model discovery has a shared worker deadline, including paginated catalogs; // the browser allows the RPC and time for panel authentication and persistence. // // The help-modal chat-CRUD helpers (list/read/create/save/delete/retitle) // were the remaining bare fetches in the scene. All six are bounded at 15000 // with their method/headers/body preserved verbatim. // // Abort mapping (deliberate): none of these catches surface the raw abort // text. Five of the six swallow the thrown AbortError and degrade to the // flow's normal falsy value ([] / null / false), so no raw "The user aborted // a request." can reach the user. loadChatFromDb is the ONE deliberate // exception (adpanel:scheduler-fetch-abort-cache): its abort is NOT smuggled // through as null, because its switch-path callers applyData(null) as an // empty thread AND cache [] for the chatId — an abort-as-null poisons // aiChatTranscriptCache and the next switch renders the empty thread // instantly. It returns the CHAT_LOAD_ABORTED sentinel instead, and the // callers map the abort to a friendly timeout toast while keeping the // current view; generic failures keep returning null exactly as before. The // pins below hold all of these degradations in place so a future catch // "improvement" cannot surface the opaque message or re-poison the cache. // // 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 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); } test("job submission no longer needs an awaited account-wide model save", () => { assert.doesNotMatch(botSrc, /async function saveSelectedAiModelToBackendNow\(/); }); // ── (b) queueSelectedAiModelBackendSave: the debounced background POST ────── const queueSelectionSaveWindow = sourceWindow( botSrc, "function queueSelectedAiModelBackendSave(", "function loadSelectedAiModelFromStorage(", "queueSelectedAiModelBackendSave" ); test("queueSelectedAiModelBackendSave POSTs through fetchWithTimeout at 15000", () => { assert.match( queueSelectionSaveWindow, /fetchWithTimeout\('\/api\/ai\/selection', \{\s*\n\s*method: 'POST',\s*\n\s*headers: \{ 'Content-Type': 'application\/json' \},\s*\n\s*body: JSON\.stringify\(\{ provider: providerId, model: modelName \}\)\s*\n\s*\}, 15000\)\.catch\(\(\) => \{ \}\)/, "the fire-and-forget background POST must be bounded with the same one-true-home treatment; the rejection lands in its .catch(() => {})" ); assert.ok( !/await fetch\(/.test(queueSelectionSaveWindow), "no bare await fetch may remain in the debounced variant" ); }); // ── (c) saveAiProviderConfig: bounded provider connection ─────────────────── const saveProviderConfigWindow = sourceWindow( botSrc, "async function saveAiProviderConfig(", "function hasConfiguredProvider(", "saveAiProviderConfig" ); test("saveAiProviderConfig keeps the action token and bounds the connect POST above the worker deadline", () => { const { DISCOVERY_TIMEOUT_MS } = require("../AgentWorker/budgets"); assert.ok(DISCOVERY_TIMEOUT_MS < 20000); assert.match( saveProviderConfigWindow, /await fetchWithTimeout\('\/api\/ai\/keys', \{\s*\n\s*method: 'POST',\s*\n\s*headers: \{\s*\n\s*'Content-Type': 'application\/json',\s*\n\s*'x-action-token': aiActionTokens\.setKey \|\| ''\s*\n\s*\},\s*\n\s*body: JSON\.stringify\(\{ provider, key, baseUrl, modelIds \}\)\s*\n\s*\}, 20000\)/, "the connect POST must stay bounded and token-gated, including when manual model IDs are supplied" ); assert.ok( !/await fetch\(/.test(saveProviderConfigWindow), "no bare await fetch may remain in the connect flow" ); // The AbortError lands in this catch, whose error is the flow's NORMAL // failure message: the click handler alerts result.error, so the user sees // 'Failed to connect provider', never the raw abort text. assert.match( saveProviderConfigWindow, /catch \{\s*\n\s*return \{ ok: false, error: 'Failed to connect provider' \};/, "the catch must keep mapping every transport failure (including the bound's abort) to the flow's normal error message" ); }); // ── (d) the help-modal chat CRUD: all six fetches bounded at 15000 ────────── const chatCrudStart = "async function loadChatsFromDb() {"; const chatCrudEnd = "async function saveChatHistory()"; const chatCrudWindow = sourceWindow(botSrc, chatCrudStart, chatCrudEnd, "chat CRUD"); test("every chat-CRUD fetch in the help-modal window is fetchWithTimeout-wrapped at 15000", () => { assert.match( chatCrudWindow, /await fetchWithTimeout\('\/api\/ai\/chats', \{\}, 15000\)/, "loadChatsFromDb's list GET must be bounded" ); assert.match( chatCrudWindow, /await fetchWithTimeout\('\/api\/ai\/chats', \{\s*\n\s*method: 'POST',\s*\n\s*headers: \{ 'Content-Type': 'application\/json' \},\s*\n\s*body: JSON\.stringify\(\{ title \}\)\s*\n\s*\}, 15000\)/, "createNewChat's create POST must be bounded" ); assert.match( chatCrudWindow, /await fetchWithTimeout\(`\/api\/ai\/chats\/\$\{Number\(chatId\)\}\$\{cursor\}`, \{\}, 15000\)/, "loadChatFromDb's read GET must be bounded" ); assert.match( chatCrudWindow, /await fetchWithTimeout\(`\/api\/ai\/chats\/\$\{Number\(chatId\)\}\/messages`, \{\s*\n\s*method: 'POST',\s*\n\s*headers: \{ 'Content-Type': 'application\/json' \},\s*\n\s*body: JSON\.stringify\(\{ role, content, thinking_time_ms: thinkingTimeMs, thinking_content: thinkingContent, model, image_data: imageData \}\)\s*\n\s*\}, 15000\)/, "saveMessageToDb's message POST must be bounded (body preserved verbatim)" ); assert.match( chatCrudWindow, /await fetchWithTimeout\(`\/api\/ai\/chats\/\$\{Number\(chatId\)\}`, \{ method: 'DELETE' \}, 15000\)/, "deleteChatFromDb's DELETE must be bounded" ); assert.match( chatCrudWindow, /await fetchWithTimeout\(`\/api\/ai\/chats\/\$\{Number\(chatId\)\}`, \{\s*\n\s*method: 'PUT',\s*\n\s*headers: \{ 'Content-Type': 'application\/json' \},\s*\n\s*body: JSON\.stringify\(\{ title \}\)\s*\n\s*\}, 15000\)/, "updateChatTitle's retitle PUT must be bounded" ); assert.ok( !/await fetch\(/.test(chatCrudWindow), "no bare await fetch may remain anywhere in the chat-CRUD window" ); }); test("the chat-CRUD catches keep swallowing the bound's abort into their normal falsy degradations", () => { // Abort mapping is deliberately absent here: no catch in this window // surfaces error text, so the AbortError degrades silently and no raw // abort message can reach the user. These pins hold that property. assert.match( chatCrudWindow, /catch \{\s*\n\s*aiChatsList = \[\];\s*\n\s*return \[\];/, "loadChatsFromDb must keep degrading to the empty list" ); assert.match( chatCrudWindow, /async function createNewChat[\s\S]*?catch \{\s*\n\s*return null;/, "createNewChat must keep degrading to null" ); assert.match( chatCrudWindow, /async function loadChatFromDb[\s\S]*?catch \(err\) \{\s*\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*if \(err\?\.name === 'AbortError' \|\| err\?\.name === 'TimeoutError'\) return CHAT_LOAD_ABORTED;[ \t]*\n[ \t]*return null;/, "loadChatFromDb must preserve the current thread on either deadline error, and still return null on unrelated failures" ); assert.match( chatCrudWindow, /async function saveMessageToDb[\s\S]*?catch \{\s*\n\s*return false;/, "saveMessageToDb must keep degrading to false (fire-and-forget persistence)" ); assert.match( chatCrudWindow, /async function deleteChatFromDb[\s\S]*?catch \{\s*\n\s*return false;/, "deleteChatFromDb must keep degrading to false (the flow refreshes the list regardless)" ); assert.match( chatCrudWindow, /async function updateChatTitle[\s\S]*?catch \{\s*\n\s*return false;/, "updateChatTitle must keep degrading to false" ); }); // ── (e) the abort sentinel and the switch-path callers that must honor it ─── // adpanel:scheduler-fetch-abort-cache — an abort during a chat load (the // 15000 bound; the fetch routinely queues 20-25s behind an open agent SSE // stream over HTTP/1.1) used to degrade to null, which switchToChat's // applyData renders as an empty thread AND caches [] for the chatId — the // next switch then showed the empty thread instantly from the cached fast // path. The sentinel keeps aborts distinguishable; the pins below hold the // callers to: no applyData, no cache write, keep the current view, surface // the friendly timeout text — while non-abort failures keep the pre-fix // behavior untouched. test("loadChatFromDb's abort sentinel is a truthy, identity-checkable value with an isChatLoadAborted predicate", () => { assert.match( chatCrudWindow, /const CHAT_LOAD_ABORTED = Object\.freeze\(\{ aborted: true \}\);\s*\n\s*function isChatLoadAborted\(result\) \{\s*\n\s*return result === CHAT_LOAD_ABORTED;\s*\n\s*\}/, "the sentinel and its identity predicate must live next to loadChatFromDb — callers distinguish aborts with isChatLoadAborted, never with truthiness (the sentinel IS truthy, unlike null)" ); }); test("switchToChat's no-cache path skips applyData and the cache on abort and surfaces the friendly timeout", () => { const switchToChatWindow = sourceWindow( botSrc, "async function switchToChat(chatId) {", "async function startNewChat() {", "switchToChat" ); assert.match( switchToChatWindow, /if \(isChatLoadAborted\(firstData\)\) \{\s*\n\s*if \(loadToken === aiChatLoadToken && aiCurrentChatId === chatId\) \{\s*\n\s*showStoreToast\('The chat request timed out\. Please try again\.', 'error', 6000\);\s*\n\s*\}\s*\n\s*return;\s*\n\s*\}\s*\n\s*if \(!applyData\(firstData\)\) return;/, "the no-cache load must return BEFORE applyData on abort (applyData would render an empty thread and cache [] for the chatId) and surface a friendly timeout toast — generic failures keep the pre-fix empty-thread behavior" ); assert.ok( !/The user aborted a request/.test(switchToChatWindow), "no raw abort text may surface — the abort maps to the friendly timeout string" ); }); test("switchToChat's post-run reconcile and cached-path revalidate never applyData an abort", () => { const switchToChatWindow = sourceWindow( botSrc, "async function switchToChat(chatId) {", "async function startNewChat() {", "switchToChat" ); // Post-run reconcile: the final commit guards the sentinel (inside the poll // loop the sentinel degrades exactly like null — retry — so only this // commit needs the branch). assert.match( switchToChatWindow, /if \(isChatLoadAborted\(refreshed\)\) \{\s*\n\s*showStoreToast\('The chat request timed out\. Please try again\.', 'error', 6000\);\s*\n\s*\} else \{\s*\n\s*applyData\(refreshed\);\s*\n\s*\}/, "the reconcile's final applyData must be abort-guarded: keep the in-memory run view and toast the timeout instead of rendering/caching an empty thread" ); // Cached-path background revalidate: the sentinel is TRUTHY, so it must be // excluded before the truthiness check or it would flow into applyData. assert.match( switchToChatWindow, /if \(!isChatLoadAborted\(fresh\) && fresh && loadToken === aiChatLoadToken && aiCurrentChatId === chatId\) \{\s*\n\s*if \(aiChatHistory === cachedView\) applyData\(fresh\);/, "the background revalidate must exclude the sentinel BEFORE its truthiness check — a truthy sentinel reaching applyData would cache [] over the good cached view" ); }); // ── (f) post-wired-review follow-ups: the sentinel consumers OUTSIDE // switchToChat's three paths, plus the two hardening nits ──────────────────── // adpanel:scheduler-fetch-abort-cache — round 2 guarded switchToChat's three // paths, but the wired review found two more consumers that key on // data && data.messages and would render an empty thread from the truthy but // message-less CHAT_LOAD_ABORTED sentinel: loadChatHistory (the trailing // aiChatHistory = nextHistory assignment wipes the rendered thread, no cache // write) and reloadVisibleChatFromDb (the post-run background reload for a // chat the user navigated back into — after 6 aborted poll attempts the final // commit wipes the VISIBLE thread, cache untouched). The pins below hold // their keep-current-view guards in place, plus the run reconcile's explicit // sentinel exclusion (previously protected only by the dbMessages.length >= // shownCount inequality) and the lowercase-normalized connect-budget lookup. test("loadChatHistory returns before the history assignment on the abort sentinel, keeping the previous thread", () => { const loadChatHistoryWindow = sourceWindow( botSrc, "async function loadChatHistory() {", "function renderChatsList() {", "loadChatHistory" ); // The guard must sit between the token re-check and the data && data.messages // mapping: the sentinel is truthy but has no .messages, so unguarded it // falls into nextHistory = [] and the trailing assignment wipes the // currently rendered thread (4 call sites, no cache write in this flow). assert.match( loadChatHistoryWindow, /const data = await loadChatFromDb\(requestedChatId\);\s*\n\s*if \(loadToken !== aiChatLoadToken \|\| aiCurrentChatId !== requestedChatId\) return;\s*\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*if \(isChatLoadAborted\(data\)\) return;\s*\n[ \t]*if \(data && data\.messages\) \{/, "loadChatHistory must return on the abort sentinel BEFORE the mapping and the trailing aiChatHistory = nextHistory assignment — the existing aiChatHistory (the previous view) is kept and a later reload re-reads the DB" ); // The keep is an early return, so the assignment itself stays untouched and // every non-abort path renders exactly as before. const guardAt = loadChatHistoryWindow.indexOf("if (isChatLoadAborted(data)) return;"); const assignAt = loadChatHistoryWindow.indexOf("aiChatHistory = nextHistory;"); assert.notStrictEqual(guardAt, -1, "the sentinel early-return must exist in loadChatHistory"); assert.notStrictEqual(assignAt, -1, "the trailing aiChatHistory = nextHistory assignment must stay"); assert.ok(guardAt < assignAt, "the sentinel early-return must precede the history assignment"); }); test("reloadVisibleChatFromDb breaks the poll on abort and keeps the visible view at the final commit", () => { const reloadWindow = sourceWindow( botSrc, "async function reloadVisibleChatFromDb(chatId) {", "function pushLocalChatMessage(role, content, attachment = null) {", "reloadVisibleChatFromDb" ); // (a) Poll loop: inside it the sentinel would degrade to [] exactly like // null (retry), but each retry re-pays the 15s abort bound within the same // starvation window — break instead of burning the remaining attempts. assert.match( reloadWindow, /data = await loadChatFromDb\(targetId\);\s*\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*if \(isChatLoadAborted\(data\)\) break;\s*\n[ \t]*const msgs = Array\.isArray\(data\?\.messages\) \? data\.messages : \[\];/, "the poll loop must break on the abort sentinel — retrying a 15s-bound fetch inside the same starvation window cannot succeed" ); // (b) Final commit: the sentinel is truthy but has no .messages, so the // unguarded commit renders [] over the thread the user is looking at. The // guard mirrors switchToChat's final commit exactly — toast the timeout in // the abort branch; the messages mapping and renderChatHistory stay in the // else so non-abort failures keep the pre-fix empty-thread commit verbatim. assert.match( reloadWindow, /if \(Number\(aiCurrentChatId\) !== targetId \|\| aiChatLoadToken !== loadToken\) return;\s*\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*if \(isChatLoadAborted\(data\)\) \{\s*\n[ \t]*showStoreToast\('The chat request timed out\. Please try again\.', 'error', 6000\);\s*\n[ \t]*\} else \{[\s\S]*?renderChatHistory\(\);\s*\n[ \t]*\}\s*\n[ \t]*\}/, "the final commit must be abort-guarded (toast + keep the current aiChatHistory/DOM) with the messages mapping and renderChatHistory inside the else — the switchToChat final-commit guard shape, mirrored" ); }); test("the run reconcile excludes the abort sentinel explicitly, not only via the length inequality", () => { const reconcileWindow = sourceWindow( botSrc, "const shownCount = aiChatHistory.length;", "catch (reconcileErr) {", "run reconcile" ); // Sentinel-safety previously relied on dbMessages.length >= shownCount alone // (the sentinel has no .messages, so dbMessages is [] and the inequality is // false while the user is looking at a non-empty thread). The explicit // conjunct protects that invariant against future edits of the comparison. assert.match( reconcileWindow, /const data = await loadChatFromDb\(aiCurrentChatId\);\s*\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*if \(isRunStillVisible\(\) && !isChatLoadAborted\(data\)\) \{\s*\n[ \t]*const dbMessages = Array\.isArray\(data\?\.messages\) \? data\.messages : \[\];\s*\n[ \t]*if \(dbMessages\.length >= shownCount\) \{/, "the reconcile must exclude the sentinel with an explicit isChatLoadAborted conjunct BEFORE the dbMessages.length >= shownCount comparison — on abort keep the in-memory view (the final answer pushed above)" ); });