"use strict"; // Source-level pin for adpanel:scheduler-model-locality in bot.js. // // The scheduler scene's AI-model dropdown (`schedulerAiModelSelect`) used to // persist every selection through saveSelectedAiModelToStorage — the writer // that owns the ACCOUNT-GLOBAL default (both localStorage keys AND the // POST /api/ai/selection backend save). That default is what the interactive // agent chat uses and what the server stamps onto every FUTURE // planner_next_to_agent schedule at create time // (index.js: getSavedAiModelSelectionForUserId), so picking a cheap model for // a one-off scheduled task silently rewrote the user's saved default. // // The fix: the scheduler selector's choice is per-task form state ONLY. It // flows into the agent_prompt create payload (createSchedulerTask sends // payload.provider/model explicitly; the server route normalizes + validates // that explicit selection via normalizeAiModelSelectionPayload + // assertAiProviderReady and — deliberately, per its own comment — never // touches the saved default). The pre-select of the saved default on open is // KEPT: it is a starting suggestion, not a persist. // // The MAIN agent-chat selector (aiModelSelect) keeps its persist behavior — // it IS the owner of the saved default. Its sites // (updateAiModelSelectorState, the send flow, callAiApi) are pinned unchanged // so a future cleanup cannot "simplify" them away by copying the scheduler // removal. // // 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); } // ── (a) the scheduler selector never persists ─────────────────────────────── const schedulerStateWindow = sourceWindow( botSrc, "// adpanel:scheduler-model-locality", "function syncSchedulerAiModelSelectorFromNative(", "updateSchedulerAiModelSelectorState" ); test("updateSchedulerAiModelSelectorState no longer persists the selection", () => { assert.ok( !/saveSelectedAiModelToStorage\s*\(/.test(schedulerStateWindow.replace(/\/\/[^\n]*/g, "")), "the scheduler selector's state update must not call saveSelectedAiModelToStorage — that writer owns the ACCOUNT-GLOBAL default (localStorage keys + POST /api/ai/selection) used by the interactive agent chat and bound into every future planner_next_to_agent schedule" ); assert.match( schedulerStateWindow, /function updateSchedulerAiModelSelectorState\(\) \{/, "the persist parameter is removed entirely — a dead persist knob on the scheduler surface is drift bait" ); }); test("syncSchedulerAiModelSelectorFromNative no longer threads a persist flag", () => { const syncWindow = sourceWindow( botSrc, "function syncSchedulerAiModelSelectorFromNative(", "async function populateSchedulerAiModelSelector() {", "syncSchedulerAiModelSelectorFromNative" ); assert.match( syncWindow, /function syncSchedulerAiModelSelectorFromNative\(\) \{/, "the persist parameter must be gone from the scheduler sync" ); assert.match( syncWindow, /updateSchedulerAiModelSelectorState\(\);/, "it must call the state update without persist arguments" ); assert.ok( !syncWindow.includes("persist"), "no persist flag may remain anywhere in the scheduler sync" ); }); test("populateSchedulerAiModelSelector keeps the saved-default PRE-SELECT but never persists it", () => { const populateWindow = sourceWindow( botSrc, "async function populateSchedulerAiModelSelector() {", "async function loadSchedulerPlannerPreview() {", "populateSchedulerAiModelSelector" ); // The pre-select is a starting suggestion and stays. assert.match( populateWindow, /previouslySelectedModel = backendSelectedModel \|\| loadSelectedAiModelFromStorage\(\);/, "the saved default must keep pre-selecting on open (starting suggestion)" ); assert.match( populateWindow, /if \(previouslySelectedModel && optionValues\.includes\(previouslySelectedModel\)\) \{/, "the pre-select application must stay" ); // But opening/populating the dropdown must not write the default back. assert.ok( !/saveSelectedAiModelToStorage\s*\(/.test(populateWindow.replace(/\/\/[^\n]*/g, "")), "populating the scheduler dropdown must not route through saveSelectedAiModelToStorage — merely opening the scene must not queue a backend save of the default" ); }); test("the scheduler option-click and change handlers update state without persisting", () => { const handlersWindow = sourceWindow( botSrc, "if (schedulerAiModelOptions && schedulerAiModelSelect) {", "if (schedulerModal) {", "schedulerAiModel handlers" ); assert.match( handlersWindow, /updateSchedulerAiModelSelectorState\(\);/, "the option-click handler must call the state update without persist arguments" ); assert.match( handlersWindow, /addEventListener\('change', \(\) => updateSchedulerAiModelSelectorState\(\)\)/, "the native change listener must call the state update without persist arguments" ); assert.ok( !handlersWindow.includes("persist"), "no persist flag may remain in the scheduler select handlers" ); assert.ok( !botSrc.includes("updateSchedulerAiModelSelectorState({ persist"), "no caller anywhere may pass a persist argument to the scheduler state update" ); }); // ── (b) the in-form choice still governs its own agent_prompt task ────────── const createWindow = sourceWindow( botSrc, "async function createSchedulerTask() {", "function resetSchedulerForm() {", "createSchedulerTask" ); test("createSchedulerTask sends the scheduler select's model explicitly in the agent_prompt payload", () => { // The payload decision is EXPLICIT SEND: since the scheduler selection no // longer persists, an omitted provider/model would make the server's // agent_prompt branch fall back to... nothing to stamp — the server accepts // and validates an explicitly-sent selection (index.js: // normalizeAiModelSelectionPayload reads payload.provider/model directly, // then assertAiProviderReady) and deliberately does NOT fall back to the // saved default here, so the client must always carry the in-form choice. assert.match( createWindow, /const modelValue = schedulerAiModelSelect\?\.value \|\| '';/, "the agent_prompt branch must read the scheduler dropdown's value" ); assert.match( createWindow, /const \{ providerId, modelName \} = decodeAiModelSelection\(modelValue\);/, "the value must be decoded into provider/model" ); assert.match( createWindow, /if \(!providerId \|\| !modelName\) \{\s*\n\s*alert\('Please select an AI model\.'\);/, "a missing in-form selection must hard-stop the create (it can no longer fall back to the saved default)" ); assert.match( createWindow, /payload\.provider = providerId;\s*\n\s*payload\.model = modelName;/, "the selected provider/model must be sent explicitly in the create payload — the server route normalizes + validates that explicit selection and stamps it onto the task without touching the saved default" ); }); // ── (c) the main agent-chat selector's persist is UNTOUCHED ───────────────── test("the main chat selector still owns and persists the saved default", () => { const mainStateWindow = sourceWindow( botSrc, "function updateAiModelSelectorState(", "function syncAiModelSelectorFromNative(", "updateAiModelSelectorState" ); assert.match( mainStateWindow, /if \(persist && selectedOption && !selectedOption\.disabled && isPersistableAiModelSelection\(aiModelSelect\.value\)\) \{\s*\n\s*saveSelectedAiModelToStorage\(aiModelSelect\.value\);/, "the MAIN selector's persist site is the owner of the account-global default and must stay — the scheduler removal must not be copy-pasted onto it" ); }); test("the main selector persists locally and submits its exact model in the live job", () => { const send = sourceWindow(botSrc, "async function sendAiMessage(", "async function refreshChatsListAfterRun(", "sendAiMessage"); assert.match(send, /window\.adpanelAgentLive\.createRun\(\{[\s\S]*?provider: providerId, model: modelName,[\s\S]*?saveSelectedAiModelToStorage\(modelValue\)/); assert.doesNotMatch(send, /saveSelectedAiModelToBackendNow/); const router = fs.readFileSync(require.resolve("../routes/agent-live"), "utf8"); assert.match(router, /await insertAiAgentChatJob[^\n]+\n\s+await saveSelection\(user\.id, job\.provider, job\.model\)/); // callAiApi keeps its persist too. const callApiAt = botSrc.indexOf("saveSelectedAiModelToStorage(modelValue);\n\n const config = AI_PROVIDERS[providerId];"); assert.notStrictEqual( callApiAt, -1, "callAiApi must keep its persist of the main selector's model" ); // Census: the writer must be called from EXACTLY the three main-selector // sites — no scheduler site may have crept back in. const callSites = botSrc.match(/(?